1. 程式人生 > >spring mvc異常統一處理(使用ControllerAdvice註解)

spring mvc異常統一處理(使用ControllerAdvice註解)

1、配置

spring 版本: [html] view plain copy print?在CODE上檢視程式碼片派生到我的程式碼片
  1. <org.springframework-version>4.1.9.RELEASE</org.springframework-version>
<org.springframework-version>4.1.9.RELEASE</org.springframework-version>
spring-servlet.xml,注意必須開啟註解,即xml要有<annotation-driven />
[html] view plain
copy print?在CODE上檢視程式碼片派生到我的程式碼片
  1. <annotation-driven/>
<annotation-driven />
[html] view plain copy print?在CODE上檢視程式碼片派生到我的程式碼片
  1. <?xmlversion="1.0"encoding="UTF-8"?>
  2. <beans:beansxmlns="http://www.springframework.org/schema/mvc"
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:beans="http://www.springframework.org/schema/beans"
  4.     xmlns:context="http://www.springframework.org/schema/context"
  5.     xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd  
  6.         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd  
  7.         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
  8.     <!-- DispatcherServlet Context: defines this servlet's request-processing   
  9.         infrastructure -->
  10.     <!-- Enables the Spring MVC @Controller programming model -->
  11.     <annotation-driven/>
  12.     <!-- Handles HTTP GET requests for /resources/** by efficiently serving   
  13.         up static resources in the ${webappRoot}/resources directory -->
  14.     <resourcesmapping="/resources/**"location="/resources/"/>
  15.     <!-- Resolves views selected for rendering by @Controllers to .jsp resources   
  16.         in the /WEB-INF/views directory -->
  17.     <beans:bean
  18.         class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  19.         <beans:propertyname="prefix"value="/WEB-INF/views/"/>
  20.         <beans:propertyname="suffix"value=".jsp"/>
  21.     </beans:bean>
  22.     <context:component-scanbase-package="org.as.asjee"use-default-filters="false">
  23.         <context:include-filtertype="annotation"expression="org.springframework.stereotype.Controller"/>
  24.     </context:component-scan>
  25. </beans:beans>
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

	<!-- DispatcherServlet Context: defines this servlet's request-processing 
		infrastructure -->

	<!-- Enables the Spring MVC @Controller programming model -->
	<annotation-driven />

	<!-- Handles HTTP GET requests for /resources/** by efficiently serving 
		up static resources in the ${webappRoot}/resources directory -->
	<resources mapping="/resources/**" location="/resources/" />

	<!-- Resolves views selected for rendering by @Controllers to .jsp resources 
		in the /WEB-INF/views directory -->
	<beans:bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<beans:property name="prefix" value="/WEB-INF/views/" />
		<beans:property name="suffix" value=".jsp" />
	</beans:bean>
	<context:component-scan base-package="org.as.asjee" use-default-filters="false">
		<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
	</context:component-scan>

</beans:beans>

2、異常統一處理類

[java] view plain copy print?在CODE上檢視程式碼片派生到我的程式碼片
  1. package org.as.asjee.core.exception;  
  2. import java.sql.SQLException;  
  3. import javax.servlet.http.HttpServletRequest;  
  4. import org.as.asjee.core.log.AsJEELogger;  
  5. import org.as.asjee.core.log.AsJEELoggerFactory;  
  6. import org.springframework.web.bind.annotation.ControllerAdvice;  
  7. import org.springframework.web.bind.annotation.ExceptionHandler;  
  8. import org.springframework.web.bind.annotation.ResponseBody;  
  9. import org.springframework.web.servlet.ModelAndView;  
  10. /** 
  11.  * 捕獲異常統一處理 
  12.  * @description TODO 
  13.  * @author chen.gs 
  14.  * @create date 2016年4月28日 
  15.  * @modified by  
  16.  * @modify date 
  17.  * @version v1.0 
  18.  */
  19. @ControllerAdvice
  20. publicclass GlobalExceptionHandler {  
  21.     privatefinalstatic AsJEELogger LOG = AsJEELoggerFactory.getLogger(GlobalExceptionHandler.class);  
  22.     privatefinalstatic String EXPTION_MSG_KEY = "message";  
  23.     @ExceptionHandler(BusinessException.class)  
  24.     @ResponseBody
  25.     publicvoid handleBizExp(HttpServletRequest request, Exception ex){  
  26.         LOG.info("Business exception handler  " + ex.getMessage() );  
  27.         request.getSession(true).setAttribute(EXPTION_MSG_KEY, ex.getMessage());  
  28.     }  
  29.     @ExceptionHandler(SQLException.class)  
  30.     public ModelAndView handSql(Exception ex){  
  31.         LOG.info("SQL Exception " + ex.getMessage());  
  32.         ModelAndView mv = new ModelAndView();  
  33.         mv.addObject("message", ex.getMessage());  
  34.         mv.setViewName("sql_error");  
  35.         return mv;  
  36.     }  
  37. }  
package org.as.asjee.core.exception;

import java.sql.SQLException;

import javax.servlet.http.HttpServletRequest;

import org.as.asjee.core.log.AsJEELogger;
import org.as.asjee.core.log.AsJEELoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 * 捕獲異常統一處理
 * @description TODO
 * @author chen.gs
 * @create date 2016年4月28日
 * @modified by 
 * @modify date
 * @version v1.0
 */
@ControllerAdvice
public class GlobalExceptionHandler {
	
	private final static AsJEELogger LOG = AsJEELoggerFactory.getLogger(GlobalExceptionHandler.class);
	
	private final static String EXPTION_MSG_KEY = "message";
	
	@ExceptionHandler(BusinessException.class)
	@ResponseBody
	public void handleBizExp(HttpServletRequest request, Exception ex){
		LOG.info("Business exception handler  " + ex.getMessage() );
		request.getSession(true).setAttribute(EXPTION_MSG_KEY, ex.getMessage());
	}
	
	@ExceptionHandler(SQLException.class)
	public ModelAndView handSql(Exception ex){
		LOG.info("SQL Exception " + ex.getMessage());
		ModelAndView mv = new ModelAndView();
		mv.addObject("message", ex.getMessage());
		mv.setViewName("sql_error");
		return mv;
	}

}
自定義異常類BussinessException.java [java] view plain copy print?在CODE上檢視程式碼片派生到我的程式碼片
  1. package org.as.asjee.core.exception;  
  2. /** 
  3.  * 業務異常 
  4.  * @description TODO 
  5.  * @author chen.gs 
  6.  * @create date 2016年4月28日 
  7.  * @modified by  
  8.  * @modify date 
  9.  * @version v1.0 
  10.  */
  11. publicclass BusinessException extends Exception{  
  12.     privatestaticfinallong serialVersionUID = 1L;  
  13.     //業務型別
  14.     private String bizType;  
  15.     //業務程式碼
  16.     privateint bizCode;  
  17.     //錯誤資訊
  18.     private String message;  
  19.     public BusinessException(String bizType, int bizCode, String message){  
  20.         super(message);  
  21.         this.bizType = bizType;  
  22.         this.bizCode = bizCode;  
  23.         this.message = message;  
  24.     }  
  25.     public BusinessException(String message){  
  26.         super(message);  
  27.         this.bizType = "";  
  28.         this.bizCode = -1;  
  29.         this.message = message;  
  30.     }  
  31.     public BusinessException(String bizType, String message){  
  32.         super(message);  
  33.         this.bizType = bizType;  
  34.         this.bizCode = -1;  
  35.         this.message = message;  
  36.     }  
  37.     public BusinessException(int bizCode, String message){  
  38.         super(message);  
  39.         this.bizType = "";  
  40.         this.bizCode = bizCode;  
  41.         this.message = message;  
  42.     }  
  43.     public String getBizType() {  
  44.         return bizType;  
  45.     }  
  46.     publicvoid setBizType(String bizType) {  
  47.         this.bizType = bizType;  
  48.     }  
  49.     publicint getBizCode() {  
  50.         return bizCode;  
  51.     }  
  52.     publicvoid setBizCode(int bizCode) {  
  53.         this.bizCode = bizCode;  
  54.     }  
  55.     public String getMessage() {  
  56.         return message;  
  57.     }  
  58.     publicvoid setMessage(String message) {  
  59.         this.message = message;  
  60.     }  
  61. }  
package org.as.asjee.core.exception;

/**
 * 業務異常
 * @description TODO
 * @author chen.gs
 * @create date 2016年4月28日
 * @modified by 
 * @modify date
 * @version v1.0
 */
public class BusinessException extends Exception{

	private static final long serialVersionUID = 1L;
	
	//業務型別
	private String bizType;
	//業務程式碼
	private int bizCode;
	//錯誤資訊
	private String message;
	
	public BusinessException(String bizType, int bizCode, String message){
		super(message);
		this.bizType = bizType;
		this.bizCode = bizCode;
		this.message = message;
	}

	public BusinessException(String message){
		super(message);
		this.bizType = "";
		this.bizCode = -1;
		this.message = message;
	}

	public BusinessException(String bizType, String message){
		super(message);
		this.bizType = bizType;
		this.bizCode = -1;
		this.message = message;
	}
	
	public BusinessException(int bizCode, String message){
		super(message);
		this.bizType = "";
		this.bizCode = bizCode;
		this.message = message;
	}

	public String getBizType() {
		return bizType;
	}

	public void setBizType(String bizType) {
		this.bizType = bizType;
	}

	public int getBizCode() {
		return bizCode;
	}

	public void setBizCode(int bizCode) {
		this.bizCode = bizCode;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

}

3、controller

[java] view plain copy print?在CODE上檢視程式碼片派生到我的程式碼片
  1. package org.as.asjee.core.security.web;  
  2. import java.sql.SQLException;  
  3. import javax.annotation.Resource;  
  4. import org.as.asjee.core.exception.BusinessException;  
  5. import org.as.asjee.core.security.model.User;  
  6. import org.as.asjee.core.security.service.UserService;  
  7. import org.as.asjee.core.service.ServiceFacade;  
  8. import org.as.asjee.core.web.AbstractController;  
  9. import org.springframework.stereotype.Controller;  
  10. import org.springframework.web.bind.annotation.RequestMapping;  
  11. @Controller
  12. @RequestMapping("/security/user")  
  13. publicclass UserController  extends AbstractController<User>{  
  14.     @Resource
  15.     private UserService userService;  
  16.     @Resource
  17.     private ServiceFacade serviceFacade;  
  18.     @RequestMapping("login")  
  19.     public String login() {   
  20.         return"login";  
  21.     }  
  22.     @RequestMapping("login2")  
  23.     public String login2() throws Exception {  
  24.         thrownew SQLException("出錯鳥。。。。。。。。。");  
  25.     }     
  26.     @RequestMapping("login3")  
  27.     public String login3() throws Exception {   
  28.         thrownew BusinessException("業務執行異常");  
  29.     }  
  30.     //此方法丟擲的異常不是由GlobalExceptionHandler處理
  31.     //而是在catch塊處理
  32.     @RequestMapping("login4")  
  33.     public String login4() {   
  34.         try {  
  35.             thrownew BusinessException("業務執行異常");  
  36.         } catch (BusinessException e) {  
  37.             e.printStackTrace();  
  38.         }  
  39.         return"login";  
  40.     }  
  41. }  
package org.as.asjee.core.security.web;

import java.sql.SQLException;

import javax.annotation.Resource;

import org.as.asjee.core.exception.BusinessException;
import org.as.asjee.core.security.model.User;
import org.as.asjee.core.security.service.UserService;
import org.as.asjee.core.service.ServiceFacade;
import org.as.asjee.core.web.AbstractController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/security/user")
public class UserController  extends AbstractController<User>{

	@Resource
	private UserService userService;
	@Resource
	private ServiceFacade serviceFacade;

	@RequestMapping("login")
	public String login() { 
		return "login";
	}
	
	@RequestMapping("login2")
	public String login2() throws Exception {
		throw new SQLException("出錯鳥。。。。。。。。。");
	}	
	
	@RequestMapping("login3")
	public String login3() throws Exception { 
		throw new BusinessException("業務執行異常");
	}
	
	//此方法丟擲的異常不是由GlobalExceptionHandler處理
	//而是在catch塊處理
	@RequestMapping("login4")
	public String login4() { 
		try {
			throw new BusinessException("業務執行異常");
		} catch (BusinessException e) {
			e.printStackTrace();
		}
		return "login";
	}
	
}

4、JSP頁面

sql_error.jsp [html] view plain copy print?在CODE上檢視程式碼片派生到我的程式碼片
  1. <%@ page language="java"contentType="text/html; charset=UTF-8" %>
  2. <!DOCTYPE html">
  3. <html>
  4. <head>
  5. <metahttp-equiv="Content-Type"content="text/html; charset=UTF-8">
  6. <title>Insert title here</title>
  7. </head>
  8. <body>
  9.     <h1>ERROR MESSAGE</h1>
  10.     <p>${message}</p>
  11. </body>
  12. </html>
<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<!DOCTYPE html">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h1>ERROR MESSAGE</h1>
	<p>${message}</p>
</body>
</html>

5、簡要說明

在Controller中丟擲的異常,當沒有被catch處理時,GlobalExceptionHandler中定義的處理方法可以起作用,在方法寫明註解@ExceptionHandler,並註明其異常類即可。此種方法不僅可以作用於Controller,同樣的在DAO層、service層也可,都可以由GlobalExceptionHandler進行處理。此種寫法減少程式碼的入侵,值得推薦。 異常的統一處理只是註解ControllerAdvice用處之一,有興趣瞭解更多的,請到spring官網查閱。

相關推薦

spring mvc異常統一處理使用ControllerAdvice註解

1、配置 spring 版本: [html] view plain copy print? <org.springframework-version>4.1.9.RELEASE</org.springframework-version>

spring mvc異常統一處理實現HandlerExceptionResolver介面不生效的問題解決

spring mvc異常統一處理常見的有3種方式: 使用 @ ExceptionHandler 註解 實現 HandlerExceptionResolver 介面 使用 @controlleradvice 註解 詳細的使用方法可參考博文:https://blog.c

Spring MVC異常統一處理包括普通請求異常以及ajax請求異常

通常SpringMVC對異常的配置都是返回某個jsp檢視給使用者,但是通過ajax方式發起請求,即使發生異常,前臺也無法獲得任何異常提示資訊。因此需要對異常進行統一的處理,對於普通請求以及ajax請求的異常都有效。 1.Spring MVC的異常處理機制 Spring

Spring MVC異常統一處理的三種方式

