http://abc08010051.iteye.com/blog/2031992

一直以来都在用spring mvc做mvc框架,我使用的不是基于注解的,还是使用的基于xml的,在controller里一般都会加上一个异常捕捉,能分析出来的异常,提示出具体信息,不能预料的异常,返回一个统一的异常提示信息,未封装前的代码为:

  1. public ModelAndView addBigDeal(HttpServletRequest request, HttpServletResponse response) throws Exception {
  2. JSONObject jsonObject = new JSONObject();
  3. try {
  4. String sessionId = WebUtils.getStringValue(request, "sessionId", true);
  5. String pl_id = WebUtils.getStringValue(request, "pl_id", true);
  6. String vsr_id = WebUtils.getStringValue(request, "vsr_id", true);
  7. String cmnts = WebUtils.getStringValue(request, "cmnts", false);
  8. if (!StringUtils.isBlank(cmnts)) {
  9. cmnts = new String(Base64Utils.decode(cmnts), "UTF-8");
  10. }
  11. JSONObject result = new JSONObject();
  12. result.put("dataId", this.storeVsrService.addBigDeal(pl_id, vsr_id, cmnts));
  13. jsonObject.put("data", result);
  14. jsonObject.put("status", CommonUtils.getSubStatus(" add bigDeal  successfully!"));
  15. } catch (GenericException e) {
  16. jsonObject.put("status", CommonUtils.getSubStatus(false, "000001", e.getMsg()));
  17. jsonObject.put("data", "");
  18. logger.error("error !", e);
  19. } catch (Exception e) {
  20. jsonObject.put("status", CommonUtils.getSubStatus(false, "000001", "网络或其他错误,请联系管理员!"));
  21. jsonObject.put("data", "");
  22. logger.error("error !", e);
  23. }
  24. response.getWriter().write(jsonObject.toString());
  25. return null;
  26. }

GenericException为自定义异常的父类,自定义的异常都要继承该类

上面代码的缺点:每写一个方法时,都要重复的写这一段:

  1. try {
  2. } catch (GenericException e) {
  3. jsonObject.put("status", CommonUtils.getSubStatus(false, "000001", e.getMsg()));
  4. jsonObject.put("data", "");
  5. logger.error("error !", e);
  6. } catch (Exception e) {
  7. jsonObject.put("status", CommonUtils.getSubStatus(false, "000001", "网络或其他错误,请联系管理员!"));
  8. jsonObject.put("data", "");
  9. logger.error("error !", e);
  10. }

因为每一个controller都会继承MultiActionController,现在在每一个controller和自己定义的controller里抽象一层,因为所有controller里的方法入口

都是MultiActionController里的handleRequestInternal方法,所以重写该方法,把异常捕捉放到这个统一的入口和出口里,

新增加的类为BaseController,封装后的代码如下:

  1. package com.intel.store.controller;
  2. import com.intel.store.common.CommonUtils;
  3. import com.intel.store.exception.GenericException;
  4. import org.codehaus.jettison.json.JSONObject;
  5. import org.slf4j.Logger;
  6. import org.slf4j.LoggerFactory;
  7. import org.springframework.web.servlet.ModelAndView;
  8. import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
  9. import org.springframework.web.servlet.mvc.multiaction.NoSuchRequestHandlingMethodException;
  10. import javax.servlet.http.HttpServletRequest;
  11. import javax.servlet.http.HttpServletResponse;
  12. /**
  13. *  mvc controller类的基类,用于一般controller的继承,
  14. *  把异常控制模块提取到基类,
  15. *  使开发更加简洁,快速
  16. * Created with IntelliJ IDEA.
  17. * User: malone
  18. * Date: 14-3-17
  19. * Time: 上午10:21
  20. * To change this template use File | Settings | File Templates.
  21. */
  22. public class BaseController<T extends BaseController<T>> extends MultiActionController {
  23. private Class<T> subclass;
  24. private Logger logger = LoggerFactory.getLogger(subclass);
  25. BaseController() {
  26. subclass = ((Class)((ParameterizedType)(this.getClass().getGenericSuperclass())).getActualTypeArguments()[0]);
  27. logger = LoggerFactory.getLogger(subclass);
  28. }
  29. @Override
  30. protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
  31. throws Exception {
  32. JSONObject jsonObject = new JSONObject();
  33. try {
  34. String methodName = this.getMethodNameResolver().getHandlerMethodName(request);
  35. Object obj = invokeNamedMethod(methodName, request, response);
  36. System.out.println(obj.getClass());
  37. return invokeNamedMethod(methodName, request, response);
  38. } catch (NoSuchRequestHandlingMethodException ex) {
  39. return handleNoSuchRequestHandlingMethod(ex, request, response);
  40. } catch (GenericException e) {
  41. jsonObject.put("status", CommonUtils.getSubStatus(false, "000001", e.getMsg()));
  42. jsonObject.put("data", "");
  43. logger.error(e.getMsg(), e);
  44. response.getWriter().write(jsonObject.toString());
  45. return null;
  46. } catch (Exception e) {
  47. jsonObject.put("status", CommonUtils.getSubStatus(false, "000001",
  48. "网络或其他错误,请联系管理员!"));
  49. jsonObject.put("data", "");
  50. logger.error("error !", e);
  51. response.getWriter().write(jsonObject.toString());
  52. return null;
  53. }
  54. }
  55. }

这样以来所有的自定义Controller只需要继承BaseController, 然后在每个方法里就需要些try catch异常捕捉模块了,如下所示

  1. public ModelAndView addBigDeal(HttpServletRequest request, HttpServletResponse response) throws Exception {
  2. JSONObject jsonObject = new JSONObject();
  3. String sessionId = WebUtils.getStringValue(request, "sessionId", true);
  4. String pl_id = WebUtils.getStringValue(request, "pl_id", true);
  5. String vsr_id = WebUtils.getStringValue(request, "vsr_id", true);
  6. String cmnts = WebUtils.getStringValue(request, "cmnts", false);
  7. if (!StringUtils.isBlank(cmnts)) {
  8. cmnts = new String(Base64Utils.decode(cmnts), "UTF-8");
  9. }
  10. JSONObject result = new JSONObject();
  11. result.put("dataId", this.storeVsrService.addBigDeal(pl_id, vsr_id, cmnts));
  12. jsonObject.put("data", result);
  13. jsonObject.put("status", CommonUtils.getSubStatus(" add bigDeal  successfully!"));
  14. response.getWriter().write(jsonObject.toString());
  15. return null;
  16. }

spring mvc controller中的异常封装的更多相关文章

  1. spring mvc controller中获取request head内容

    spring mvc controller中获取request head内容: @RequestMapping("/{mlid}/{ptn}/{name}") public Str ...

  2. Spring MVC Controller中解析GET方式的中文参数会乱码的问题(tomcat如何解码)

    Spring MVC Controller中解析GET方式的中文参数会乱码的问题 问题描述 在工作上使用突然出现从get获取中文参数乱码(新装机器,tomcat重新下载和配置),查了半天终于找到解决办 ...

  3. Spring MVC Controller中GET方式传过来的中文参数会乱码的问题

    Spring MVC controller 这样写法通常意味着访问该请求,GET和POST请求都行,可是经常会遇到,如果碰到参数是中文的,post请求可以,get请求过来就是乱码.如果强行对参数进行了 ...

  4. spring MVC controller中的方法跳转到另外controller中的某个method的方法

    1. 需求背景     需求:spring MVC框架controller间跳转,需重定向.有几种情况:不带参数跳转,带参数拼接url形式跳转,带参数不拼接参数跳转,页面也能显示. 本来以为挺简单的一 ...

  5. spring mvc Controller中使用@Value无法获取属性值

    在使用spring mvc时,实际上是两个spring容器: 1,dispatcher-servlet.xml 是一个,我们的controller就在这里,所以这个里面也需要注入属性文件 org.sp ...

  6. 在Spring MVC Controller中注入HttpServletRequest对象会不会造成线程安全的问题

    做法: 1.比如我们在Controller的方法中,通常是直接将HttpServletRequest做为参数,而为了方便节省代码,通常会定义为全局变量,然后使用@Autowire注入. 说明: 1.观 ...

  7. spring mvc controller中的参数验证机制(二)

    这里我们介绍以下自定义的校验器的简单的使用示例 一.包结构和主要文件 二.代码 1.自定义注解文件MyConstraint package com.knyel.validator; import ja ...

  8. spring mvc controller中的参数验证机制(一)

    一.验证用到的注解 @Valid 对传到后台的参数的验证 @BindingResult 配合@Valid使用,验证失败后的返回 二.示例 1.传统方式 @PostMapping public User ...

  9. spring mvc controller间跳转 重定向 传参(转)

    spring mvc controller间跳转 重定向 传参 url:http://zghbwjl.blog.163.com/blog/static/12033667220137795252845/ ...

