1、SpringMVC异常处理
系统中异常包括两类,预期异常和运行异常(RuntimeException),前者通过捕获异常获取异常信息,后者通过规范代码、测试等手段减少该类异常的发生。
系统的dao、service、controller层都可以通过throws Exception方式向上抛出异常,最后又SpringMVC前端控制器交由异常处理器进行异常处理。
SpringMVC提供全局异常处理器(一个系统只有一个异常处理器)进行统一的异常处理。
全局异常处理器处理思路:
(1)解析异常类型;
(2)如果该异常类型是系统自定义的异常,那么直接获取异常信息即可;如果该异常类型不是系统自定义的异常,那么需要构造一个自定义的异常类型。
2、实例
(1)项目结构
(2)HelloController.java
package cn.hwd.springmvc.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import cn.hwd.springmvc.exception.HelloException;
@Controller
@RequestMapping("/hello")
public class HelloController {
@RequestMapping("/index.action")
public String index(Model model, String name) throws Exception {
if(name == null){
throw new HelloException("用户名不能为空");
}
model.addAttribute("message", name);
return "index";
}
}
(3)HelloException.java
package cn.hwd.springmvc.exception;
/**
* 自定义异常类(继承Exception类)
* @author huangwending
*
*/
public class HelloException extends Exception {
private String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public HelloException(String message) {
super();
this.message = message;
}
}
(4)HelloExceptionResolver.java
package cn.hwd.springmvc.exception;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
/**
* 定义全局异常处理器(实现springmvc提供的HandlerExceptionResolver接口)
* @author huangwending
*
*/
public class HelloExceptionResolver implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex) {
HelloException helloException = null;
if(ex instanceof HelloException){
helloException = (HelloException)ex;
}else{
helloException = new HelloException("未知错误");
}
String message = helloException.getMessage();
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("message", message);
modelAndView.setViewName("error");
return modelAndView;
}
}
(5)spring-servlet.xml
<?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:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd">
<context:component-scan base-package="cn.hwd.springmvc.controller" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/page/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- 配置全局异常处理器 -->
<bean class="cn.hwd.springmvc.exception.HelloExceptionResolver"></bean>
</beans>
(6)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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>cn.hwd</groupId>
<artifactId>SpringMVC35</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>SpringMVC35 Maven Webapp</name>
<url>http://maven.apache.org</url>
<build>
<finalName>SpringMVC35</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.0</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.0.2.RELEASE</version>
</dependency>
</dependencies>
</project>
(7)error.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
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>Insert title here</title>
</head>
<body>
${message }
</body>
</html>
(8)index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
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>Insert title here</title>
</head>
<body>
${message }
</body>
</html>
(9)web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>Archetype Created Web Application</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-servlet.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
</web-app>
(10)运行结果