SpringMVC处理异常:
1 使用@ExceptionHandler注解
只有ModelAndView可以携带错误信息
@ExceptionHandler public ModelAndView handleException(Exception ex) {
System.out.println("出现异常:" + ex);
ModelAndView mv = new ModelAndView(); mv.setViewName("error");//转到error.jsp mv.addObject("exception", ex);
return mv; }
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" isErrorPage="true"%>
<!-- 打印异常信息 -->
<%=exception.getMessage() %>
${exception.message}
2 使用@ExceptionHandler处理特定类型的异常
public class LackParamException extends ServletException{
private static final long serialVersionUID = 1L;
public LackParamException() { super("缺少参数"); } public LackParamException(String msg) { super(msg); } }
@ExceptionHandler(LackParamException.class) public ModelAndView handleException(Exception ex) { System.out.println("出现异常:" + ex); ModelAndView mv = new ModelAndView(); mv.setViewName("error"); mv.addObject("exception", ex); return mv; } @RequestMapping("test_exception") public String testException(String str) throws LackParamException { if(StringUtils.isEmpty(str)) { throw new LackParamException(); } return "success"; }
3 使用@ControllerAdvice织入全局异常
//异常切面:将本类内部的@ExceptionHandler方法织入到所有的@RequestMapping方法
@ControllerAdvice public class MyExceptionHandler {
@ExceptionHandler(Exception.class) public ModelAndView handleException(Exception ex) { System.out.println("出现全局异常:" + ex); ModelAndView mv = new ModelAndView(); mv.setViewName("error"); mv.addObject("exception", ex); return mv; } }
<!-- 扫描异常处理 --> <context:component-scan base-package="com.roxy.springmvc.exception">
</context:component-scan>