springMVC处理器拦截允许运行目标方法之间进行一些拦截工作,或者目标方法之后进行一些其他处理。
代码部分
1、InterController.java
package com.qingruan.servlet; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.http.HttpServletRequest; @Controller @RequestMapping("/inter") public class InterController { @RequestMapping("/test") public String test(HttpServletRequest request){ System.out.println("inter...test()"); request.setAttribute("key","value"); return "success"; } }
2、MyFirstInter.java
package com.qingruan.servlet; import org.springframework.stereotype.Component; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @Component public class MyFirstInter implements HandlerInterceptor { //目标方法运行之前执行 @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("preHandle"); //表示继续执行后续的操作 return true; } //目标方法运行之后运行 @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("postHandle"); } //在整个请求完成之后的操作 @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("afterCompletion"); } }
3、spring-mvc.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.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"> <!--配置spring,创建容器时,扫扫描的包--> <context:component-scan base-package="com.qingruan"></context:component-scan> <!--配置内部视图解析器--> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!--前缀和后缀都是与业务逻辑方法值进行组合,组合成jsp文件所在的路径,/hello.jsp--> <property name="prefix" value="/views/"></property> <property name="suffix" value=".jsp"></property> </bean> <!--配置响应结果的转换器--> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"> <property name="messageConverters"> <!--将响应结果转换成json格式数据--> <list> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"></bean> </list> </property> </bean> <!--文件解析器--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!--所有文件大小上限 100M--> <property name="maxUploadSize" value="104857600"/> <!--单个文件大小上限 1M--> <property name="maxUploadSizePerFile" value="1038576"/> <!--编码类型--> <property name="defaultEncoding" value="UTF-8"/> </bean> <!--开启sringmvc框架注解的支持--> <mvc:annotation-driven></mvc:annotation-driven> <!--出现静态资源访问不到的情况,是因为前端控制器会拦截所有的请求,进行处理器的匹配 方式一:开启默认servlet,所有请求都会经过默认servlet请求,如果是静态资源则直接进行响应 <mvc:default-servlet-handler/> --> <!--方式二:设置指定的静态资源访问映射--> <!--<mvc:resources mapping="/img/**" location="/img/"></mvc:resources> <mvc:resources mapping="/js/**" location="/js/"></mvc:resources> <mvc:resources mapping="/html/**" location="/html/"></mvc:resources> <mvc:resources mapping="/css/**" location="/css/"></mvc:resources> --> <!--配置拦截器,拦截那些请求的目标方法--> <mvc:interceptors> <!--表示配置单个拦截器--> <mvc:interceptor> <!--配置拦截器拦截的路径--> <mvc:mapping path="/inter/test"/> <ref bean="myFirstInter"></ref> </mvc:interceptor> </mvc:interceptors> </beans>
4、success.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ page isELIgnored="false" %> <html> <head> <title>SUCCESS</title> <% pageContext.setAttribute("page",request.getContextPath());%> <!--绝对url指向指定栈点--> <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script> </head> <body> ${key} </body> </html>
5、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> <!--配置核心控制器 前端控制器springmvc的集中访问点,负责指定分派 --> <servlet> <servlet-name>dispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!--设置初始化参数,让程序启动后帮我们加载spring主配置文件--> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mvc.xml</param-value> </init-param> </servlet> <!--设置servlet拦截的请求路径--> <servlet-mapping> <servlet-name>dispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
6、index.jsp
<%-- Created by IntelliJ IDEA. User: 45579 Date: 2022/11/15 Time: 20:04 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ page isELIgnored="false" %> <html> <head> <title>Title</title> <% pageContext.setAttribute("page",request.getContextPath());%> <!--绝对url指向指定栈点--> <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script> <script> $(function (){ $("#btn").click(function () { var user={age:21,name:"zhangsan",phone:"111222333"}; $.ajax({ type:"POST", data:JSON.stringify(user), url:"${page}/getUser", contentType:"application/json;charset=utf-8", success:function (data) { console.log(data.age); } }) }) }) </script> </head> <body> <input type="button" id="btn" value="submitUser"/> <%--<img src="${page}/img/1.jpg">--%> </body> </html>
7、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.qingruan</groupId> <artifactId>springmvc_day01</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <name>springmvc_day01 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.7</maven.compiler.source> <maven.compiler.target>1.7</maven.compiler.target> </properties> <dependencies> <!--导入spring的依赖(坐标)--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.1.6.RELEASE</version> </dependency> <!--SpringMVC--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.1.6.RELEASE</version> </dependency> <!--springweb--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>5.1.6.RELEASE</version> </dependency> <!--servlet--> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <!--jsp--> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api</artifactId> <version>2.3.3</version> <scope>provided</scope> </dependency> <!--内置json格式--> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.9.8</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.9.8</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.8</version> </dependency> <!--文件上传--> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.4</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.6</version> </dependency> </dependencies> <build> <finalName>springmvc_day01</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>
运行效果
前端地址栏访问test方法,拦截器生效,触发拦截页面success.jsp,页面显示value;
控制台