码迷,mamicode.com
首页 > 编程语言 > 详细

spring mvc 异常统一处理 【转】

时间:2016-08-05 15:28:41      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:

SpringMVC 提供的异常处理主要有两种方式,一种是直接实现自己的HandlerExceptionResolver,另一种是使用注解的方式实现一个专门用于处理异 常的Controller——ExceptionHandler。前者当发生异常时,页面会跳到指定的错误页面,后者同样,只是后者会在每个 controller中都需要加入重复的代码。如何进行简单地统一配置异常,使得发生普通错误指定到固定的页面,ajax发生错直接通过js获取,展现给 用户,变得非常重要。下面先介绍下2种异常处理方式,同时,结合现有的代码,让其支持ajax方式,实现spring MVC web系统的异常统一处理。

 

1、实现自己的HandlerExceptionResolver,HandlerExceptionResolver是一个接 口,springMVC本身已经对其有了一个自身的实现——DefaultExceptionResolver,该解析器只是对其中的一些比较典型的异常 进行了拦截处理 。

 

Java代码  技术分享
  1. import javax.servlet.http.HttpServletRequest;  
  2. import javax.servlet.http.HttpServletResponse;  
  3. import org.springframework.web.servlet.HandlerExceptionResolver;  
  4. import org.springframework.web.servlet.ModelAndView;  
  5. public class ExceptionHandler implements HandlerExceptionResolver {  
  6.     @Override  
  7. public ModelAndView resolveException(HttpServletRequest request,  
  8.         // TODO Auto-generated method stub  
  9. return new ModelAndView("exception");  
  10.   
  11. }  

 

 上述的resolveException的第4个参数表示对哪种类型的异常进行处理,如果想同时对多种异常进行处理,可以把它换成一个异常数组。

定义了这样一个异常处理器之后就要在applicationContext中定义这样一个bean对象,如:

Xml代码  技术分享
  1. <bean id="exceptionResolver" class="com.tiantian.xxx.web.handler.ExceptionHandler"/>  

 

2、使用@ExceptionHandler进行处理

使用@ExceptionHandler进行处理有一个不好的地方是进行异常处理的方法必须与出错的方法在同一个Controller里面

如:

Java代码  技术分享
  1. import org.springframework.stereotype.Controller;  
  2. import org.springframework.web.bind.annotation.ExceptionHandler;  
  3. import org.springframework.web.bind.annotation.RequestMapping;  
  4. import com.tiantian.blog.web.servlet.MyException;  
  5. @Controller  
  6. public class GlobalController {  
  7.       
  8. /** 
  9.      * 用于处理异常的 
  10.      * @return 
  11.      */  
  12. @ExceptionHandler({MyException.class})  
  13. public String exception(MyException e) {  
  14.         e.printStackTrace();  
  15. return "exception";  
  16.       
  17. @RequestMapping("test")  
  18. public void test() {  
  19. throw new MyException("出错了!");  
  20.       
  21. }  

 

这里在页面上访问test方法的时候就会报错,而拥有该test方法的Controller又拥有一个处理该异常的方法,这个时候处理异常的方法就会被调用。当发生异常的时候,上述两种方式都使用了的时候,第一种方式会将第二种方式覆盖。

 

3. 针对Spring MVC 框架,修改代码实现普通异常及ajax异常的全部统一处理解决方案。

在上篇文章中,关于spring异常框架体系讲的非常清楚,Dao层,以及sevcie层异常我们建立如下异常。

Java代码  技术分享
  1. package com.jason.exception;  
  2. public class BusinessException extends Exception {  
  3.     private static final long serialVersionUID = 1L;  
  4.     public BusinessException() {  
  5. // TODO Auto-generated constructor stub  
  6.   
  7. public BusinessException(String message) {  
  8. super(message);  
  9. // TODO Auto-generated constructor stub  
  10.   
  11. public BusinessException(Throwable cause) {  
  12. super(cause);  
  13. // TODO Auto-generated constructor stub  
  14.   
  15. public BusinessException(String message, Throwable cause) {  
  16. super(message, cause);  
  17. // TODO Auto-generated constructor stub  
  18.   
  19. }  

 

Java代码  技术分享
  1. package com.jason.exception;  
  2. public class SystemException extends RuntimeException {  
  3.     private static final long serialVersionUID = 1L;  
  4.     public SystemException() {  
  5. // TODO Auto-generated constructor stub  
  6.   
  7. /** 
  8.      * @param message 
  9.      */  
  10. public SystemException(String message) {  
  11. super(message);  
  12. // TODO Auto-generated constructor stub  
  13.   
  14. /** 
  15.      * @param cause 
  16.      */  
  17. public SystemException(Throwable cause) {  
  18. super(cause);  
  19. // TODO Auto-generated constructor stub  
  20.   
  21. /** 
  22.      * @param message 
  23.      * @param cause 
  24.      */  
  25. public SystemException(String message, Throwable cause) {  
  26. super(message, cause);  
  27. // TODO Auto-generated constructor stub  
  28.   
  29. }  

 

在sevice层我们需要将建立的异常抛出,在controller层,我们需要捕捉异常,将其转换直接抛出,抛出的异常,希望能通过我们自己统一的配置,支持普通页面和ajax方式的页面处理,下面就详细讲一下步骤。

(1) 配置web.xml 文件,将常用的异常进行配置,配置文件如下403,404,405,500页面都配置好了:

 

Xml代码  技术分享
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">  
  3. <display-name>SpringJSON</display-name>  
  4. <context-param>    
  5. <param-name>webAppRootKey</param-name>    
  6. <param-value>SpringJSON.webapp.root</param-value>    
  7. </context-param>   
  8. <!--******************************** -->  
  9.     既有log4j也有commons-logging,这里只是强制转换为log4j!并且,log4j的配置文件只能放在classpath根路径。  
  10.     在classpath根路径****** -->  
  11. <!--******************************* -->  
  12. <context-param>  
  13. <param-name>log4jConfigLocation</param-name>  
  14. <param-value>classpath:log4j.xml</param-value>  
  15. </context-param>  
  16.     <!--Spring默认刷新Log4j配置文件的间隔,单位为millisecond,可以不设置 -->  
  17. <context-param>  
  18. <param-name>log4jRefreshInterval</param-name>  
  19. <param-value>60000</param-value>  
  20. </context-param>  
  21.     <!--******************************** -->  
  22. <!--*******spring bean的配置******** -->  
  23.     统领service层,dao层,datasource层,及国际化层-->  
  24. <!--******************************* -->  
  25. <context-param>  
  26. <param-name>contextConfigLocation</param-name>  
  27. <param-value>classpath:applicationContext.xml</param-value>  
  28. </context-param>  
  29.     <listener>  
  30. <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>  
  31. </listener>  
  32. <listener>  
  33. <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
  34. </listener>  
  35. <listener>  
  36. <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>  
  37. </listener>  
  38. <!--******************************** -->  
  39. <!--*******字符集 过滤器************ -->  
  40. <!--******************************* -->  
  41. <filter>  
  42. <filter-name>CharacterEncodingFilter</filter-name>  
  43. <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>  
  44. <init-param>  
  45. <param-name>encoding</param-name>  
  46. <param-value>UTF-8</param-value>  
  47. </init-param>  
  48. <init-param>  
  49. <param-name>forceEncoding</param-name>  
  50. <param-value>true</param-value>  
  51. </init-param>  
  52. </filter>  
  53. <filter-mapping>  
  54. <filter-name>CharacterEncodingFilter</filter-name>  
  55. <url-pattern>/*</url-pattern>  
  56. </filter-mapping>  
  57.     <!-- Spring 分发器,设置MVC配置信息 -->  
  58. <servlet>  
  59. <servlet-name>SpringJSON</servlet-name>  
  60. <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
  61. <init-param>  
  62. <param-name>contextConfigLocation</param-name>  
  63. <param-value>classpath:spring/applicationContext-servlet.xml</param-value>  
  64. </init-param>  
  65. <load-on-startup>1</load-on-startup>  
  66. </servlet>  
  67. <!--******************************** -->  
  68.     同时,可骗过搜索引擎,增加被收录的概率 。真正的静态网页可以用.htm,以避免被框架拦截-->  
  69. <!--******************************* -->  
  70. <servlet-mapping>  
  71. <servlet-name>SpringJSON</servlet-name>  
  72. <url-pattern>*.html</url-pattern>  
  73. </servlet-mapping>  
  74. <welcome-file-list>  
  75. <welcome-file>index.html</welcome-file>  
  76. </welcome-file-list>  
  77. <error-page>  
  78. <error-code>403</error-code>  
  79. <location>/WEB-INF/pages/error/403.jsp</location>  
  80. </error-page>  
  81. <error-page>  
  82. <error-code>404</error-code>  
  83. <location>/WEB-INF/pages/error/404.jsp</location>  
  84. </error-page>  
  85. <error-page>  
  86. <error-code>405</error-code>  
  87. <location>/WEB-INF/pages/error/405.jsp</location>  
  88. </error-page>  
  89. <error-page>  
  90. <error-code>500</error-code>  
  91. <location>/WEB-INF/pages/error/500.jsp</location>  
  92. </error-page>  
  93. </web-app>  

 2.建立相应的error页面,其中errorpage.jsp 是业务异常界面

Html代码  技术分享
  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8" isErrorPage="true"%>  
  2. <%@ include file="/common/taglibs.jsp"%>  
  3. >  
  4. <html xmlns="http://www.w3.org/1999/xhtml">  
  5. <head>  
  6. <title>error page</title>  
  7. <script type="text/javascript">  
  8.             $("#center-div").center(true);  
  9.     </script>  
  10. </head>  
  11. <body style="margin: 0;padding: 0;#f5f5f5;">  
  12. <div id="center-div">  
  13. <table style="height: 100%; width: 600px; text-align: center;">  
  14. <tr>  
  15. <td>  
  16. <img width="220" height="393" src="${basePath}/images/common/error.png" style="float: left; padding-right: 20px;" alt="" />  
  17. <%= exception.getMessage()%>  
  18. <style="line-height: 12px; color: #666666; font-family: Tahoma, ‘宋体‘; font-size: 12px; text-align: left;">  
  19. <href="javascript:history.go(-1);">返回</a>!!!  
  20. </p>  
  21. </td>  
  22. </tr>  
  23. </table>  
  24. </div>  
  25. </body>  
  26. </html>  

技术分享
 errorpage.jsp代码内容如下:

Html代码  技术分享
  1.   

 

3.分析spring源码,自定义SimpleMappingExceptionResolver覆盖spring的SimpleMappingExceptionResolver。

关于SimpleMappingExceptionResolver的用法,大家都知道,只需在application-servlet.xml中做如下的配置

Java代码  技术分享
  1. "exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">  
  2. "exceptionMappings">   
  3.           <prop key="com.jason.exception.SystemException">error/500</prop>   
  4. "com.jason.exception.BusinessException">error/errorpage</prop>  
  5. "java.lang.exception">error/500</prop>  
  6.        </props>   
  7.     </bean>  

 观察SimpleMappingExceptionResolver,我们可以复写其doResolveException(HttpServletRequest request,
            HttpServletResponse response, Object handler, Exception ex)方法,通过修改该方法实现普通异常和ajax异常的处理,代码如下:

 

Java代码  技术分享
  1. package com.jason.exception;  
  2. import java.io.IOException;  
  3. import java.io.PrintWriter;  
  4. import javax.servlet.http.HttpServletRequest;  
  5. import javax.servlet.http.HttpServletResponse;  
  6. import org.springframework.web.servlet.ModelAndView;  
  7. import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;  
  8. public class CustomSimpleMappingExceptionResolver extends  
  9.   
  10. @Override  
  11. protected ModelAndView doResolveException(HttpServletRequest request,  
  12.         // Expose ModelAndView for chosen error view.  
  13.         if (viewName != null) {// JSP格式返回  
  14. if (!(request.getHeader("accept").indexOf("application/json") > -1 || (request  
  15. "X-Requested-With")!= null && request  
  16. "X-Requested-With").indexOf("XMLHttpRequest") > -1))) {  
  17. // 如果不是异步请求  
  18. // Apply HTTP status code for error views, if specified.  
  19. // Only apply it if we‘re processing a top-level request.  
  20.                 if (statusCode != null) {  
  21.                 }  
  22. return getModelAndView(viewName, ex, request);  
  23. else {// JSON格式返回  
  24. try {  
  25.                     writer.write(ex.getMessage());  
  26.                 } catch (IOException e) {  
  27.                 }  
  28. return null;  
  29.             }  
  30. else {  
  31. return null;  
  32.     }  
  33. }  

 

配置application-servelt.xml如下:(代码是在大的工程中提炼出来的,具体有些东西这里不做处理)

 

Java代码  技术分享
  1. "1.0" encoding="UTF-8"?>  
  2. "http://www.springframework.org/schema/beans"  
  3. "http://www.w3.org/2001/XMLSchema-instance"  
  4. "http://www.springframework.org/schema/mvc"  
  5. "http://www.springframework.org/schema/p"  
  6. "http://www.springframework.org/schema/context"  
  7. "http://www.springframework.org/schema/aop"  
  8. "http://www.springframework.org/schema/tx"  
  9. //www.springframework.org/schema/beans  
  10. //www.springframework.org/schema/beans/spring-beans.xsd  
  11. //www.springframework.org/schema/context   
  12. //www.springframework.org/schema/context/spring-context.xsd  
  13. //www.springframework.org/schema/aop   
  14. //www.springframework.org/schema/aop/spring-aop.xsd  
  15. //www.springframework.org/schema/tx   
  16. //www.springframework.org/schema/tx/spring-tx.xsd  
  17. //www.springframework.org/schema/mvc   
  18. //www.springframework.org/schema/mvc/spring-mvc.xsd  
  19. //www.springframework.org/schema/context   
  20. //www.springframework.org/schema/context/spring-context.xsd">  
  21.     <!-- 配置静态资源,直接映射到对应的文件夹,不被DispatcherServlet处理 -->  
  22. "/images/**" location="/images/"/>  
  23. "/css/**" location="/css/"/>  
  24. "/js/**" location="/js/"/>  
  25. "/html/**" location="/html/"/>  
  26. "/common/**" location="/common/"/>  
  27.     <!-- Configures the @Controller programming model -->  
  28.       
  29.     <context:component-scan base-package="com.jason.web"/>  
  30.     <bean id="captchaProducer" name= "captchaProducer" class="com.google.code.kaptcha.impl.DefaultKaptcha">    
  31. "config">    
  32. class="com.google.code.kaptcha.util.Config">    
  33.                     <props>    
  34. "kaptcha.image.width">300</prop>  
  35. "kaptcha.image.height">60</prop>  
  36. "kaptcha.textproducer.char.string">0123456789</prop>  
  37. "kaptcha.textproducer.char.length">4</prop>   
  38.                 </constructor-arg>    
  39.         </property>    
  40.     <!--   
  41. "captchaProducer" class="com.google.code.kaptcha.impl.DefaultKaptcha">    
  42. "config">    
  43. class="com.google.code.kaptcha.util.Config">    
  44.                     <props>    
  45. "kaptcha.border">no</prop>    
  46. "kaptcha.border.color">105,179,90</prop>    
  47. "kaptcha.textproducer.font.color">red</prop>    
  48. "kaptcha.image.width">250</prop>    
  49. "kaptcha.textproducer.font.size">90</prop>    
  50. "kaptcha.image.height">90</prop>    
  51. "kaptcha.session.key">code</prop>    
  52. "kaptcha.textproducer.char.length">4</prop>    
  53. "kaptcha.textproducer.font.names">宋体,楷体,微软雅黑</prop>    
  54.                 </constructor-arg>    
  55.         </property>    
  56.     -->   
  57.     <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">  
  58.      <bean id="exceptionResolver" class="com.jason.exception.CustomSimpleMappingExceptionResolver">  
  59. "exceptionMappings">   
  60.           <prop key="com.jason.exception.SystemException">error/500</prop>   
  61. "com.jason.exception.BusinessException">error/errorpage</prop>  
  62. "java.lang.exception">error/500</prop>  
  63.        </props>   
  64.     </bean>  
  65.     <!--启动Spring MVC的注解功能,设置编码方式,防止乱码-->  
  66. class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">  
  67. "messageConverters">     
  68.              <bean class = "org.springframework.http.converter.StringHttpMessageConverter">     
  69. "supportedMediaTypes">  
  70.                           <value>text/html;charset=UTF-8</value>     
  71.                 </property>     
  72.          </list>     
  73.     </bean>  
  74.     <!--默认的就是JstlView所以这里就不用配置viewClass -->  
  75. "viewResolver"  class="org.springframework.web.servlet.view.InternalResourceViewResolver"   
  76. "/WEB-INF/pages/"   
  77. ".jsp" />  
  78. </beans>  

 

至此,整个异常体系架构配置成功,当整个工程出现异常时,页面会根据web.xml跳转到指定的页面。当在系统应用中出现普通异常时,根据是系统异常还是 应用异常,跳到相应的界面,当ajax异常时,在ajax的error中可直接获得异常。普通的异常我们都配置好了界面,系统会自动跳转,主要看一下 ajax的方式。

具体演示如下:

在登录界面建立如下的controller

Java代码  技术分享
  1. package com.jason.web;  
  2. import java.io.IOException;  
  3. import java.util.Date;  
  4. import java.util.HashMap;  
  5. import java.util.Map;  
  6. import javax.servlet.http.HttpServletRequest;  
  7. import javax.servlet.http.HttpServletResponse;  
  8. import javax.servlet.http.HttpSession;  
  9. import org.apache.commons.lang.StringUtils;  
  10. import org.springframework.beans.factory.annotation.Autowired;  
  11. import org.springframework.stereotype.Controller;  
  12. import org.springframework.web.bind.annotation.RequestMapping;  
  13. import org.springframework.web.bind.annotation.ResponseBody;  
  14. import org.springframework.web.servlet.ModelAndView;  
  15. import com.jason.domain.User;  
  16. import com.jason.exception.BusinessException;  
  17. import com.jason.service.UserService;  
  18. import com.jason.util.Constants;  
  19. import com.jason.web.dto.LoginCommand;  
  20. @Controller  
  21. public class LoginController {  
  22.     @Autowired  
  23. private UserService userService;  
  24.     /** 
  25.      * jump into the login page 
  26.      *  
  27.      * @return 
  28.      * @throws BusinessException 
  29.      * @throws 
  30.      * @throws BusinessException 
  31.      */  
  32. @RequestMapping(value = "/index.html")  
  33. public String loginPage() throws BusinessException {  
  34. return Constants.LOGIN_PAGE;  
  35.   
  36. /** 
  37.      * get the json object 
  38.      *  
  39.      * @return 
  40.      * @throws Exception 
  41.      */  
  42. @RequestMapping(value = "/josontest.html")  
  43. public @ResponseBody  
  44. throws BusinessException {  
  45. new HashMap<String, Object>();  
  46. try {  
  47. "content", "123");  
  48. "result", true);  
  49. "account", 1);  
  50. throw new Exception();  
  51. catch (Exception e) {  
  52. throw new BusinessException("detail of ajax exception information");  
  53.     }  
  54.     /** 
  55.      * login in operation 
  56.      *  
  57.      * @param request 
  58.      * @param loginCommand 
  59.      * @return 
  60.      * @throws IOException 
  61.      */  
  62. @RequestMapping(value = "/login.html")  
  63. public ModelAndView loginIn(HttpServletRequest request,  
  64.             throws IOException {  
  65.         boolean isValidUser = userService.hasMatchUser(  
  66.         boolean isValidateCaptcha = validateCaptcha(request, loginCommand);  
  67.         ModelAndView modeview = new ModelAndView(Constants.LOGIN_PAGE);  
  68.         if (!isValidUser) {  
  69. // if have more information,you can put a map to modelView,this use  
  70. // internalization  
  71. "loginError", "login.user.error");  
  72. return modeview;  
  73. else if (!isValidateCaptcha) {  
  74. // if have more information,you can put a map to modelView,this use  
  75. // internalization  
  76. "loginError", "login.user.kaptchaError");  
  77. return modeview;  
  78. else {  
  79.                     .getUserName());  
  80.             user.setLastVisit(new Date());  
  81.             userService.loginSuccess(user);  
  82.             // we can also use  
  83.             String uri = (String) request.getSession().getAttribute(  
  84.             if (uri != null  
  85.                             Constants.CAPTCHA_IMAGE)) {  
  86.             }  
  87. return new ModelAndView(Constants.FRONT_MAIN_PAGE);  
  88.     }  
  89.     /** 
  90.      * logout operation 
  91.      *  
  92.      * @param request 
  93.      * @param response 
  94.      * @return 
  95.      */  
  96. @RequestMapping(value = "/logout.html")  
  97. public ModelAndView logout(HttpServletRequest request,  
  98.   
  99. /* 
  100.          * HttpServletRequest.getSession(ture) equals to 
  101.          * HttpServletRequest.getSession() means a new session created if no 
  102.          * session exists request.getSession(false) means if session exists get 
  103.          * the session,or value null 
  104.          */  
  105. false);  
  106.         if (session != null) {  
  107.         }  
  108.         return new ModelAndView("redirect:/index.jsp");  
  109.   
  110. /** 
  111.      * check the Captcha code 
  112.      *  
  113.      * @param request 
  114.      * @param command 
  115.      * @return 
  116.      */  
  117. protected Boolean validateCaptcha(HttpServletRequest request, Object command) {  
  118.                 com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);  
  119.         if (!StringUtils.equalsIgnoreCase(captchaId, response)) {  
  120. return false;  
  121.         return true;  
  122. }  

 首先看一下ajax的方式,在controller中我们认为让ajax抛出一样,在页面中我们采用js这样调用

Js代码  技术分享
  1. function ajaxTest()  
  2.         $.ajax( {  
  3. ‘GET‘,  
  4. //contentType : ‘application/json‘,     
  5. ‘${basePath}/josontest.html‘,     
  6. false,//禁止ajax的异步操作,使之顺序执行。  
  7. ‘json‘,  
  8. function(data,textStatus){  
  9.             },  
  10. function(data,textstatus){  
  11.             }  
  12.     }  

 当抛出异常是,我们在js的error中采用 alert(data.responseText);将错误信息弹出,展现给用户,具体页面代码如下:

Html代码  技术分享
  1. <%@ page language="java" contentType="text/html; charset=UTF-8"  
  2. pageEncoding="UTF-8"%>  
  3. <%@ include file="/common/taglibs.jsp"%>  
  4. >  
  5. <html>  
  6. <head>  
  7. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
  8. <title>spring login information</title>  
  9. <script type="text/javascript">  
  10.     {  
  11.             type : ‘GET‘,  
  12.             url : ‘${basePath}/josontest.html‘,     
  13.             dataType : ‘json‘,  
  14.                 alert(JSON.stringify(data));  
  15.             error : function(data,textstatus){  
  16.             }  
  17.     }  
  18. </script>  
  19. </head>  
  20. <body>  
  21. <table cellpadding="0" cellspacing="0" style="width:100%;">  
  22. <tr>  
  23. <td rowspan="2" style="width:30px;">  
  24. </td>  
  25. <td style="height:72px;">  
  26. <div>  
  27.               </div>  
  28. <div>  
  29.               </div>  
  30. <div>  
  31. <href="${basePath}/backendmain.html">后台管理</a>  
  32. </div>  
  33. </td>  
  34. <td style="height:72px;">  
  35. <div>  
  36. <input type=button value="Ajax Exception Test" onclick="ajaxTest();"></input>  
  37. </div>  
  38. </td>  
  39. <td>  
  40. <div>  
  41. <href="${basePath}/logout.html">退出</a>  
  42. </div>  
  43. </td>  
  44. </tr>  
  45. </table>  
  46. </body>  
  47. </html>  

 验证效果:

 


技术分享
 至此,ajax方式起了作用,整个系统的异常统一处理方式做到了统一处理。我们在开发过程中无需关心,异常处理配置了。

SpringMVC 提供的异常处理主要有两种方式,一种是直接实现自己的HandlerExceptionResolver,另一种是使用注解的方式实现一个专门用于处理异 常的Controller——ExceptionHandler。前者当发生异常时,页面会跳到指定的错误页面,后者同样,只是后者会在每个 controller中都需要加入重复的代码。如何进行简单地统一配置异常,使得发生普通错误指定到固定的页面,ajax发生错直接通过js获取,展现给 用户,变得非常重要。下面先介绍下2种异常处理方式,同时,结合现有的代码,让其支持ajax方式,实现spring MVC web系统的异常统一处理。

 

http://gaojiewyh.iteye.com/blog/1297746

spring mvc 异常统一处理 【转】

标签:

原文地址:http://www.cnblogs.com/yucongblog/p/5741036.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!