最近在搭建新的应用框架,彻底抛弃了struts,应用spring mvc,在jsp端也只使用jstl和jquery,根据情况可能会用tile。
异常的统一处理,是框架必要考虑点。
Spring提供两种方式实现异常处理:一种是直接实现自己的HandlerExceptionResolver,另一种是使用注解的方式实现一个专门用于处理异常的Controller——ExceptionHandler。
由于方法二需要对每个Controller类的提供一个异常方法,所以不采用该方法。
一、直接实现自己的HandlerExceptionResolver
HandlerExceptionResolver是一个接口,Spring提供其两个实现:DefaultExceptionResolver和SimpleMappingExceptionResolver,
DefaultExceptionResolver配置性不强,所以决定自定义一个SimpleMappingExceptionResolver继承Spring的SimpleMappingExceptionResolver,在其基础上同时支持jsp和json的异常捕捉。
1、自定义SimpleMappingExceptionResolver类
public class CustomSimpleMappingExceptionResolver extends
SimpleMappingExceptionResolver {
@Override
protected ModelAndView doResolveException(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex) {
String viewName = super.determineViewName(ex, request);
if (viewName != null) {// JSP格式返回
if (!(request.getHeader("accept").indexOf("application/json") > -1 || (request
.getHeader("X-Requested-With")!= null && request
.getHeader("X-Requested-With").indexOf("XMLHttpRequest") > -1))) {
// 如果不是异步请求
// Apply HTTP status code for error views, if specified.
// Only apply it if we're processing a top-level request.
Integer statusCode = super.determineStatusCode(request, viewName);
if (statusCode != null) {
super.applyStatusCodeIfPossible(request, response, statusCode);
}
return super.getModelAndView(viewName, ex, request);
} else {// JSON格式返回
try {
PrintWriter writer = response.getWriter();
writer.write(ex.getMessage());
writer.flush();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
} else {
return null;
} //if
}//doResolveException
}
2、修改Spring的配置XML,定义CustomSimpleMappingExceptionResolver的Bean
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:security="http://www.springframework.org/schema/security"
xmlns:p="http://www.springframework.org/schema/p" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!-- 配置WebBindingInitializer ,比如日期初始化等 -->
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<util:list id="beanList">
<ref bean="mappingJacksonHttpMessageConverter" />
</util:list>
</property>
</bean>
<!-- Autodetect annotated controllers -->
<context:component-scan
base-package="com.winssage.ccp.module.*,com.winssage.ccp.module.*.*," />
<!--mvc:annotation-driven 会自动注册DefaultAnnotationHandlerMapping和AnnotationMethodHandlerAdapter两个实例 -->
<!-- 启动SpringMVC的注解功能,它会自动注册HandlerMapping、 HandlerAdapter、ExceptionResolver的相关实例 -->
<mvc:annotation-driven />
<!-- JSON转换器 -->
<bean id="mappingJacksonHttpMessageConverter"
class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
</list>
</property>
</bean>
<!-- 异常处理-->
<bean id="exceptionResolver" class="com.winssage.framework.server.exception.CustomSimpleMappingExceptionResolver">
<property name="defaultErrorView" value="error/errorpage"/>
<!-- 定义异常处理页面用来获取异常信息的变量名,如果不添加exceptionAttribute属性,则默认为exception -->
<property name="exceptionAttribute" value="exception"/>
<property name="exceptionMappings">
<props>
<prop key="java.lang.exception">error/errorpage</prop> <!-- 不设置将根据defaultErrorView -->
</props>
</property>
</bean>
<!-- Resolves views selected for rendering by @Controllers to .jsp resources
in the /WEB-INF/views directory -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/pages/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
3、创建errorpage.jsp,放置相应目录
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Hello World!error!~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ${exception} </h1>
</body>
</html>4、如上所配置,当jsp加载遇到异常,则跳转到errorpage.jsp;如通过json访问服务器发生异常,则在error方法中直接返回错误信息,如下例,在error方法的data.responseText直接显示错误信息。
function ajaxTest()
{
$.ajax( {
type : 'GET',
//contentType : 'application/json',
url : '${basePath}/josontest.html',
async: false,//禁止ajax的异步操作,使之顺序执行。
dataType : 'json',
success : function(data,textStatus){
alert(JSON.stringify(data));
},
error : function(data,textstatus){
alert(data.responseText);
}
});
}
二、参考
1、http://m.blog.youkuaiyun.com/blog/mr__fang/9092511
2、http://blog.youkuaiyun.com/sinlff/article/details/5872724
本文介绍了一种在Spring MVC中实现异常处理的方法,通过自定义SimpleMappingExceptionResolver来支持JSP和JSON异常处理,并提供了详细的配置步骤。
1万+

被折叠的 条评论
为什么被折叠?



