🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
~~~ 拦截器和过滤器的区别 1.过滤器是servlet规范中的一部分,任何java web工程都可以使用 2.拦截器是SpringMVC框架自己的,只有使用了SpringMVC框架的工程才能用 3.过滤器在url-pattern中配置了 /* 之后,可以对所有要访问的资源拦截 4.拦截器它只会拦截访问的控制器方法,如果访问的是jsp,html,css,image或者js是不会进行拦截的 二.自定义异常处理 1.编写自定义异常类(做提示信息用的) 2.编写异常处理器(实现 HandlerExceptionResolver 接口) 3.配置异常处理器(跳转到提示页面) 三.自定义拦截器 1.编写拦截器类,实现HandlerInterceptor接口 2.配置拦截器 ~~~ ***** 一.`pom.xml`代码 ~~~ <?xml version="1.0" encoding="UTF-8"?> <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.youge</groupId> <artifactId>springmvc_exception</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <name>springmvc_exception Maven Webapp</name> <!-- FIXME change it to the project's website --> <url>http://www.example.com</url> <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>5.2.9.RELEASE</spring.version> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <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>2.5</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.2</version> <scope>provided</scope> </dependency> </dependencies> <build> <finalName>springmvc_exception</finalName> <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) --> <plugins> <plugin> <artifactId>maven-clean-plugin</artifactId> <version>3.1.0</version> </plugin> <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging --> <plugin> <artifactId>maven-resources-plugin</artifactId> <version>3.0.2</version> </plugin> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.0</version> </plugin> <plugin> <artifactId>maven-surefire-plugin</artifactId> <version>2.22.1</version> </plugin> <plugin> <artifactId>maven-war-plugin</artifactId> <version>3.2.2</version> </plugin> <plugin> <artifactId>maven-install-plugin</artifactId> <version>2.5.2</version> </plugin> <plugin> <artifactId>maven-deploy-plugin</artifactId> <version>2.8.2</version> </plugin> </plugins> </pluginManagement> </build> </project> ~~~ ***** 二.`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> <!-- 配置前端控制器--> <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> <!-- 配置解决中文乱码过滤器--> <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> </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:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!-- 开启注解扫描--> <context:component-scan base-package="com.youge"></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> <!-- 配置文件解析器对象--> <!-- <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">--> <!-- <property name="maxUploadSize" value="10485760"/>--> <!-- </bean>--> <!-- 前端控制器,哪些静态资源不拦截--> <!-- <mvc:resources mapping="/js/**" location="/js/"></mvc:resources>--> <!-- <mvc:resources mapping="/css/**" location="/css/"></mvc:resources>--> <!-- <mvc:resources mapping="/images/**" location="/images/"></mvc:resources>--> <!-- 配置异常处理器--> <bean id="sysExceptionResolver" class="com.youge.exception.SysExceptionResolver"/> <!-- 配置拦截器--> <mvc:interceptors> <!-- 配置第一个拦截器--> <mvc:interceptor> <!-- 要拦截的具体的方法--> <mvc:mapping path="/user/*"/> <!-- 不要拦截的方法--> <!-- <mvc:exclude-mapping path=""/>--> <!-- 配置拦截器对象--> <bean class="com.youge.interceptor.MyInterceptor1"/> </mvc:interceptor> <!-- 配置第二个拦截器--> <mvc:interceptor> <!-- 要拦截的具体的方法--> <mvc:mapping path="/**"/> <!-- 不要拦截的方法--> <!-- <mvc:exclude-mapping path=""/>--> <!-- 配置拦截器对象--> <bean class="com.youge.interceptor.MyInterceptor2"/> </mvc:interceptor> </mvc:interceptors> <!-- 开启SpringMVC框架注解的支持--> <mvc:annotation-driven/> </beans> ~~~ ***** 四.` index.jsp` 代码 ~~~ <%-- Created by IntelliJ IDEA. User: Administrator Date: 2020-09-27 Time: 21:36 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> <h2>springmvc-exception</h2> <a href="/user/testException">异常处理</a><br> <a href="/user/testInterceptor">自定义拦截器</a> </body> </html> ~~~ ***** 五. `UserController.java`代码 ~~~ package com.youge.controller; import com.youge.exception.SysException; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; /** * @author: hcf * @qq: 46914685 * @email: 46914685@qq.com * @date: 2020-09-27 21:50 */ @Controller @RequestMapping("/user") public class UserController { /** * 测试自定义异常类 * @return * @throws SysException */ @RequestMapping("/testException") public String testException() throws SysException { System.out.println("testException执行了..."); try { //模拟异常 int a = 10 / 0; } catch (Exception e) { //打印异常信息 e.printStackTrace(); throw new SysException("查询所有用户出现错误了.."); } return "success"; } /** * 测试自定义拦截器 * @return */ @RequestMapping("/testInterceptor") public String testInterceptor(){ System.out.println("testInterceptor执行了..."); return "success"; } } ~~~ ***** 六. `SysException.java`代码 ~~~ package com.youge.exception; /** * @author: hcf * @qq: 46914685 * @email: 46914685@qq.com * @date: 2020-09-27 22:08 */ /** * 自定义异常类 */ public class SysException extends Exception { //存储提示信息 private String message; @Override public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public SysException(String message) { this.message = message; } } ~~~ ***** 七.`SysExceptionResolver.java`代码 ~~~ package com.youge.exception; import org.springframework.web.servlet.HandlerExceptionResolver; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * @author: hcf * @qq: 46914685 * @email: 46914685@qq.com * @date: 2020-09-27 22:37 */ public class SysExceptionResolver implements HandlerExceptionResolver { /** * 处理异常业务逻辑 * * @param httpServletRequest * @param httpServletResponse * @param obj * @param ex * @return */ @Override public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object obj, Exception ex) { //1.获取异常对象 SysException e = null; if (ex instanceof SysException) { e = (SysException) ex; } else { e = new SysException("系统正在维护..."); } //创建ModelAndView对象 ModelAndView mv = new ModelAndView(); mv.addObject("errorMsg", e.getMessage()); mv.setViewName("error"); return mv; } } ~~~ ***** 八`.MyInterceptor1.java`代码 ~~~ package com.youge.interceptor; /** * @author: hcf * @qq: 46914685 * @email: 46914685@qq.com * @date: 2020-09-27 23:18 */ import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 自定义拦截器 */ public class MyInterceptor1 implements HandlerInterceptor { /** * 预处理,controller方法执行前 * return true 放行,执行下一个拦截器,如果没有下一个拦截器,则执行controller中的方法 * 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("MyInterceptor1...preHandle...执行了..."); return true; //转发 // request.getRequestDispatcher("/WEB-INF/pages/error.jsp").forward(request,response); // return false; } /** * 后处理方法. controller方法执行后,success.jsp执行之前 * @param request * @param response * @param handler * @param modelAndView * @throws Exception */ @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("MyInterceptor1...postHandle...执行了..."); //转发 // request.getRequestDispatcher("/WEB-INF/pages/error.jsp").forward(request,response); } /** * success.jsp页面执行后,该方法会执行,可以用来释放资源 * @param request * @param response * @param handler * @param ex * @throws Exception */ @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("MyInterceptor1...afterCompletion...执行了..."); } } ~~~ ***** 九.`MyInterceptor2.java` 代码 ~~~ package com.youge.interceptor; /** * @author: hcf * @qq: 46914685 * @email: 46914685@qq.com * @date: 2020-09-27 23:18 */ 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 { /** * 预处理,controller方法执行前 * return true 放行,执行下一个拦截器,如果没有下一个拦截器,则执行controller中的方法 * 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("MyInterceptor2...preHandle...执行了..."); return true; //转发 // request.getRequestDispatcher("/WEB-INF/pages/error.jsp").forward(request,response); // return false; } /** * 后处理方法. controller方法执行后,success.jsp执行之前 * @param request * @param response * @param handler * @param modelAndView * @throws Exception */ @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("MyInterceptor2...postHandle...执行了..."); //转发 // request.getRequestDispatcher("/WEB-INF/pages/error.jsp").forward(request,response); } /** * success.jsp页面执行后,该方法会执行,可以用来释放资源 * @param request * @param response * @param handler * @param ex * @throws Exception */ @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("MyInterceptor2...afterCompletion...执行了..."); } } ~~~ ***** 十.`succes.jsp`代码 ~~~ <%-- Created by IntelliJ IDEA. User: Administrator Date: 2020-09-27 Time: 21:42 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>success</title> </head> <body> <h2>成功了.....</h2> <% System.out.println("success.jsp执行了..."); %> </body> </html> ~~~