spring mvc controller中的异常封装
http://abc08010051.iteye.com/blog/2031992
一直以来都在用spring mvc做mvc框架,我使用的不是基于注解的,还是使用的基于xml的,在controller里一般都会加上一个异常捕捉,能分析出来的异常,提示出具体信息,不能预料的异常,返回一个统一的异常提示信息,未封装前的代码为:
- public ModelAndView addBigDeal(HttpServletRequest request, HttpServletResponse response) throws Exception {
- JSONObject jsonObject = new JSONObject();
- try {
- String sessionId = WebUtils.getStringValue(request, "sessionId", true);
- String pl_id = WebUtils.getStringValue(request, "pl_id", true);
- String vsr_id = WebUtils.getStringValue(request, "vsr_id", true);
- String cmnts = WebUtils.getStringValue(request, "cmnts", false);
- if (!StringUtils.isBlank(cmnts)) {
- cmnts = new String(Base64Utils.decode(cmnts), "UTF-8");
- }
- JSONObject result = new JSONObject();
- result.put("dataId", this.storeVsrService.addBigDeal(pl_id, vsr_id, cmnts));
- jsonObject.put("data", result);
- jsonObject.put("status", CommonUtils.getSubStatus(" add bigDeal successfully!"));
- } catch (GenericException e) {
- jsonObject.put("status", CommonUtils.getSubStatus(false, "000001", e.getMsg()));
- jsonObject.put("data", "");
- logger.error("error !", e);
- } catch (Exception e) {
- jsonObject.put("status", CommonUtils.getSubStatus(false, "000001", "网络或其他错误,请联系管理员!"));
- jsonObject.put("data", "");
- logger.error("error !", e);
- }
- response.getWriter().write(jsonObject.toString());
- return null;
- }
GenericException为自定义异常的父类,自定义的异常都要继承该类
上面代码的缺点:每写一个方法时,都要重复的写这一段:
- try {
- } catch (GenericException e) {
- jsonObject.put("status", CommonUtils.getSubStatus(false, "000001", e.getMsg()));
- jsonObject.put("data", "");
- logger.error("error !", e);
- } catch (Exception e) {
- jsonObject.put("status", CommonUtils.getSubStatus(false, "000001", "网络或其他错误,请联系管理员!"));
- jsonObject.put("data", "");
- logger.error("error !", e);
- }
因为每一个controller都会继承MultiActionController,现在在每一个controller和自己定义的controller里抽象一层,因为所有controller里的方法入口
都是MultiActionController里的handleRequestInternal方法,所以重写该方法,把异常捕捉放到这个统一的入口和出口里,
新增加的类为BaseController,封装后的代码如下:
- package com.intel.store.controller;
- import com.intel.store.common.CommonUtils;
- import com.intel.store.exception.GenericException;
- import org.codehaus.jettison.json.JSONObject;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import org.springframework.web.servlet.ModelAndView;
- import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
- import org.springframework.web.servlet.mvc.multiaction.NoSuchRequestHandlingMethodException;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- /**
- * mvc controller类的基类,用于一般controller的继承,
- * 把异常控制模块提取到基类,
- * 使开发更加简洁,快速
- * Created with IntelliJ IDEA.
- * User: malone
- * Date: 14-3-17
- * Time: 上午10:21
- * To change this template use File | Settings | File Templates.
- */
- public class BaseController<T extends BaseController<T>> extends MultiActionController {
- private Class<T> subclass;
- private Logger logger = LoggerFactory.getLogger(subclass);
- BaseController() {
- subclass = ((Class)((ParameterizedType)(this.getClass().getGenericSuperclass())).getActualTypeArguments()[0]);
- logger = LoggerFactory.getLogger(subclass);
- }
- @Override
- protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
- throws Exception {
- JSONObject jsonObject = new JSONObject();
- try {
- String methodName = this.getMethodNameResolver().getHandlerMethodName(request);
- Object obj = invokeNamedMethod(methodName, request, response);
- System.out.println(obj.getClass());
- return invokeNamedMethod(methodName, request, response);
- } catch (NoSuchRequestHandlingMethodException ex) {
- return handleNoSuchRequestHandlingMethod(ex, request, response);
- } catch (GenericException e) {
- jsonObject.put("status", CommonUtils.getSubStatus(false, "000001", e.getMsg()));
- jsonObject.put("data", "");
- logger.error(e.getMsg(), e);
- response.getWriter().write(jsonObject.toString());
- return null;
- } catch (Exception e) {
- jsonObject.put("status", CommonUtils.getSubStatus(false, "000001",
- "网络或其他错误,请联系管理员!"));
- jsonObject.put("data", "");
- logger.error("error !", e);
- response.getWriter().write(jsonObject.toString());
- return null;
- }
- }
- }
这样以来所有的自定义Controller只需要继承BaseController, 然后在每个方法里就需要些try catch异常捕捉模块了,如下所示
- public ModelAndView addBigDeal(HttpServletRequest request, HttpServletResponse response) throws Exception {
- JSONObject jsonObject = new JSONObject();
- String sessionId = WebUtils.getStringValue(request, "sessionId", true);
- String pl_id = WebUtils.getStringValue(request, "pl_id", true);
- String vsr_id = WebUtils.getStringValue(request, "vsr_id", true);
- String cmnts = WebUtils.getStringValue(request, "cmnts", false);
- if (!StringUtils.isBlank(cmnts)) {
- cmnts = new String(Base64Utils.decode(cmnts), "UTF-8");
- }
- JSONObject result = new JSONObject();
- result.put("dataId", this.storeVsrService.addBigDeal(pl_id, vsr_id, cmnts));
- jsonObject.put("data", result);
- jsonObject.put("status", CommonUtils.getSubStatus(" add bigDeal successfully!"));
- response.getWriter().write(jsonObject.toString());
- return null;
- }
spring mvc controller中的异常封装的更多相关文章
- spring mvc controller中获取request head内容
spring mvc controller中获取request head内容: @RequestMapping("/{mlid}/{ptn}/{name}") public Str ...
- Spring MVC Controller中解析GET方式的中文参数会乱码的问题(tomcat如何解码)
Spring MVC Controller中解析GET方式的中文参数会乱码的问题 问题描述 在工作上使用突然出现从get获取中文参数乱码(新装机器,tomcat重新下载和配置),查了半天终于找到解决办 ...
- Spring MVC Controller中GET方式传过来的中文参数会乱码的问题
Spring MVC controller 这样写法通常意味着访问该请求,GET和POST请求都行,可是经常会遇到,如果碰到参数是中文的,post请求可以,get请求过来就是乱码.如果强行对参数进行了 ...
- spring MVC controller中的方法跳转到另外controller中的某个method的方法
1. 需求背景 需求:spring MVC框架controller间跳转,需重定向.有几种情况:不带参数跳转,带参数拼接url形式跳转,带参数不拼接参数跳转,页面也能显示. 本来以为挺简单的一 ...
- spring mvc Controller中使用@Value无法获取属性值
在使用spring mvc时,实际上是两个spring容器: 1,dispatcher-servlet.xml 是一个,我们的controller就在这里,所以这个里面也需要注入属性文件 org.sp ...
- 在Spring MVC Controller中注入HttpServletRequest对象会不会造成线程安全的问题
做法: 1.比如我们在Controller的方法中,通常是直接将HttpServletRequest做为参数,而为了方便节省代码,通常会定义为全局变量,然后使用@Autowire注入. 说明: 1.观 ...
- spring mvc controller中的参数验证机制(二)
这里我们介绍以下自定义的校验器的简单的使用示例 一.包结构和主要文件 二.代码 1.自定义注解文件MyConstraint package com.knyel.validator; import ja ...
- spring mvc controller中的参数验证机制(一)
一.验证用到的注解 @Valid 对传到后台的参数的验证 @BindingResult 配合@Valid使用,验证失败后的返回 二.示例 1.传统方式 @PostMapping public User ...
- spring mvc controller间跳转 重定向 传参(转)
spring mvc controller间跳转 重定向 传参 url:http://zghbwjl.blog.163.com/blog/static/12033667220137795252845/ ...
随机推荐
- 链表各种操作及其实现方法(c实现)
链表是一种最简单的数据结构之一,经常会被面试官用来考察应聘者的基础扎不扎实,最近也到了求职季,所以我把自己对链表的一些理解写出来,希望能跟大家交流交流: 链表的概念其实挺简单,无非就是一个利用指针将数 ...
- gitlab 搭建与迁移
#下载gitlabhttps://mirrors.tuna.tsinghua.edu.cn/gitlab-ce/yum/el6/gitlab-ce-10.1.3-ce.0.el6.x86_64.rpm ...
- AC日记——开关灯 codevs 1690
开关灯 思路: 线段树: bool懒标记维护: 更新区间时是区间总值减去当前值: 来,上代码: #include <cstdio> #include <cstring> #in ...
- HDU 1171 Big Event in HDU【01背包/求两堆数分别求和以后的差最小】
Big Event in HDU Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) T ...
- 51nod 1420 数袋鼠好有趣【贪心】
1420 数袋鼠好有趣 题目来源: CodeForces 基准时间限制:1 秒 空间限制:131072 KB 分值: 40 难度:4级算法题 收藏 关注 有n只袋鼠.每只袋鼠的大小用一个整数表示. ...
- Struts2 学习笔记——struts.xml文件之Bean的配置
Struts2的大部分核心组件不是以硬编码的形式写在代码中,而是通过自身的IoC容器来管理的. Struts2以可配置的形式来管理核心组件,所以开发者可以很容易的扩展框架的核心组件.当开发者需要扩展或 ...
- FZU-2270 Two Triangles(两个三角形全等)
原题地址: 题意: 给出n个点,有两个人,每个人可以选3个点,问有多少种情况是可以找出两个三角形,是可以通过旋转使其全等. 思路: 所以首先要是三角形即三点不能共线,其次要全等,即三条边对应相等, ...
- OpenJ_Bailian - 1037 A decorative fence
Discription Richard just finished building his new house. Now the only thing the house misses is a c ...
- linux 自动删除n天前文件
现在系统每天生成一个日期文件夹,并压缩上传到ftp服务器,造成目录下文件太多,所以决定写个定时删除文件的任务 写脚本文件 find /home/data -mtime +90 -name " ...
- C/C++框架和库 (真的很强大) 转
http://blog.csdn.net/xiaoxiaoyeyaya/article/details/42541419 值得学习的C语言开源项目 - 1. Webbench Webbench ...