这篇文章描述了在Spring MVC 3中执行错误处理的不同技术。该代码在GitHub上的Spring-MVC-Error-Handling目录中可用。 它基于带有注释的Spring MVC示例。
在Spring 3之前处理异常
在Spring 3之前,使用HandlerExceptionResolvers处理异常。 此接口定义一个方法:
ModelAndView resolveException(
HttpServletRequest request,
HttpServletResponse response,
Object handler,
Exception ex)
注意,它返回一个ModelAndView对象。 因此,遇到错误意味着将被转发到特殊页面。 但是,此方法不适用于REST Ajax对JSON的调用(例如)。 在这种情况下,我们不想返回页面,我们可能想返回特定的HTTP状态代码。 提供了进一步描述的解决方案。
为了本示例的缘故,已经创建了两个假的CustomizedException1和CustomizedException2异常。 要将自定义的异常映射到视图,可以(并且仍然可以)使用impleMappingExceptionResolver :
SimpleMappingExceptionResolver getSimpleMappingExceptionResolver() {
SimpleMappingExceptionResolver result
= new SimpleMappingExceptionResolver();
// Setting customized exception mappings
Properties p = new Properties();
p.put(CustomizedException1.class.getName(), 'Errors/Exception1');
result.setExceptionMappings(p);
// Unmapped exceptions will be directed there
result.setDefaultErrorView('Errors/Default');
// Setting a default HTTP status code
result.setDefaultStatusCode(HttpStatus.BAD_REQUEST.value());
return result;
}
我们将CustomizedException1映射到Errors / Exception1 JSP页面(视图)。 我们还为未映射的异常设置了默认错误视图,在此示例中为CustomizedException2。 我们还设置了默认的HTTP状态代码。
这是Exception1 JSP页面,默认页面与此类似:
<%@page contentType='text/html' pageEncoding='UTF-8'%>
<%@ taglib prefix='c' uri='http://java.sun.com/jsp/jstl/core' %>
<!doctype html>
<html lang='en'>
<head>
<meta http-equiv='Content-Type' content='text/html;' charset=UTF-8'>
<title>Welcome To Exception I !!!</title>
</head>
<body>
<h1>Welcome To Exception I !!!</h1>
Exception special message:<
${exception.specialMsg}
<a href='<c:url value='/'/>'>Home</a>
</body>
</html>
我们还创建了一个虚拟错误控制器来帮助触发这些异常:
@Controller
public class TriggeringErrorsController {
@RequestMapping(value = '/throwCustomizedException1')
public ModelAndView throwCustomizedException1(
HttpServletRequest request,HttpServletResponse response)
throws CustomizedException1 {
throw new CustomizedException1(
'Houston, we have a problem!');
}
@RequestMapping(value = '/throwCustomizedException2')
public ModelAndView throwCustomizedException2(
HttpServletRequest request,HttpServletResponse response)
throws CustomizedException2 {
throw new CustomizedException2(
'Something happened on the way to heaven!');
}
...
}
在Spring 3之前,将在Web.xml中将SimpleMappingExceptionResolver声明为@Bean。 但是,我们将使用HandlerExceptionResolverComposite,稍后将对其进行描述。
我们还在web.xml中为HTTP状态代码配置目标页面,这是处理问题的另一种方法:
<error-page>
<error-code>404</error-code>
<location>/WEB-INF/pages/Errors/My404.jsp</location>
</error-page>
从Spring 3.X开始有什么新功能?
@ResponseStatus批注是在调用方法时设置Http状态代码的新方法。 这些由ResponseStatusExceptionResolver处理。 @ExceptionHandler注释有助于在Spring中处理异常。 此类注释由AnnotationMethodHandlerExceptionResolver处理。
下面说明了如何在触发我们的自定义异常时使用这些注释将HTTP状态代码设置为响应。 该消息在响应的正文中返回:
@Controller
public class TriggeringErrorsController {
...
@ExceptionHandler(Customized4ExceptionHandler.class)
@ResponseStatus(value=HttpStatus.BAD_REQUEST)
@ResponseBody
public String handleCustomized4Exception(
Customized4ExceptionHandler ex) {
return ex.getSpecialMsg();
}
@RequestMapping(value = '/throwCustomized4ExceptionHandler')
public ModelAndView throwCustomized4ExceptionHandler(
HttpServletRequest request,HttpServletResponse response)
throws Customized4ExceptionHandler {
throw new Customized4ExceptionHandler('S.O.S !!!!');
}
}
在用户端,如果使用Ajax调用,则可以使用以下方法(我们正在使用JQuery)来检索错误:
$.ajax({
type: 'GET',
url: prefix + '/throwCustomized4ExceptionHandler',
async: true,
success: function(result) {
alert('Unexpected success !!!');
},
error: function(jqXHR, textStatus, errorThrown) {
alert(jqXHR.status + ' ' + jqXHR.responseText);
}
});
一些使用Ajax的人喜欢返回带有错误代码的JSON和一些用于处理异常的消息。 我觉得这太过分了。 一个简单的错误号和一条消息使其保持简单。
由于我们使用了多个解析器,因此我们需要一个复合解析器(如前所述):
@Configuration
public class ErrorHandling {
...
@Bean
HandlerExceptionResolverComposite getHandlerExceptionResolverComposite() {
HandlerExceptionResolverComposite result
= new HandlerExceptionResolverComposite();
List<HandlerExceptionResolver> l
= new ArrayList<HandlerExceptionResolver>();
l.add(new AnnotationMethodHandlerExceptionResolver());
l.add(new ResponseStatusExceptionResolver());
l.add(getSimpleMappingExceptionResolver());
l.add(new DefaultHandlerExceptionResolver());
result.setExceptionResolvers(l);
return result;
}
DefaultHandlerExceptionResolver解析标准的Spring异常并将其转换为相应的HTTP状态代码。
运行示例
编译后,可以使用mvn tomcat:run运行该示例。 然后,浏览:
http:// localhost:8585 / spring-mvc-error-handling /
主页将如下所示:
如果单击“例外1”链接,将显示以下页面:
如果单击“例外2”链接,将显示以下页面:
如果单击“异常处理程序”按钮,将显示一个弹出窗口:
这些技术足以涵盖Spring中的错误处理。
更多春天相关的帖子在这里 。
参考: 技术说明博客上来自JCG合作伙伴 Jerome Versrynge的Spring MVC错误处理 。
翻译自: https://www.javacodegeeks.com/2012/11/spring-mvc-error-handling-example.html