原文出处:http://howtodoinjava.com/spring/spring-mvc/spring-mvc-simplemappingexceptionresolver-example/
这个例子很简单,主要需求是在进行web开发时,当用户访问时出现异常,直接将异常暴露在前台,一是很不友好,二是异常连的输出会直接暴露后台接口,这是很不安全。所以需要当发生异常时都转到一个默认的jsp页面。在spring mvc中,可以使用simpleMappingExceptionResolver来解决这个问题。
1. 构建MAVEN项目。其项目结构如下:
2. 在Controller中抛出异常,则EmployeeCotroller中的代码如下:
package com.howtodoinjava.demo.controller; import java.util.Date; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.howtodoinjava.demo.exception.AuthException; @Controller @RequestMapping("/employee-module") public class EmployeeController { @RequestMapping(value="/getAllEmployees", method = RequestMethod.GET) public String welcome(Model model) { // throw new AuthException(new Date(), "Something bad happened dude !! Run Away :-("); throw new NullPointerException(); } }
同时,添加自己定义的异常类AuthException,代码如下:
package com.howtodoinjava.demo.exception; import java.util.Date; public class AuthException extends RuntimeException { private static final long serialVersionUID = 1L; private Date date; private String message; public AuthException(Date date, String message) { super(); this.date = date; this.message = message; } public Date getDate() { return date; } public String getMessage() { return message; } @Override public String toString() { return "AuthException [date=" + date + ", message=" + message + "]"; } }
3. 创建jsp文件,当抛出自定义异常时返回view的页面是authException.jsp,当抛出nullPointException时,返回页面是genericView.jsp。
--- authException.jsp页面的代码为:
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <html> <head> <title>Authentication Exception</title> </head> <body> <h2>Exception occured at: </h2><fmt:formatDate value="${exception.date}" pattern="yyyy-MM-dd" /> <h2>Exception Message : </h2>${exception.message} </body> </html>
---genericView.jsp
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> <html> <head> <title>Generic Exception</title> </head> <body> <h2>Some generic error message</h2> </body> </html>
4. 修改配置文件,在spring-serlvet.xml中增加SimpleMappingExceptionResolver的Bean,具体代码如下:
<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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.howtodoinjava.demo" />
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="messages" />
</bean>
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="com.howtodoinjava.demo.exception.AuthException">
error/authExceptionView
</prop>
</props>
</property>
<property name="defaultErrorView" value="error/genericView"/>
</bean>
</beans>
5. web.xml以及pom.xml文件分别为:
---web.xml
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <display-name>Spring Web MVC Hello World Application</display-name> <servlet> <servlet-name>spring</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>spring</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
---pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.howtodoinjava.mvc</groupId> <artifactId>exceptionHandlerDemo</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <dependencies> <dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> <version>1.0.0.GA</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>4.3.1.Final</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <!-- Spring MVC support --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.1.4.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>4.1.4.RELEASE</version> </dependency> <!-- Tag libs support for view layer --> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> <scope>runtime</scope> </dependency> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> <scope>runtime</scope> </dependency> </dependencies> </project>
执行结果:
输入url: localhost:8080/exceptionHandlerDemo/employee-module/getAllEmployees
--当抛出AuthException异常时,访问得到页面如下所示: