spring mvc異常統一處理(使用ControllerAdvice註解)
1、配置
spring 版本: [html] view plain copy print?- <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
- <annotation-driven/>
<annotation-driven />
[html]
view plain
copy
print?
- <?xmlversion="1.0"encoding="UTF-8"?>
- <beans:beansxmlns="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 -->
- <resourcesmapping="/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:propertyname="prefix"value="/WEB-INF/views/"/>
- <beans:propertyname="suffix"value=".jsp"/>
- </beans:bean>
- <context:component-scanbase-package="org.as.asjee"use-default-filters="false">
- <context:include-filtertype="annotation"expression="org.springframework.stereotype.Controller"/>
- </context:component-scan>
- </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?- 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
- publicclass GlobalExceptionHandler {
- privatefinalstatic AsJEELogger LOG = AsJEELoggerFactory.getLogger(GlobalExceptionHandler.class);
- privatefinalstatic String EXPTION_MSG_KEY = "message";
- @ExceptionHandler(BusinessException.class)
- @ResponseBody
- publicvoid 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;
- }
- }
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?
- package org.as.asjee.core.exception;
- /**
- * 業務異常
- * @description TODO
- * @author chen.gs
- * @create date 2016年4月28日
- * @modified by
- * @modify date
- * @version v1.0
- */
- publicclass BusinessException extends Exception{
- privatestaticfinallong serialVersionUID = 1L;
- //業務型別
- private String bizType;
- //業務程式碼
- privateint 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;
- }
- publicvoid setBizType(String bizType) {
- this.bizType = bizType;
- }
- publicint getBizCode() {
- return bizCode;
- }
- publicvoid setBizCode(int bizCode) {
- this.bizCode = bizCode;
- }
- public String getMessage() {
- return message;
- }
- publicvoid setMessage(String message) {
- this.message = message;
- }
- }
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?- 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")
- publicclass 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 {
- thrownew SQLException("出錯鳥。。。。。。。。。");
- }
- @RequestMapping("login3")
- public String login3() throws Exception {
- thrownew BusinessException("業務執行異常");
- }
- //此方法丟擲的異常不是由GlobalExceptionHandler處理
- //而是在catch塊處理
- @RequestMapping("login4")
- public String login4() {
- try {
- thrownew BusinessException("業務執行異常");
- } catch (BusinessException e) {
- e.printStackTrace();
- }
- return"login";
- }
- }
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?- <%@ page language="java"contentType="text/html; charset=UTF-8" %>
- <!DOCTYPE html">
- <html>
- <head>
- <metahttp-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>
<%@ 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規範文檔)