随机推荐

  1. Guava源码学习(二)Ordering

    基于版本:Guava 22.0 Wiki:Ordering 0. Ordering简介 Guava的Ordering提供了链式风格的比较器的实现,我们可以用Ordering轻松构建复杂的比较器. 1. ...

  2. HihoCoder 1629 Graph (2017 ACM-ICPC 北京区域赛 C题,回滚莫队 + 启发式合并 + 可撤销并查集)

    题目链接  2017 ACM-ICPC Beijing Regional Contest Problem C 题意  给定一个$n$个点$m$条边的无向图.现在有$q$个询问,每次询问格式为$[l, ...

  3. (转)Limboy:自学 iOS 开发的一些经验

    不知不觉作为 iOS 开发也有两年多的时间了,记得当初看到 OC 的语法时,愣是被吓了回去,隔了好久才重新耐下心去啃一啃.啃了一阵,觉得大概有了点概念,看到 Cocoa 那么多的 Class,又懵了, ...

  4. AOJ 0531:Paint Color(二维离散+imos)

    [题目链接] http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=0531 [题目大意] 给出一张图,和一些矩形障碍物,求该图没被障碍物覆 ...

  5. [COCI2015]TRAKTOR

    题目大意: 一个$X\times Y(X,Y\leq10^5)$的格子中,每秒钟依次$n(n\leq10^6)$个蘑菇, 告诉你每个蘑菇出现的时间和位置,问何时第一次出现$k(2\leq k\leq ...

  6. Java字符串(String)

    从表面上看,字符串就是双引号之间的数据,例如“微学苑”.“http://www.weixueyuan.net”等.在Java中,可以使用下面的方法定义字符串:    String stringName ...

  7. 【转载】【面试经验】PHP中级面试题

    By chajian8.com - Last updated: 2012/05/24 21:13:12 - 17 views - Posted in PHP, 职场/生活/面试 - Tags: PHP ...

  8. Apache2 httpd.conf 配置详解

    Apache2 httpd.conf 配置详解 <第一部分> 常用配置指令说明 1. ServerRoot:服务器的基础目录,一般来说它将包含conf/和logs/子目录,其它配置文件的相 ...

  9. [转] IplImage, CvMat, Mat 的关系

    拼装小火车 的原文 IplImage, CvMat, Mat 的关系 opencv中常见的 与图像操作有关的数据容器有Mat,cvMat和IplImage,这三种类型都可以代表和显示图像,但是,Mat ...

  10. 【Java】java注解@Transient的作用, 配合JPA中时间段的查询

    java注解@Transient的作用 @Transient标注的属性,不会被ORM框架映射到数据库中. 用于数据库表字段和java实体属性不一致的时候,标注在属性上使用. 例如时间段的查询 查询 R ...