SpringMVC-异常处理器
1.基于配置的异常处理
SpringMVC提供了一个处理控制器方法执行过程中所出现的异常的接口:HandlerExceptionResolver HandlerExceptionResolver接口的实现类有:DefaultHandlerExceptionResolver和 SimpleMappingExceptionResolver SpringMVC提供了自定义的异常处理器SimpleMappingExceptionResolver,使用方式:
在SpringMVC.xml中配置异常处理器
<!--配置异常处理器--> <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> <property name="exceptionMappings"> <props> <!-- properties的键表示处理器方法执行过程中出现的异常 properties的值表示若出现指定异常时,设置一个新的视图名称,跳转到指定页面 --> <prop key="java.lang.ArithmeticException">error</prop> </props> </property> <!--exceptionAttribute属性设置一个属性名,将出现的异常处理信息在请求域中共享--> <property name="exceptionAttribute" value="ex"></property> </bean>
创建控制器(有一个数学异常)
创建出现错误时跳转的页面
在主页写出跳转链接
页面显示
2、基于注解的异常处理
写出注解的控制器方法
编写异常处理方法类
package com.hrf.SpringMVC.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; @ControllerAdvice public class ExceptionController { //@ExceptionHandler用于设置所标识方法处理的异常 @ExceptionHandler(ArithmeticException.class) //ex标识当前请求处理中出现的异常对象 public String handlerArithmeticException(Exception ex, Model model){ model.addAttribute("ex",ex); return "error"; } }
结果于配置文件相同