Spring MVC 全局异常处理&文件上传

时间:2022-12-13 17:09:59

Spring MVC 全局异常处理

使用SimpleMappingExceptionResolver实现异常处理 

在welcome-servlet.xml进行如下配置:

1 <bean
2         class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
3         <property name="exceptionMappings">
4             <props>
5                 <prop key="cn.jbit.Controler.UserController">error</prop>
6             </props>
7         </property>
8     </bean>

然后注释掉局部异常

1 /*@ExceptionHandler(value={UserException.class})
2  public String handlerException(UserException exception,HttpServletRequest request){
3 
4   request.setAttribute("e",exception);
5   return "error";
6 
7 }*/

最后在error.jsp页面输出

 1 ${exception.message} 

 

Spring MVC 上传文件

1.在welcome-servlet.xml配置MultipartResolver

 

1 <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
2 
3 <property name="maxUploadSize" value="5000000"></property>
4 
5 </bean> 

 

 

2.在add.jsp页面编写文件上传表单页面和控制器

Spring MVC 全局异常处理&文件上传

 

3.在UserController界面接收

 1 @RequestMapping(value = "/addSave", method = RequestMethod.POST)
 2     public String addSave(@Validated User user, BindingResult result,
 3             MultipartFile upload, HttpServletRequest request)
 4             throws IOException {
 5         String uploadFilePath = request.getSession().getServletContext()
 6                 .getRealPath("/statics/upload");
 7         System.out.println(upload.getOriginalFilename());
 8         System.out.println(upload.getContentType());
 9         System.out.println(upload.getName());
10 
11         if (!upload.isEmpty()) {
12             File file = new File(uploadFilePath + File.separator
13                     + upload.getOriginalFilename());
14             FileUtils.copyInputStreamToFile(upload.getInputStream(), file);
15         }
16 
17         userList.put(user.getId(), user);
18         return "redirect:/list";
19     }

 

注:

getOriginalFilename():获取上传文件的原名

getContentType():获取文件MIME类型

getName():获取表单中文件组件的名字