1 描述
在J2EE项目的开发中,不管是对底层的数据库操作过程,还是业务层的处理过程,还是控制层的处理过程,都不可避免会遇到各种可预知的、不可预知的异常需要处理。每个过程都单独处理异常,系统的代码耦合度高,工作量大且不好统一,维护的工作量也很大。
那么,能不能将所有类型的异常处理从各处理过程解耦出来,这样既保证了相关处理过程的功能较单一,也实现了异常信息的统一处理和维护?答案是肯定的。下面将介绍使用Spring MVC统一处理异常的解决和实现过程。
2 分析
Spring MVC处理异常有3种方式:
(1)使用Spring MVC提供的简单异常处理器SimpleMappingExceptionResolver;
(2)实现Spring的异常处理接口HandlerExceptionResolver 自定义自己的异常处理器;
(3)使用@ExceptionHandler注解实现异常处理;
3 实战
3.1 引言
为了验证Spring MVC的3种异常处理方式的实际效果,我们需要开发一个测试项目,从Dao层、Service层、Controller层分别抛出不同的异常,然后分别集成3种方式进行异常处理,从而比较3种方式的优缺点。
3.2 实战项目
3.2.1 项目结构
3.2.2 Dao层代码
3.2.3 Service层代码
3.2.4 Controller层代码
3.2.5 JSP页面代码
3.3 集成异常处理
3.3.1 使用SimpleMappingExceptionResolver实现异常处理
1、在Spring的配置文件applicationContext.xml中增加以下内容:
2、启动测试项目,经验证,Dao层、Service层、Controller层抛出的异常(业务异常BusinessException、参数异常ParameterException和其它的异常Exception)都能准确显示定义的异常处理页面,达到了统一异常处理的目标。
3、从上面的集成过程可知,使用SimpleMappingExceptionResolver进行异常处理,具有集成简单、有良好的扩展性、对已有代码没有入侵性等优点,但该方法仅能获取到异常信息,若在出现异常时,对需要获取除异常以外的数据的情况不适用。
3.3.2 实现HandlerExceptionResolver 接口自定义异常处理器
1、增加HandlerExceptionResolver 接口的实现类MyExceptionHandler,代码如下:
2、在Spring的配置文件applicationContext.xml中增加以下内容:
3、启动测试项目,经验证,Dao层、Service层、Controller层抛出的异常(业务异常BusinessException、参数异常ParameterException和其它的异常Exception)都能准确显示定义的异常处理页面,达到了统一异常处理的目标。
4、从上面的集成过程可知,使用实现HandlerExceptionResolver接口的异常处理器进行异常处理,具有集成简单、有良好的扩展性、对已有代码没有入侵性等优点,同时,在异常处理时能获取导致出现异常的对象,有利于提供更详细的异常处理信息。
3.3.3 使用@ExceptionHandler注解实现异常处理
1、增加BaseController类,并在类中使用@ExceptionHandler注解声明异常处理,代码如下:
2、修改代码,使所有需要异常处理的Controller都继承该类,如下所示,修改后的TestController类继承于BaseController:
3、启动测试项目,经验证,Dao层、Service层、Controller层抛出的异常(业务异常BusinessException、参数异常ParameterException和其它的异常Exception)都能准确显示定义的异常处理页面,达到了统一异常处理的目标。
4、从上面的集成过程可知,使用@ExceptionHandler注解实现异常处理,具有集成简单、有扩展性好(只需要将要异常处理的Controller类继承于BaseController即可)、不需要附加Spring配置等优点,但该方法对已有代码存在入侵性(需要修改已有代码,使相关类继承于BaseController),在异常处理时不能获取除异常以外的数据。
3.4 未捕获异常的处理
对于Unchecked Exception而言,由于代码不强制捕获,往往被忽略,如果运行期产生了Unchecked Exception,而代码中又没有进行相应的捕获和处理,则我们可能不得不面对尴尬的404、500……等服务器内部错误提示页面。
我们需要一个全面而有效的异常处理机制。目前大多数服务器也都支持在Web.xml中通过<error-page>(Websphere/Weblogic)或者<error-code>(Tomcat)节点配置特定异常情况的显示页面。修改web.xml文件,增加以下内容:
4 解决结果
1、运行测试项目显示的首页,如下图所示:
2、业务错误显示的页面,如下图所示:
3、参数错误显示的页面,如下图所示:
4、未知错误显示的页面,如下图所示:
5、服务器内部错误页面,如下图所示:
5 总结
综合上述可知,Spring MVC集成异常处理3种方式都可以达到统一异常处理的目标。从3种方式的优缺点比较,若只需要简单的集成异常处理,推荐使用SimpleMappingExceptionResolver即可;若需要集成的异常处理能够更具个性化,提供给用户更详细的异常信息,推荐自定义实现HandlerExceptionResolver接口的方式;若不喜欢Spring配置文件或要实现“零配置”,且能接受对原有代码的适当入侵,则建议使用@ExceptionHandler注解方式。
6 源代码
源代码项目如下所示,为Maven项目,若需运行,请自行获取相关的依赖包。
点击这里获取源代码
7 参考资料
[1] Spring MVC统一处理异常的方法
http://hi.baidu.com/99999999hao/blog/item/25da70174bfbf642f919b8c3.html
[2] SpringMVC 异常处理初探
http://exceptioneye.iteye.com/blog/1306150
[3] Spring3 MVC 深入研究
http://elf8848.iteye.com/blog/875830
[4] Spring MVC异常处理
http://blog.csdn.net/rj042/article/details/7380442
在J2EE项目的开发中,不管是对底层的数据库操作过程,还是业务层的处理过程,还是控制层的处理过程,都不可避免会遇到各种可预知的、不可预知的异常需要处理。每个过程都单独处理异常,系统的代码耦合度高,工作量大且不好统一,维护的工作量也很大。
那么,能不能将所有类型的异常处理从各处理过程解耦出来,这样既保证了相关处理过程的功能较单一,也实现了异常信息的统一处理和维护?答案是肯定的。下面将介绍使用Spring MVC统一处理异常的解决和实现过程。
2 分析
Spring MVC处理异常有3种方式:
(1)使用Spring MVC提供的简单异常处理器SimpleMappingExceptionResolver;
(2)实现Spring的异常处理接口HandlerExceptionResolver 自定义自己的异常处理器;
(3)使用@ExceptionHandler注解实现异常处理;
3 实战
3.1 引言
为了验证Spring MVC的3种异常处理方式的实际效果,我们需要开发一个测试项目,从Dao层、Service层、Controller层分别抛出不同的异常,然后分别集成3种方式进行异常处理,从而比较3种方式的优缺点。
3.2 实战项目
3.2.1 项目结构
3.2.2 Dao层代码
- @Repository("testDao")
- public class TestDao {
- public void exception(Integer id) throws Exception {
- switch(id) {
- case 1:
- throw new BusinessException("12", "dao12");
- case 2:
- throw new BusinessException("22", "dao22");
- case 3:
- throw new BusinessException("32", "dao32");
- case 4:
- throw new BusinessException("42", "dao42");
- case 5:
- throw new BusinessException("52", "dao52");
- default:
- throw new ParameterException("Dao Parameter Error");
- }
- }
- }
@Repository("testDao")
public class TestDao {
public void exception(Integer id) throws Exception {
switch(id) {
case 1:
throw new BusinessException("12", "dao12");
case 2:
throw new BusinessException("22", "dao22");
case 3:
throw new BusinessException("32", "dao32");
case 4:
throw new BusinessException("42", "dao42");
case 5:
throw new BusinessException("52", "dao52");
default:
throw new ParameterException("Dao Parameter Error");
}
}
}
3.2.3 Service层代码
- public interface TestService {
- public void exception(Integer id) throws Exception;
- public void dao(Integer id) throws Exception;
- }
- @Service("testService")
- public class TestServiceImpl implements TestService {
- @Resource
- private TestDao testDao;
- public void exception(Integer id) throws Exception {
- switch(id) {
- case 1:
- throw new BusinessException("11", "service11");
- case 2:
- throw new BusinessException("21", "service21");
- case 3:
- throw new BusinessException("31", "service31");
- case 4:
- throw new BusinessException("41", "service41");
- case 5:
- throw new BusinessException("51", "service51");
- default:
- throw new ParameterException("Service Parameter Error");
- }
- }
- @Override
- public void dao(Integer id) throws Exception {
- testDao.exception(id);
- }
- }
public interface TestService {
public void exception(Integer id) throws Exception;
public void dao(Integer id) throws Exception;
}
@Service("testService")
public class TestServiceImpl implements TestService {
@Resource
private TestDao testDao;
public void exception(Integer id) throws Exception {
switch(id) {
case 1:
throw new BusinessException("11", "service11");
case 2:
throw new BusinessException("21", "service21");
case 3:
throw new BusinessException("31", "service31");
case 4:
throw new BusinessException("41", "service41");
case 5:
throw new BusinessException("51", "service51");
default:
throw new ParameterException("Service Parameter Error");
}
}
@Override
public void dao(Integer id) throws Exception {
testDao.exception(id);
}
}
3.2.4 Controller层代码
- @Controller
- public class TestController {
- @Resource
- private TestService testService;
- @RequestMapping(value = "/controller.do", method = RequestMethod.GET)
- public void controller(HttpServletResponse response, Integer id) throws Exception {
- switch(id) {
- case 1:
- throw new BusinessException("10", "controller10");
- case 2:
- throw new BusinessException("20", "controller20");
- case 3:
- throw new BusinessException("30", "controller30");
- case 4:
- throw new BusinessException("40", "controller40");
- case 5:
- throw new BusinessException("50", "controller50");
- default:
- throw new ParameterException("Controller Parameter Error");
- }
- }
- @RequestMapping(value = "/service.do", method = RequestMethod.GET)
- public void service(HttpServletResponse response, Integer id) throws Exception {
- testService.exception(id);
- }
- @RequestMapping(value = "/dao.do", method = RequestMethod.GET)
- public void dao(HttpServletResponse response, Integer id) throws Exception {
- testService.dao(id);
- }
- }
@Controller
public class TestController {
@Resource
private TestService testService;
@RequestMapping(value = "/controller.do", method = RequestMethod.GET)
public void controller(HttpServletResponse response, Integer id) throws Exception {
switch(id) {
case 1:
throw new BusinessException("10", "controller10");
case 2:
throw new BusinessException("20", "controller20");
case 3:
throw new BusinessException("30", "controller30");
case 4:
throw new BusinessException("40", "controller40");
case 5:
throw new BusinessException("50", "controller50");
default:
throw new ParameterException("Controller Parameter Error");
}
}
@RequestMapping(value = "/service.do", method = RequestMethod.GET)
public void service(HttpServletResponse response, Integer id) throws Exception {
testService.exception(id);
}
@RequestMapping(value = "/dao.do", method = RequestMethod.GET)
public void dao(HttpServletResponse response, Integer id) throws Exception {
testService.dao(id);
}
}
3.2.5 JSP页面代码
- <%@ page contentType="text/html; charset=UTF-8"%>
- <html>
- <head>
- <title>Maven Demo</title>
- </head>
- <body>
- <h1>所有的演示例子</h1>
- <h3>[url=./dao.do?id=1]Dao正常错误[/url]</h3>
- <h3>[url=./dao.do?id=10]Dao参数错误[/url]</h3>
- <h3>[url=./dao.do?id=]Dao未知错误[/url]</h3>
- <h3>[url=./service.do?id=1]Service正常错误[/url]</h3>
- <h3>[url=./service.do?id=10]Service参数错误[/url]</h3>
- <h3>[url=./service.do?id=]Service未知错误[/url]</h3>
- <h3>[url=./controller.do?id=1]Controller正常错误[/url]</h3>
- <h3>[url=./controller.do?id=10]Controller参数错误[/url]</h3>
- <h3>[url=./controller.do?id=]Controller未知错误[/url]</h3>
- <h3>[url=./404.do?id=1]404错误[/url]</h3>
- </body>
- </html>
<%@ page contentType="text/html; charset=UTF-8"%>
<html>
<head>
<title>Maven Demo</title>
</head>
<body>
<h1>所有的演示例子</h1>
<h3>[url=./dao.do?id=1]Dao正常错误[/url]</h3>
<h3>[url=./dao.do?id=10]Dao参数错误[/url]</h3>
<h3>[url=./dao.do?id=]Dao未知错误[/url]</h3>
<h3>[url=./service.do?id=1]Service正常错误[/url]</h3>
<h3>[url=./service.do?id=10]Service参数错误[/url]</h3>
<h3>[url=./service.do?id=]Service未知错误[/url]</h3>
<h3>[url=./controller.do?id=1]Controller正常错误[/url]</h3>
<h3>[url=./controller.do?id=10]Controller参数错误[/url]</h3>
<h3>[url=./controller.do?id=]Controller未知错误[/url]</h3>
<h3>[url=./404.do?id=1]404错误[/url]</h3>
</body>
</html>
3.3 集成异常处理
3.3.1 使用SimpleMappingExceptionResolver实现异常处理
1、在Spring的配置文件applicationContext.xml中增加以下内容:
- <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
- <!-- 定义默认的异常处理页面,当该异常类型的注册时使用 -->
- <property name="defaultErrorView" value="error"></property>
- <!-- 定义异常处理页面用来获取异常信息的变量名,默认名为exception -->
- <property name="exceptionAttribute" value="ex"></property>
- <!-- 定义需要特殊处理的异常,用类名或完全路径名作为key,异常也页名作为值 -->
- <property name="exceptionMappings">
- <props>
- <prop key="cn.basttg.core.exception.BusinessException">error-business</prop>
- <prop key="cn.basttg.core.exception.ParameterException">error-parameter</prop>
- <!-- 这里还可以继续扩展对不同异常类型的处理 -->
- </props>
- </property>
- </bean>
2、启动测试项目,经验证,Dao层、Service层、Controller层抛出的异常(业务异常BusinessException、参数异常ParameterException和其它的异常Exception)都能准确显示定义的异常处理页面,达到了统一异常处理的目标。
3、从上面的集成过程可知,使用SimpleMappingExceptionResolver进行异常处理,具有集成简单、有良好的扩展性、对已有代码没有入侵性等优点,但该方法仅能获取到异常信息,若在出现异常时,对需要获取除异常以外的数据的情况不适用。
3.3.2 实现HandlerExceptionResolver 接口自定义异常处理器
1、增加HandlerExceptionResolver 接口的实现类MyExceptionHandler,代码如下:
- public class MyExceptionHandler implements HandlerExceptionResolver {
- public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
- Exception ex) {
- Map<String, Object> model = new HashMap<String, Object>();
- model.put("ex", ex);
- // 根据不同错误转向不同页面
- if(ex instanceof BusinessException) {
- return new ModelAndView("error-business", model);
- }else if(ex instanceof ParameterException) {
- return new ModelAndView("error-parameter", model);
- } else {
- return new ModelAndView("error", model);
- }
- }
- }
public class MyExceptionHandler implements HandlerExceptionResolver {
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
Exception ex) {
Map<String, Object> model = new HashMap<String, Object>();
model.put("ex", ex);
// 根据不同错误转向不同页面
if(ex instanceof BusinessException) {
return new ModelAndView("error-business", model);
}else if(ex instanceof ParameterException) {
return new ModelAndView("error-parameter", model);
} else {
return new ModelAndView("error", model);
}
}
}
2、在Spring的配置文件applicationContext.xml中增加以下内容:
- <bean id="exceptionHandler" class="cn.basttg.core.exception.MyExceptionHandler"/>
3、启动测试项目,经验证,Dao层、Service层、Controller层抛出的异常(业务异常BusinessException、参数异常ParameterException和其它的异常Exception)都能准确显示定义的异常处理页面,达到了统一异常处理的目标。
4、从上面的集成过程可知,使用实现HandlerExceptionResolver接口的异常处理器进行异常处理,具有集成简单、有良好的扩展性、对已有代码没有入侵性等优点,同时,在异常处理时能获取导致出现异常的对象,有利于提供更详细的异常处理信息。
3.3.3 使用@ExceptionHandler注解实现异常处理
1、增加BaseController类,并在类中使用@ExceptionHandler注解声明异常处理,代码如下:
- public class BaseController {
- /** 基于@ExceptionHandler异常处理 */
- @ExceptionHandler
- public String exp(HttpServletRequest request, Exception ex) {
- request.setAttribute("ex", ex);
- // 根据不同错误转向不同页面
- if(ex instanceof BusinessException) {
- return "error-business";
- }else if(ex instanceof ParameterException) {
- return "error-parameter";
- } else {
- return "error";
- }
- }
- }
public class BaseController {
/** 基于@ExceptionHandler异常处理 */
@ExceptionHandler
public String exp(HttpServletRequest request, Exception ex) {
request.setAttribute("ex", ex);
// 根据不同错误转向不同页面
if(ex instanceof BusinessException) {
return "error-business";
}else if(ex instanceof ParameterException) {
return "error-parameter";
} else {
return "error";
}
}
}
2、修改代码,使所有需要异常处理的Controller都继承该类,如下所示,修改后的TestController类继承于BaseController:
- public class TestController extends BaseController
public class TestController extends BaseController
3、启动测试项目,经验证,Dao层、Service层、Controller层抛出的异常(业务异常BusinessException、参数异常ParameterException和其它的异常Exception)都能准确显示定义的异常处理页面,达到了统一异常处理的目标。
4、从上面的集成过程可知,使用@ExceptionHandler注解实现异常处理,具有集成简单、有扩展性好(只需要将要异常处理的Controller类继承于BaseController即可)、不需要附加Spring配置等优点,但该方法对已有代码存在入侵性(需要修改已有代码,使相关类继承于BaseController),在异常处理时不能获取除异常以外的数据。
3.4 未捕获异常的处理
对于Unchecked Exception而言,由于代码不强制捕获,往往被忽略,如果运行期产生了Unchecked Exception,而代码中又没有进行相应的捕获和处理,则我们可能不得不面对尴尬的404、500……等服务器内部错误提示页面。
我们需要一个全面而有效的异常处理机制。目前大多数服务器也都支持在Web.xml中通过<error-page>(Websphere/Weblogic)或者<error-code>(Tomcat)节点配置特定异常情况的显示页面。修改web.xml文件,增加以下内容:
- <!-- 出错页面定义 -->
- <error-page>
- <exception-type>java.lang.Throwable</exception-type>
- <location>/500.jsp</location>
- </error-page>
- <error-page>
- <error-code>500</error-code>
- <location>/500.jsp</location>
- </error-page>
- <error-page>
- <error-code>404</error-code>
- <location>/404.jsp</location>
- </error-page>
- <!-- 这里可继续增加服务器错误号的处理及对应显示的页面 -->
4 解决结果
1、运行测试项目显示的首页,如下图所示:
2、业务错误显示的页面,如下图所示:
3、参数错误显示的页面,如下图所示:
4、未知错误显示的页面,如下图所示:
5、服务器内部错误页面,如下图所示:
5 总结
综合上述可知,Spring MVC集成异常处理3种方式都可以达到统一异常处理的目标。从3种方式的优缺点比较,若只需要简单的集成异常处理,推荐使用SimpleMappingExceptionResolver即可;若需要集成的异常处理能够更具个性化,提供给用户更详细的异常信息,推荐自定义实现HandlerExceptionResolver接口的方式;若不喜欢Spring配置文件或要实现“零配置”,且能接受对原有代码的适当入侵,则建议使用@ExceptionHandler注解方式。
6 源代码
源代码项目如下所示,为Maven项目,若需运行,请自行获取相关的依赖包。
点击这里获取源代码
7 参考资料
[1] Spring MVC统一处理异常的方法
http://hi.baidu.com/99999999hao/blog/item/25da70174bfbf642f919b8c3.html
[2] SpringMVC 异常处理初探
http://exceptioneye.iteye.com/blog/1306150
[3] Spring3 MVC 深入研究
http://elf8848.iteye.com/blog/875830
[4] Spring MVC异常处理
http://blog.csdn.net/rj042/article/details/7380442
评论
20 楼
join_lin 2014-04-08
LZ写得不错,有用。
19 楼
jzhx107 2014-03-17
不错,谢谢!
18 楼
gary_bu 2014-03-05
很专业,学习了
17 楼
yjlleilei 2014-02-19
真是专业!
16 楼
cgs1999 2013-12-23
qingbo921 写道
你好,楼主,最近我在某某框架上看到一种特殊的效果:
当用户请求某个页面操作按钮,只要执行失败,不进行页面跳转的情况下,统一抛出异常并
alert出来!目前我也想这么搞,能否给点思路呢???
当用户请求某个页面操作按钮,只要执行失败,不进行页面跳转的情况下,统一抛出异常并
alert出来!目前我也想这么搞,能否给点思路呢???
这个是采用ajax来实现的,推荐使用jquery,参考代码:
- @Controller
- public class TestController {
- @RequestMapping(value = "/ajax.do")
- public void ajax(HttpServletResponse response, User user) throws Exception {
- if(user.getId()==null) {
- if(user.getUserName()==null || "".equals(user.getUserName())) {
- AjaxUtils.rendJson(response, false, "用户名为空创建失败");
- } else {
- AjaxUtils.rendJson(response, true, "创建用户成功");
- }
- } else {
- AjaxUtils.rendJson(response, true, "修改用户成功");
- }
- }
- ...
- }
@Controller
public class TestController {
@RequestMapping(value = "/ajax.do")
public void ajax(HttpServletResponse response, User user) throws Exception {
if(user.getId()==null) {
if(user.getUserName()==null || "".equals(user.getUserName())) {
AjaxUtils.rendJson(response, false, "用户名为空创建失败");
} else {
AjaxUtils.rendJson(response, true, "创建用户成功");
}
} else {
AjaxUtils.rendJson(response, true, "修改用户成功");
}
}
...
}
- <!DOCTYPE html>
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
- <title>AJAX请求</title>
- <script type="text/javascript" src="./jquery-1.10.2.min.js"></script>
- <script type="text/javascript">
- $(function(){
- init();
- });
- function init(){
- $("#ajaxCreate").click(function(){
- doAjax({userName: "cgs1999", realName: "cgs"});
- })
- $("#ajaxUpdate").click(function(){
- doAjax({id: 1, userName: "cgs1999", realName: "cgs"});
- })
- $("#ajaxFail").click(function(){
- doAjax({realName: "cgs"});
- })
- }
- function doAjax(data) {
- $.post("./ajax.do",data,function(t){
- if(!t.success){
- alert("操作失败, 原因:" + t.message);
- }else{
- alert("操作成功, 描述:" + t.message);
- }
- },"json").error(function(){
- alert("未知错误");
- });
- }
- </script>
- </head>
- <body>
- <br />
- <a id="ajaxCreate" href="#">创建用户成功</a>
- <br />
- <a id="ajaxUpdate" href="#">修改用户成功</a>
- <br />
- <a id="ajaxFail" href="#">用户名为空创建失败</a>
- </body>
- </html>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>AJAX请求</title>
<script type="text/javascript" src="./jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(function(){
init();
});
function init(){
$("#ajaxCreate").click(function(){
doAjax({userName: "cgs1999", realName: "cgs"});
})
$("#ajaxUpdate").click(function(){
doAjax({id: 1, userName: "cgs1999", realName: "cgs"});
})
$("#ajaxFail").click(function(){
doAjax({realName: "cgs"});
})
}
function doAjax(data) {
$.post("./ajax.do",data,function(t){
if(!t.success){
alert("操作失败, 原因:" + t.message);
}else{
alert("操作成功, 描述:" + t.message);
}
},"json").error(function(){
alert("未知错误");
});
}
</script>
</head>
<body>
<br />
<a id="ajaxCreate" href="#">创建用户成功</a>
<br />
<a id="ajaxUpdate" href="#">修改用户成功</a>
<br />
<a id="ajaxFail" href="#">用户名为空创建失败</a>
</body>
</html>
15 楼
qingbo921 2013-12-20
你好,楼主,最近我在某某框架上看到一种特殊的效果:
当用户请求某个页面操作按钮,只要执行失败,不进行页面跳转的情况下,统一抛出异常并
alert出来!目前我也想这么搞,能否给点思路呢???
当用户请求某个页面操作按钮,只要执行失败,不进行页面跳转的情况下,统一抛出异常并
alert出来!目前我也想这么搞,能否给点思路呢???
14 楼
cgs1999 2013-10-22
weipeng1986 写道
貌似如果是ajax请求的话,异常不会捕捉到,求解
看了一下之前的代码,controllerAjax方法定义有问题,不应该抛出异常,即将下面代码中的throws Exception去掉试试
之前提供的代码
------------------------------------------------
- @Controller
- public class TestController {
- @Resource
- private TestService testService;
- @RequestMapping(value = "/controllerAjax.do", method = RequestMethod.GET)
- public void controllerAjax(HttpServletResponse response, Integer id) throws Exception {
- try {
- testService.dao(id);
- AjaxUtils.rendJson(response, true, "操作成功");
- } catch(Exception be) {
- AjaxUtils.rendJson(response, false, "操作失败");
- }
- }
- ……
- }
@Controller
public class TestController {
@Resource
private TestService testService;
@RequestMapping(value = "/controllerAjax.do", method = RequestMethod.GET)
public void controllerAjax(HttpServletResponse response, Integer id) throws Exception {
try {
testService.dao(id);
AjaxUtils.rendJson(response, true, "操作成功");
} catch(Exception be) {
AjaxUtils.rendJson(response, false, "操作失败");
}
}
……
}
修改后的代码
------------------------------------------------
- @Controller
- public class TestController {
- @Resource
- private TestService testService;
- @RequestMapping(value = "/controllerAjax.do", method = RequestMethod.GET)
- public void controllerAjax(HttpServletResponse response, Integer id) {
- try {
- testService.dao(id);
- AjaxUtils.rendJson(response, true, "操作成功");
- } catch(Exception be) {
- AjaxUtils.rendJson(response, false, "操作失败");
- }
- }
- ……
- }
@Controller
public class TestController {
@Resource
private TestService testService;
@RequestMapping(value = "/controllerAjax.do", method = RequestMethod.GET)
public void controllerAjax(HttpServletResponse response, Integer id) {
try {
testService.dao(id);
AjaxUtils.rendJson(response, true, "操作成功");
} catch(Exception be) {
AjaxUtils.rendJson(response, false, "操作失败");
}
}
……
}
13 楼
weipeng1986 2013-10-22
貌似如果是ajax请求的话,异常不会捕捉到,求解
12 楼
weipeng1986 2013-10-22
很清晰明了
11 楼
cgs1999 2013-08-04
snailxr 写道
楼主,controller里里面有的方法是返回到页面,但是有的方法如果存在异常的话需要通过json返回异信息,这个有木有好的解决方案
可以通过在controller中捕获相关的Exception,将相关的异常封装为JSON继续抛出
- /**
- * 系统业务异常
- */
- public class BusinessException extends RuntimeException {
- /** serialVersionUID */
- private static final long serialVersionUID = 2332608236621015980L;
- private String code;
- public BusinessException() {
- super();
- }
- public BusinessException(String message) {
- super(message);
- }
- public BusinessException(String code, String message) {
- super(message);
- this.code = code;
- }
- public BusinessException(Throwable cause) {
- super(cause);
- }
- public BusinessException(String message, Throwable cause) {
- super(message, cause);
- }
- public BusinessException(String code, String message, Throwable cause) {
- super(message, cause);
- this.code = code;
- }
- public String getCode() {
- return code;
- }
- public void setCode(String code) {
- this.code = code;
- }
- }
- public class ParameterException extends RuntimeException {
- /** serialVersionUID */
- private static final long serialVersionUID = 6417641452178955756L;
- public ParameterException() {
- super();
- }
- public ParameterException(String message) {
- super(message);
- }
- public ParameterException(Throwable cause) {
- super(cause);
- }
- public ParameterException(String message, Throwable cause) {
- super(message, cause);
- }
- }
- @Controller
- public class TestController {
- @Resource
- private TestService testService;
- @RequestMapping(value = "/controllerJson.do", method = RequestMethod.GET)
- public void controllerJson(HttpServletResponse response, Integer id) throws Exception {
- try {
- testService.dao(id);
- } catch(Exception be) {
- throw new BusinessException("{errorCode: 10001, errorMessage: \"错误信息\"}");
- }
- }
- ……
- }
/**
* 系统业务异常
*/
public class BusinessException extends RuntimeException {
/** serialVersionUID */
private static final long serialVersionUID = 2332608236621015980L;
private String code;
public BusinessException() {
super();
}
public BusinessException(String message) {
super(message);
}
public BusinessException(String code, String message) {
super(message);
this.code = code;
}
public BusinessException(Throwable cause) {
super(cause);
}
public BusinessException(String message, Throwable cause) {
super(message, cause);
}
public BusinessException(String code, String message, Throwable cause) {
super(message, cause);
this.code = code;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
}
public class ParameterException extends RuntimeException {
/** serialVersionUID */
private static final long serialVersionUID = 6417641452178955756L;
public ParameterException() {
super();
}
public ParameterException(String message) {
super(message);
}
public ParameterException(Throwable cause) {
super(cause);
}
public ParameterException(String message, Throwable cause) {
super(message, cause);
}
}
@Controller
public class TestController {
@Resource
private TestService testService;
@RequestMapping(value = "/controllerJson.do", method = RequestMethod.GET)
public void controllerJson(HttpServletResponse response, Integer id) throws Exception {
try {
testService.dao(id);
} catch(Exception be) {
throw new BusinessException("{errorCode: 10001, errorMessage: \"错误信息\"}");
}
}
……
}
若是ajax可使用一些代码处理
- import java.io.IOException;
- import javax.servlet.http.HttpServletResponse;
- import net.sf.json.JSONObject;
- import com.kedacom.common.Message;
- public class AjaxUtils {
- public static void rendText(HttpServletResponse response, String content)
- throws IOException {
- response.setCharacterEncoding("UTF-8");
- response.getWriter().write(content);
- }
- public static void rendJson(HttpServletResponse response, boolean success, String message) throws IOException{
- JSONObject json = new JSONObject();
- json.put("isSuccess", success());
- json.put("message", message);
- rendText(response, json.toString());
- }
- }
- @Controller
- public class TestController {
- @Resource
- private TestService testService;
- @RequestMapping(value = "/controllerAjax.do", method = RequestMethod.GET)
- public void controllerAjax(HttpServletResponse response, Integer id) throws Exception {
- try {
- testService.dao(id);
- AjaxUtils.rendJson(response, true, "操作成功");
- } catch(Exception be) {
- AjaxUtils.rendJson(response, false, "操作");
- }
- }
- ……
- }
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import com.kedacom.common.Message;
public class AjaxUtils {
public static void rendText(HttpServletResponse response, String content)
throws IOException {
response.setCharacterEncoding("UTF-8");
response.getWriter().write(content);
}
public static void rendJson(HttpServletResponse response, boolean success, String message) throws IOException{
JSONObject json = new JSONObject();
json.put("isSuccess", success());
json.put("message", message);
rendText(response, json.toString());
}
}
@Controller
public class TestController {
@Resource
private TestService testService;
@RequestMapping(value = "/controllerAjax.do", method = RequestMethod.GET)
public void controllerAjax(HttpServletResponse response, Integer id) throws Exception {
try {
testService.dao(id);
AjaxUtils.rendJson(response, true, "操作成功");
} catch(Exception be) {
AjaxUtils.rendJson(response, false, "操作");
}
}
……
}
10 楼
snailxr 2013-07-31
楼主,controller里里面有的方法是返回到页面,但是有的方法如果存在异常的话需要通过json返回异信息,这个有木有好的解决方案
9 楼
cgs1999 2013-04-22
zf95834073 写道
非常感谢,问题已经圆满解决了,并且迁入到了框架里,领导也夸我啦,哈哈哈哈~~~~~
呵呵呵~~,替你高兴,解决了就好:D
8 楼
zf95834073 2013-04-22
非常感谢,问题已经圆满解决了,并且迁入到了框架里,领导也夸我啦,哈哈哈哈~~~~~
7 楼
cgs1999 2013-04-18
sunwang810812 写道
佩服楼主,估计永远也达不到楼主的水平了,受益匪浅!!!!!感谢中
我相信努力你也可以做到,甚至比我好~~。
其实本文也是参考了很多前辈的文章,在此感谢。
6 楼
cgs1999 2013-04-18
zf95834073 写道
麻烦再问一下,我使用的是SimpleMappingExceptionResolver这个方式,我理解的是,统一异常处理,是不是dao层抛出异常到service,service再抛出到controller,最终统一处理呢,如果在controller统一处理,那为什么dao,service还要用try catch呢,那样岂不是每个方法都要有try catch了吗,我之前以为如果统一异常处理,代码中就不需要try catch了,我的理解是不是根本就是错误的呢,谢谢
1、你的理解是对的。
异常处理是一层一层往上抛,最终通过指定的异常处理方式统一处理。
2、为什么dao、service和controller还要用try...catch?
其实可以不用try...catch
使用try...catch,主要是统一规范捕获的异常处理,对异常可以捕获后不往上抛,或转换捕获到的异常为较明确的异常继续往上抛出
举个例子NullPointerException,若不做处理,用户在界面上会直接看到Exception信息,但作为终端用户,他是不清楚到底是怎么回事。但如果在controller、service、dao等转换成“用户不存在或已被删除”、“会议已被取消”等这样的信息是不是更好更清楚呢?
5 楼
sunwang810812 2013-04-16
佩服楼主,估计永远也达不到楼主的水平了,受益匪浅!!!!!感谢中
4 楼
zf95834073 2013-04-16
麻烦再问一下,我使用的是SimpleMappingExceptionResolver这个方式,我理解的是,统一异常处理,是不是dao层抛出异常到service,service再抛出到controller,最终统一处理呢,如果在controller统一处理,那为什么dao,service还要用try catch呢,那样岂不是每个方法都要有try catch了吗,我之前以为如果统一异常处理,代码中就不需要try catch了,我的理解是不是根本就是错误的呢,谢谢
3 楼
zf95834073 2013-04-16
谢谢了,非常非常感谢~~~
2 楼
cgs1999 2013-04-15
zf95834073 写道
您好,我按着您的例子,已经配置到我的项目里了,但是我实际运用的时候,怎么用呢,能贴几个实际使用controller,serveice,dao的方法带捕获异常的方法吗,谢谢~~~
实际应用中,“3.3 集成异常处理 ”部分,只需要根据实际处理需要,选择集成一种方式即可。另,结合“3.4 未捕获异常的处理”部分,处理404和500的错误。
若仅需提示异常信息,推荐使用“3.3.1 使用SimpleMappingExceptionResolver实现异常处理”,该方式简单、扩展方便、松耦合。
实际使用的方法,实际上在范例代码中已给出。Spring MVC异常处理都是对controller层抛出的异常进行处理的,所以对于dao、service的异常只需要一层一层的往上抛到controller层,然后在Controller层抛出该异常即可。
特别注意
(1)可在dao、service和controller层try...catch底层抛上来的异常,然后根据需要转化为其它的异常继续往上抛;
(2)不要在dao、service和controller层把异常给try...catch后而不往上抛异常,这样Spring MVC框架是处理不到异常的。
鉴于范例代码测试成分比较大,可能不是很明了,现修改一下代码:
- @Repository("userDao")
- public class UserDao {
- public void getById(Integer id) throws Exception {
- try {
- ...
- } catch(Exception e) {
- throw new BusinessException("用户不存在");
- }
- }
- public void create(User user) throws Exception {
- try {
- ...
- } catch(Exception e) {
- throw new BusinessException("保存失败");
- }
- }
- public void update(User user) throws Exception {
- try {
- ...
- } catch(Exception e) {
- throw new BusinessException("修改失败");
- }
- }
- public void delete(Integer id) throws Exception {
- try {
- ...
- } catch(Exception e) {
- throw new BusinessException("删除失败");
- }
- }
- }
- public interface UserService {
- public void getById(Integer id) throws Exception;
- public void create(User user) throws Exception;
- public void update(User user) throws Exception;
- public void delete(Integer id) throws Exception;
- }
- @Service("userService")
- public class UserServiceImpl implements UserService {
- @Resource
- private UserDao userDao;
- @Override
- public void getById(Integer id) throws Exception {
- ...
- userDao.getById(id);
- }
- @Override
- public void create(User user) throws Exception {
- try{
- ...
- userDao.create(user);
- } catch(Exception e) {
- throw new BusinessException("创建用户失败,原因...");
- }
- }
- @Override
- public void update(User user) throws Exception {
- try{
- ...
- userDao.update(user);
- } catch(Exception e) {
- throw new BusinessException("修改用户失败,原因...");
- }
- }
- @Override
- public void delete(Integer id) throws Exception {
- try{
- ...
- userDao.delete(id);
- } catch(Exception e) {
- throw new BusinessException("删除用户失败,原因...");
- }
- }
- }
- @Controller
- public class UserController {
- @Resource
- private UserService userService;
- @RequestMapping(value = "/getById.do", method = RequestMethod.GET)
- public void getById(HttpServletResponse response, Integer id) throws Exception {
- try{
- ...
- userService.getById(id);
- } catch(Exception e) {
- throw new ParameterException("参数不正确");
- }
- }
- @RequestMapping(value = "/create.do", method = RequestMethod.POST)
- public void create(HttpServletResponse response, User user) throws Exception {
- ...
- userService.create(user);
- }
- @RequestMapping(value = "/update.do", method = RequestMethod.POST)
- public void update(HttpServletResponse response, User user) throws Exception {
- ...
- userService.update(user);
- }
- @RequestMapping(value = "/delete.do", method = RequestMethod.POST)
- public void delete(HttpServletResponse response, Integer id) throws Exception {
- ...
- userService.delete(id);
- }
- }
@Repository("userDao")
public class UserDao {
public void getById(Integer id) throws Exception {
try {
...
} catch(Exception e) {
throw new BusinessException("用户不存在");
}
}
public void create(User user) throws Exception {
try {
...
} catch(Exception e) {
throw new BusinessException("保存失败");
}
}
public void update(User user) throws Exception {
try {
...
} catch(Exception e) {
throw new BusinessException("修改失败");
}
}
public void delete(Integer id) throws Exception {
try {
...
} catch(Exception e) {
throw new BusinessException("删除失败");
}
}
}
public interface UserService {
public void getById(Integer id) throws Exception;
public void create(User user) throws Exception;
public void update(User user) throws Exception;
public void delete(Integer id) throws Exception;
}
@Service("userService")
public class UserServiceImpl implements UserService {
@Resource
private UserDao userDao;
@Override
public void getById(Integer id) throws Exception {
...
userDao.getById(id);
}
@Override
public void create(User user) throws Exception {
try{
...
userDao.create(user);
} catch(Exception e) {
throw new BusinessException("创建用户失败,原因...");
}
}
@Override
public void update(User user) throws Exception {
try{
...
userDao.update(user);
} catch(Exception e) {
throw new BusinessException("修改用户失败,原因...");
}
}
@Override
public void delete(Integer id) throws Exception {
try{
...
userDao.delete(id);
} catch(Exception e) {
throw new BusinessException("删除用户失败,原因...");
}
}
}
@Controller
public class UserController {
@Resource
private UserService userService;
@RequestMapping(value = "/getById.do", method = RequestMethod.GET)
public void getById(HttpServletResponse response, Integer id) throws Exception {
try{
...
userService.getById(id);
} catch(Exception e) {
throw new ParameterException("参数不正确");
}
}
@RequestMapping(value = "/create.do", method = RequestMethod.POST)
public void create(HttpServletResponse response, User user) throws Exception {
...
userService.create(user);
}
@RequestMapping(value = "/update.do", method = RequestMethod.POST)
public void update(HttpServletResponse response, User user) throws Exception {
...
userService.update(user);
}
@RequestMapping(value = "/delete.do", method = RequestMethod.POST)
public void delete(HttpServletResponse response, Integer id) throws Exception {
...
userService.delete(id);
}
}
1 楼
zf95834073 2013-04-12
您好,我按着您的例子,已经配置到我的项目里了,但是我实际运用的时候,怎么用呢,能贴几个实际使用controller,serveice,dao的方法带捕获异常的方法吗,谢谢~~~
发表评论
- 浏览: 37839 次
- 性别:
- 来自: 上海
最新评论
- join_lin: LZ写得不错,有用。
使用Spring MVC统一异常处理实战 - jzhx107: 不错,谢谢!
使用Spring MVC统一异常处理实战 - gary_bu: 很专业,学习了
使用Spring MVC统一异常处理实战 - yjlleilei: 真是专业!
使用Spring MVC统一异常处理实战 - Just1n: 官网上找到的示例代码,跟楼主这里的不一样。请问楼主这个是在哪看 ...
使用Java操作LDAP案例
评论排行榜