Spring MVC annotation (二)
来源:互联网 发布:淘宝活动促销词 编辑:程序博客网 时间:2024/05/18 02:09
@ExceptionHandler
Spring注解,改变了我的开发思路。前段时间,用@RequestBody,@ResponseBody,不费吹灰之力就解决了JSon自动绑定。接着就发现,如果遇到RuntimeException,需要给出一个默认返回JSON。
以前都是用SimpleMappingExceptionResolver拦截实现,今天偶尔看下资料,@ExceptionHandler,就把这个异常给拦截了,太方便了!
以前都是用SimpleMappingExceptionResolver拦截实现,今天偶尔看下资料,@ExceptionHandler,就把这个异常给拦截了,太方便了!
直接上代码:
- @Controller
- public class AccessController {
- /**
- * 异常页面控制
- *
- * @param runtimeException
- * @return
- */
- @ExceptionHandler(RuntimeException.class)
- public @ResponseBody
- Map<String,Object> runtimeExceptionHandler(RuntimeException runtimeException) {
- logger.error(runtimeException.getLocalizedMessage());
- Map model = new TreeMap();
- model.put("status", false);
- return model;
- }
- }
或者这个有些有些复杂,来个简单易懂的,上代码:
- @Controller
- public class AccessController {
- /**
- * 异常页面控制
- *
- * @param runtimeException
- * @return
- */
- @ExceptionHandler(RuntimeException.class)
- public String runtimeExceptionHandler(RuntimeException runtimeException,
- ModelMap modelMap) {
- logger.error(runtimeException.getLocalizedMessage());
- modelMap.put("status", IntegralConstant.FAIL_STATUS);
- return "exception";
- }
- }
================================================================
(http://www.mkyong.com/spring-mvc/spring-mvc-exceptionhandler-example/)
In this tutorial, we show you how to do exception handling in Spring MVC frameworks. Normally, we use@ExceptionHandler
to decide which “view” should be returned back if certain exception is raised.
P.S This @ExceptionHandler class is available since Spring 3.0
1. Project Structure
Review the project directory structure, a standard Maven project.
2. Custom Exception
A custom exception, with custom error code and error description.
public class CustomGenericException extends RuntimeException {private static final long serialVersionUID = 1L;private String errCode;private String errMsg;public String getErrCode() {return errCode;}public void setErrCode(String errCode) {this.errCode = errCode;}public String getErrMsg() {return errMsg;}public void setErrMsg(String errMsg) {this.errMsg = errMsg;}public CustomGenericException(String errCode, String errMsg) {this.errCode = errCode;this.errMsg = errMsg;}}
3. Spring Controller
A Spring controller, review the execution-flows below :
- If user provide a
/error
request, it throws “CustomGenericException”, and thehandleCustomException()
method will be fired. - If user provide a
/io-error
request, it throws “IOException”, and thehandleAllException()
method will be fired.
import java.io.IOException;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.ExceptionHandler;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.servlet.ModelAndView;import com.mkyong.web.exception.CustomGenericException;@Controllerpublic class MainController {@RequestMapping(value = "/{type:.+}", method = RequestMethod.GET)public ModelAndView getPages(@PathVariable("type") String type)throws Exception { if ("error".equals(type)) {// go handleCustomExceptionthrow new CustomGenericException("E888", "This is custom message"); } else if ("io-error".equals(type)) {// go handleAllExceptionthrow new IOException(); } else {return new ModelAndView("index").addObject("msg", type); }}@ExceptionHandler(CustomGenericException.class)public ModelAndView handleCustomException(CustomGenericException ex) {ModelAndView model = new ModelAndView("error/generic_error");model.addObject("errCode", ex.getErrCode());model.addObject("errMsg", ex.getErrMsg());return model;}@ExceptionHandler(Exception.class)public ModelAndView handleAllException(Exception ex) {ModelAndView model = new ModelAndView("error/generic_error");model.addObject("errMsg", "this is Exception.class");return model;}}
4. JSP Pages
pages/index.jsp<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%><html><body><h2>Spring MVC @ExceptionHandler Example</h2><c:if test="${not empty msg}"><h2>${msg}</h2></c:if></body></html>
pages/error/generic_error.jsp
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%><html><body><c:if test="${not empty errCode}"><h1>${errCode} : System Errors</h1></c:if><c:if test="${empty errCode}"><h1>System Errors</h1></c:if><c:if test="${not empty errMsg}"><h2>${errMsg}</h2></c:if></body></html>
5. Testing
Review following 3 test cases :
1. http://localhost:8080/SpringMvcExample/anything
2. http://localhost:8080/SpringMvcExample/error
3. http://localhost:8080/SpringMvcExample/io-error
6. @ControllerAdvice Example
The above @ExceptionHandler
example is only apply to a single controller, to apply it globally (all controllers), annotate a class with @ControllerAdvice
.
import org.springframework.web.bind.annotation.ControllerAdvice;import org.springframework.web.bind.annotation.ExceptionHandler;import org.springframework.web.servlet.ModelAndView;import com.mkyong.web.exception.CustomGenericException;@ControllerAdvicepublic class GlobalExceptionController {@ExceptionHandler(CustomGenericException.class)public ModelAndView handleCustomException(CustomGenericException ex) {ModelAndView model = new ModelAndView("error/generic_error");model.addObject("errCode", ex.getErrCode());model.addObject("errMsg", ex.getErrMsg());return model;}@ExceptionHandler(Exception.class)public ModelAndView handleAllException(Exception ex) {ModelAndView model = new ModelAndView("error/generic_error");model.addObject("errMsg", "this is Exception.class");return model;}}
0 0
- Spring MVC annotation (二)
- spring mvc annotation总结
- [Spring MVC] - Annotation验证
- [Spring MVC] - Annotation验证
- [Spring MVC] - Annotation验证
- Spring MVC annotation (一)
- spring mvc annotation
- Spring mvc:annotation-driven
- Spring MVC annotation
- spring-mvc源码阅读(二)<mvc:annotation-driven/>做了什么
- Spring参考手册 mvc:annotation-driven
- Spring MVC 3 -- annotation 配置
- spring mvc annotation 的例子
- Spring MVC MultiActionController annotation example
- Spring MVC MultiActionController annotation example
- spring mvc <mvc:annotation-driver/>详解
- 【Spring MVC】<mvc:annotation-driven/>详解
- Spring MVC 中关于 mvc:annotation-driven
- The type android.support.v4.app.FragmentActivity cannot be resolved. It is indirectly referenced fro
- iOS UITesting (Objective-C Version) (一)
- 穷举法解决问题5
- StringBuffer的基本用法
- java中String类详解
- Spring MVC annotation (二)
- Linux Source 命令
- UVa 10692 Huge Mods(快速幂)(欧拉定理)
- servlet 的生命周期
- 有关图片锯齿化问题
- 开始搬砖
- Zephyr简介:第二节
- android控件——AlertDialog
- 穷举法解决问题6