  Spring 統一異常處理有 3 種方式,分別為: 使用 @ ExceptionHandler 註解 實現 HandlerExceptionResolver 介面 使用 @controlleradvice 註解 HandlerExceptionReso

Spring MVC異常統一處理(異常資訊的國際化,日誌記錄)

       JAVA EE專案中,不管是對底層的資料操作,還是業務層的處理過程,還是控制層的處理,都不可避免的會遇到各種可預知的(業務異常主動丟擲)、不可預知的異常需要處理。一般dao層、service層的異常都會直接丟擲,最後由controller統一進行處理,每個過程

Spring MVC異常統一處理

/** * 自定義返回結果封裝類 */public class ResultUtil implements Serializable {private static final long serialVersionUID = 1L;private Integer code;private String msg

Spring MVC 靜態資源處理

完整的專案案例: springmvc.zip 目錄 例項 專案結構:   一、配置web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.

Springboot-系統異常統一處理介面程式設計異常處理

Springboot-系統異常統一處理(介面程式設計異常) 1. 系統異常捕獲 /** * 全域性異常處理 * @Author: wangxc * @GitHub: https://github.com/vector4wang * @CS

Spring MVC-環境設置轉載實踐

framework group 運行 env 分享 blog osi 下載 rep 以下內容翻譯自:https://www.tutorialspoint.com/springmvc/springmvc_environment_setup.htm 說明:示例基於Spring

Spring MVC-Hello World示例轉載實踐

efi internal add property 建議 per 如果 b-s ase 以下內容翻譯自:https://www.tutorialspoint.com/springmvc/springmvc_hello_world_example.htm 說明:示例基於Sp

spring定時任務詳解@Scheduled註解

在springMVC裡使用spring的定時任務非常的簡單,如下: (一)在xml里加入task的名稱空間 xmlns:task="http://www.springframework.org/schema/task" http://www.spr

spring mvc web.xml配置攔截資源

<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.o

spring mvc 全部整合約束個人筆記

<beans xmlns="http://www.springframework.org/schema/beans"     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"     xmlns:aop="http://www.springfra

spring mvc 異常runtime異常、ajax異常統一處理與範例

SpringMVC 提供的異常處理主要有兩種方式,一種是直接實現自己的HandlerExceptionResolver,另一種是使用註解的方式實現一個專門用於處理異常的Controller——ExceptionHandler。前者當發生異常時,頁面會跳到指定的錯誤頁面

spring mvc 異常處理

連結:http://gaojiewyh.iteye.com/blog/1297746 (附原始碼)  連結:http://zywang.iteye.com/blog/983801   連結:http://www.cnblogs.com/xguo/p/3163519.html

詳解Spring MVC/Boot 統一異常處理最佳實踐

開發十年,就只剩下這套架構體系了! >>>   

Spring MVC異常處理實例

bsp ips etag label 視圖 uri _id integer ive 以下內容引用自http://wiki.jikexueyuan.com/project/spring/mvc-framework/spring-exception-handling-examp

Spring MVC異常處理SimpleMappingExceptionResolver

bean pri 分享圖片 ESS bsh trace 內部實現 ont per Spring MVC異常處理SimpleMappingExceptionResolver【轉】 (2012-12-07 13:45:33) 轉載▼ 標簽: 雜談 分類: 技術

Spring MVC 異常處理 - ResponseStatusExceptionResolver

執行 代碼 pin ces val col resolv use turn 作用在類和方法上面 更改返回的代碼和錯誤消息 類上 通過throw new UserName***Exception()拋出 @ResponseStatus(value=HttpStatus.FO

Spring系列(七) Spring MVC 異常處理

nco 部分 給定 uri too ebo intended 路徑 onf Servlet傳統異常處理 Servlet規範規定了當web應用發生異常時必須能夠指明, 並確定了該如何處理, 規定了錯誤信息應該包含的內容和展示頁面的方式.(詳細可以參考servlet規範文檔)