异常处理
pom.xml
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<spring.version>4.3.13.RELEASE</spring.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>3.0</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
</dependency>
</dependencies>
web.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<!--配置字符编码过滤器-->
<filter>
<filter-name>characterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--配置前端控制器对象-->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
springmvc.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--配置Spring创建容器时要扫描的包-->
<context:component-scan base-package="com.how2java"></context:component-scan>
<!--配置视图解析器对象-->
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!--配置前端控制器,过滤静态资源-->
<mvc:resources mapping="/css/**" location="/css/"></mvc:resources><!--样式-->
<mvc:resources mapping="/images/**" location="/images/"></mvc:resources><!--图片-->
<mvc:resources mapping="/js/**" location="/js/"></mvc:resources><!--JavaScript-->
<!--配置异常处理器-->
<bean id="sysExceptionResolver" class="com.how2java.exception.SysExceptionResolver"></bean>
<!--开启SpringMVC注解的支持-->
<mvc:annotation-driven></mvc:annotation-driven>
</beans>
index.jsp
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2019/12/27
Time: 17:19
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h3>异常处理</h3>
<a href="exception/testException">testException</a>
</body>
</html>
success.jsp
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2019/12/27
Time: 17:23
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h3>success</h3>
</body>
</html>
error.jsp
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2019/12/27
Time: 18:01
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>Title</title>
</head>
<body>
${errorMsg}
</body>
</html>
ExceptionController.java
package com.how2java.controller;
import com.how2java.exception.SysException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/exception")
public class ExceptionController {
@RequestMapping("/testException")
public String testException() throws SysException{
System.out.println("testException方法测试。。。");
try {
//模拟异常
int i = 1/0;
} catch (Exception e) {
//打印异常信息
e.printStackTrace();
//抛出自定义异常信息
throw new SysException("意不意外,开不开心,奔溃了吧!");
}
return "success";
}
}
SysException.java
package com.how2java.exception;
/**
* 自定义异常类
*/
public class SysException extends Exception{
//储存异常信息
private String msg;
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public SysException(String msg) {
this.msg = msg;
}
}
SysExceptionResolver.java
package com.how2java.exception;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 异常处理器
*/
public class SysExceptionResolver implements HandlerExceptionResolver{
/**
* 处理异常信息
* @param request
* @param response
* @param handler
* @param e
* @return
*/
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception e) {
//获取异常对象
SysException se = null;
if(e instanceof SysException){
se = (SysException)e;
} else {
se = new SysException("系统正在维护。。。");
}
//创建ModelAndView对象
ModelAndView mav = new ModelAndView();
mav.addObject("errorMsg", se.getMsg());
mav.setViewName("error");
return mav;
}
}
拦截器
pom.xml
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<spring.version>4.3.13.RELEASE</spring.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>3.0</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
</dependency>
</dependencies>
web.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<!--配置字符编码过滤器-->
<filter>
<filter-name>characterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--配置前端控制器对象-->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
springmvc.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--配置Spring创建容器时要扫描的包-->
<context:component-scan base-package="com.how2java"></context:component-scan>
<!--配置视图解析器对象-->
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!--配置前端控制器,过滤静态资源-->
<mvc:resources mapping="/css/**" location="/css/"></mvc:resources><!--样式-->
<mvc:resources mapping="/images/**" location="/images/"></mvc:resources><!--图片-->
<mvc:resources mapping="/js/**" location="/js/"></mvc:resources><!--JavaScript-->
<!--配置拦截器-->
<mvc:interceptors>
<!--配置1号拦截器-->
<mvc:interceptor>
<!--拦截的方法-->
<mvc:mapping path="/interceptor/*"/>
<!--不要拦截的方法-->
<!--<mvc:exclude-mapping path=""/>-->
<!--配置拦截器对象-->
<bean id="myInterceptor1" class="com.how2java.interceptor.MyInterceptor1"></bean>
</mvc:interceptor>
<!--配置2号拦截器-->
<mvc:interceptor>
<!--拦截的方法-->
<mvc:mapping path="/interceptor/*"/>
<!--不要拦截的方法-->
<!--<mvc:exclude-mapping path=""/>-->
<!--配置拦截器对象-->
<bean id="myInterceptor2" class="com.how2java.interceptor.MyInterceptor2"></bean>
</mvc:interceptor>
</mvc:interceptors>
<!--开启SpringMVC注解的支持-->
<mvc:annotation-driven></mvc:annotation-driven>
</beans>
index.jsp
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2019/12/27
Time: 20:59
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h3>拦截器</h3>
<a href="interceptor/testInterceptor">testInterceptor</a>
</body>
</html>
success.jsp
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2019/12/27
Time: 21:00
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h3>success</h3>
<% System.out.println("success.jsp"); %>
</body>
</html>
error.jsp
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2019/12/27
Time: 21:10
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h3>出错了</h3>
</body>
</html>
InterceptorController.java
package com.how2java.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/interceptor")
public class InterceptorController {
@RequestMapping("/testInterceptor")
public String testInterceptor(){
System.out.println("testInterceptor方法测试。。。");
return "success";
}
}
MyInterceptor1.java
package com.how2java.interceptor;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 拦截器:SpringMVC处理器拦截器类似于Servlet开发中的过滤器,用于对处理器进行预处理和后处理。
* 拦截器链:将拦截器按照一定顺序联结成一条链,在访问被拦截的方法或字段时,拦截器链中的拦截器会按其之前被定义的顺序被调用。
* 拦截器和过滤器的区别:
* 过滤器:
* ①servlet规范中的一部分,任何java web工程都可以使用。
* ②在url-pattern中配置/*之后,可以对所有要访问的资源进行拦截。
* 拦截器:
* ①SpringMVC框架自己的,只有使用了SpringMVC框架之后才能使用。
* ②只会拦截访问的控制类方法,如果是访问jsp、html、image或者js,不会进行拦截。
* 自定义拦截器必须实现HandlerInterceptor接口。
*/
public class MyInterceptor1 implements HandlerInterceptor{
/**
* 预处理方法,控制类方法执行之前,执行。
* return true:表示放行,执行下一个拦截器。如果没有,执行控制器方法。
* return false:表示不放行,直接跳转页面。
* @param request
* @param response
* @param handler
* @return
* @throws Exception
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("1号拦截器预处理方法测试。。。");
// request.getRequestDispatcher("/WEB-INF/pages/error.jsp").forward(request, response);
return true;
}
/**
* 后处理方法,控制类方法执行之后,跳转页面(success.jsp)执行之前,执行。
* @param request
* @param response
* @param handler
* @param mav
* @throws Exception
*/
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView mav) throws Exception {
System.out.println("1号拦截器后处理方法测试。。。");
// request.getRequestDispatcher("/WEB-INF/pages/error.jsp").forward(request, response);
}
/**
* 最终方法,跳转页面执行后,执行。
* @param request
* @param response
* @param handler
* @param e
* @throws Exception
*/
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception e) throws Exception {
System.out.println("1号拦截器最终方法测试。。。");
}
}
MyInterceptor2.java
package com.how2java.interceptor;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 自定义拦截器
*/
public class MyInterceptor2 implements HandlerInterceptor{
/**
* 预处理方法,控制类方法执行之前,执行。
* return true:表示放行,执行下一个拦截器。如果没有,执行控制器方法。
* return false:表示不放行,直接跳转页面。
* @param request
* @param response
* @param handler
* @return
* @throws Exception
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("2号拦截器预处理方法测试。。。");
// request.getRequestDispatcher("/WEB-INF/pages/error.jsp").forward(request, response);
return true;
}
/**
* 后处理方法,控制类方法执行之后,跳转页面(success.jsp)执行之前,执行。
* @param request
* @param response
* @param handler
* @param mav
* @throws Exception
*/
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView mav) throws Exception {
System.out.println("2号拦截器后处理方法测试。。。");
// request.getRequestDispatcher("/WEB-INF/pages/error.jsp").forward(request, response);
}
/**
* 最终方法,跳转页面执行后,执行。
* @param request
* @param response
* @param handler
* @param e
* @throws Exception
*/
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception e) throws Exception {
System.out.println("2号拦截器最终方法测试。。。");
}
}