SpringMVC:异常处理器
1.基于配置的异常处理
SpringMVC提供了一个处理控制器方法执行过程中所出现的异常的接口:HandlerExceptionResolver
HandlerExceptionResolver接口的实现类有:DefaultHandlerExceptionResolver和SimpleMappingExceptionResolver
SpringMVC提供了自定义的异常处理器SimpleMappingExceptionResolver,使用方式:
<!--配置异常处理-->
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<!--
properties的键表示处理器方法执行过程中出现的异常
properties的值表示若出现指定异常时,设置一个新的视图名称,跳
转到指定页面
-->
<prop key="java.lang.ArithmeticException">error</prop>
</props>
</property>
<!--设置将异常信息共享在请求域中的键-->
<property name="exceptionAttribute" value="ex"></property>
</bean>
控制器(有错误)
//异常处理
@RequestMapping("/teste")
public String teste(){
System.out.println(2/0);
return "success";
}
超链接到teste时,跳转到error.html
<body>
出现错误
<p th:text="${ex}"></p>
</body>
2.基于注解的异常处理
//@ControllerAdvice将当前类标识为异常处理的组件
@ControllerAdvice
public class ExceptionController {
//@ExceptionHandler用于设置所标识方法处理的异常
@ExceptionHandler(value ={ArithmeticException.class,NullPointerException.class})
public String testException(Exception ex, Model model){
//ex表示当前请求处理中出现的异常对象
model.addAttribute("ex",ex);
return "error";
}
阅读剩余
版权声明:
作者:Tin
链接:http://www.tinstu.com/1201.html
文章版权归作者所有,未经允许请勿转载。
THE END