
spring mvc的异常与文件上传
1.异常:
spring注解版的异常有局部异常和全局异常
1.局部异常对单个controller有效;(在controller类写一个处理异常的方法)
@ExceptionHandler(value={UserException.class})
public String handlerExceptionTest(UserException e ,HttpServletRequest request){
request.setAttribute("msg", "用户不存在"); return "error";
}
2.全局异常对所有的controller有效(在配置文件中配置;用于所有的controller)
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="po.UserException">error</prop>
</props>
</property>
</bean>
//上边两种方法中使用的异常类UserException是我们自己创建的,继承自一个异常类. (我通常extends(继承) RuntimeException或Exception)
2.文件上传
//页面
form表单设置enctype属性
<form action="/SpringOne/login" method="post" enctype="multipart/form-data" class="hehe">
用户名<input type="text" name="name"/>
密码<input type="text" name="pwd"/>
文件 <input type="file" name="attach"/>
<input type="submit" value="提交"/>
</form>
//
在配置文件(xxx-servlet.xml)中配置如下代码:
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="5000000"> </property> </bean>
//controller中
@RequestMapping(value="/login",method=RequestMethod.POST)
public String login(String name,String pwd,HttpSession session,MultipartFile attach) throws UserException, IOException{
boolean flag=true;
if(name!=null && !name.equals("")){
for (User item : list) {
if(name.equals(item.getName())){
//model.addAttribute("user",item);
session.setAttribute("user", item); flag= false; }
}
}
//为true抛出局部异常
if(flag){
throw new UserException();
}
//文件上传
System.out.println(session.getServletContext().getRealPath("/static/upoload")); FileUtils.copyInputStreamToFile(attach.getInputStream(),new File(session.getServletContext().getRealPath("/static/upoload")+File.separator+attach.getOriginalFilename())); return "redirect:/hello"; }