1 基于配置文件的處理 spring-mvc.xml中配置 <!-- 配置文件的異常處理機(jī)制 --> <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> <property name="exceptionAttribute" value="ex"></property> <property name="exceptionMappings"> <props> <prop key="java.lang.Exception">error</prop> </props> </property> </bean> 2 通過實(shí)現(xiàn)HandlerExceptionResolver接口自定義異常處理類 package com.hzlssd.company.controller; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.HandlerExceptionResolver; import org.springframework.web.servlet.ModelAndView; /** * 通過實(shí)現(xiàn)HandlerExceptionResolver接口自定義異常處理類 * @author QY */ public class MyMappingExceptionResolver implements HandlerExceptionResolver{ @Override public ModelAndView resolveException(HttpServletRequest req, HttpServletResponse res, Object obj, Exception ex) { Map<String,Object> model = new HashMap<String,Object>(); model.put("ex",ex); return new ModelAndView("error",model); } } <!-- 注解開啟自定義異常處理類 --> <bean id="exceptionHandler" class="com.hzlssd.company.controller.MyMappingExceptionResolver" /> 3 通過注解的方式自定義異常處理方法,讓可能拋出異常的類繼承該類,從而處理異常 package com.hzlssd.company.controller; import javax.servlet.http.HttpServletRequest; import org.springframework.web.bind.annotation.ExceptionHandler; /** * 通過注解的方式自定義異常處理方法,讓可能拋出異常的類繼承該類,從而處理異常 * @author QY */ public class BaseExceptionAnn{ @ExceptionHandler public String execute(HttpServletRequest request,Exception ex){ request.setAttribute("ex", ex); return "error"; } } 拋出異常類要繼承自定義的類 @Controller @RequestMapping("/login") public class HelloController extends BaseExceptionAnn{ } |
|