2019独角兽企业重金招聘Python工程师标准>>>
Spring MVC处理异常有3种方式:
(1)使用Spring MVC提供的简单异常处理器SimpleMappingExceptionResolver;
(2)实现Spring的异常处理接口HandlerExceptionResolver 自定义自己的异常处理器;
(3)使用@ExceptionHandler注解实现异常处理。
方法一:SimpleMappingExceptionResolver:
springMVC-servlet.xml
<beanclass="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
定义默认的异常处理页面,当该异常类型的注册时使用
<property name="defaultErrorView" value="error">
</property>
定义异常处理页面用来获取异常信息的变量名,默认名为exception
<propertyname="exceptionAttribute"value="ex"></property>
定义需要特殊处理的异常,用类名或完全路径名作为key,异常也页名作为值
<property name="exceptionMappings">
<props>
<propkey="etc.exception.MyException">error-my</prop>
这里还可以继续扩展对不同异常类型的处理
</props>
</property>
</bean>
方法二:HandlerExceptionResolver
public class MyExceptionHandler{
@ExceptionHandler
public ModelAndView resolveException(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex) {
Map<String, Exception> map = new HashMap<String, Exception>();
map.put("ex",ex);
// 根据获取的Exception参数进行view跳转
if (ex instanceof MyException) {
return new ModelAndView("error-my",map);
} else {
return new ModelAndView("error",map);
}
}
}
定义了这样一个异常处理器之后就要在springMVC-servlet.xml中定义这样一个bean对象,如
<bean id="myExceptionHandler" class="com.tiantian.xxx.web.handler.myExceptionHandler"/>
方法三.使用@ExceptionHandler进行处理
使用@ExceptionHandler进行处理有一个不好的地方是进行异常处理的方法必须与出错的方法在同一个Controller里面
如:
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import com.tiantian.blog.web.servlet.MyException;
@Controller
public class GlobalController {
/**
* 用于处理异常的
* @return
*/
@ExceptionHandler({MyException.class})
public String exception(MyException e) {
System.out.println(e.getMessage());
e.printStackTrace();
return "exception";
}
@RequestMapping("test")
public void test() {
throw new MyException("出错了!");
}
}
参考:
SpringMVC杂记(十七) HandlerMethodArgumentResolver接口应用example