springmvc中自带了一个异常处理器叫SimpleMappingExceptionResolver,该处理器实现了HandlerExceptionResolver 接口,全局异常处理器都需要实现该接口。我们要使用这个自带的异常处理器,
步骤1:在springmvc.xml文件中配置该处理器
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value ="/jsp/"></property> <property name="suffix" value =".jsp"></property> </bean> <!-- springmvc提供的简单异常处理器 --> <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> <!-- 定义默认的异常处理页面 --> <property name="defaultErrorView" value="error"/> <!-- 定义异常处理页面用来获取异常信息的变量名,也可不定义,默认名为exception --> <property name="exceptionAttribute" value="ex"/> <!-- 定义需要特殊处理的异常,这是重要点 --> <property name="exceptionMappings"> <props> <prop key="com.test.validator.entity.GyException">custom_error</prop> </props> <!-- 还可以定义其他的自定义异常 --> </property> </bean>
步骤2:创建异常类
public class GyException extends Exception { /** * */ private static final long serialVersionUID = 1L; private String exception; public GyException() {} public GyException(String exception) { super(exception); this.exception =exception; }
步骤3:抛出异常
@RequestMapping(value="exception") public String ecxeption(HttpServletRequest httpServletRequest , HttpServletResponse httpServletResponse ,User user) throws Exception { if(user.getUserName()==null) { System.out.println("用户名不能为空"); throw new GyException(); } return "custom_error"; }
步骤4:页面获取
${ex}