代码实现
1、先导包
<?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.baidu</groupId>
<artifactId>springMVC-interceptor</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>springMVC-interceptor 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>
<!--servlet-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
</dependency>
<!--jsp-->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.18.RELEASE</version>
</dependency>
</dependencies>
<build>
<finalName>springMVC-interceptor</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>
2、前端页面
主页
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<p>
<a href="${pageContext.request.contextPath}/user/toLogin">登录</a>
<a href="${pageContext.request.contextPath}/user/toSuccess">强制成功</a>
</p>
</body>
</html>
登陆页面 login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>登录</title>
</head>
<body>
<h1>登录</h1>
<hr>
<form action="${pageContext.request.contextPath}/user/login" method="post">
用户名: <input type="text" name="username"><br>
密码: <input type="text" name="pwd"><br>
<input type="submit">
</form>
</body>
</html>
登录成功页面success.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>注销</title>
</head>
<body>
用户登陆成功
名字: ${name}
<a href="${pageContext.request.contextPath}/user/loginOut">注销</a>
</body>
</html>
3、controller
package com.anye.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpSession;
@Controller
@RequestMapping("/user")
public class UserController {
@RequestMapping("/toLogin")
public String toLogin(){
return "login";
}
@RequestMapping("/toSuccess")
public String success(){
return "success";
}
@RequestMapping("login")
public String login(String name, String pwd, HttpSession session){
System.out.println("用户名"+name);
session.setAttribute("name",name);
return "success";
}
@RequestMapping("loginOut")
public String loginOut(HttpSession session){
session.invalidate();
return "login";
}
}
4、编写拦截器
package com.anye.interceptor;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class UserInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
request.setCharacterEncoding("utf-8");
System.out.println("进入UserInterceptor拦截器区域");
//判断是不是登录页面,如果是就放行
//获得请求的路径
System.out.println("url"+request.getRequestURL());
if(request.getRequestURI().contains("login")){
System.out.println("login放行");
return true;
}
//如果用户已登录,放行
HttpSession session = request.getSession();
System.out.println(session.getAttribute("user"));
if(request.getAttribute("user")!=null){
System.out.println("登录放行");
return true;
}
//如果用户没用登陆,想进入成功页面,拦截,让他回到登陆页面
request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request,response);
return false;
}
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
}
}
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
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">
<!--扫描注解-->
<context:component-scan base-package="com.anye.controller"/>
<!--加载驱动-->
<mvc:annotation-driven/>
<!--静态资源过滤器-->
<mvc:default-servlet-handler/>
<!--配置拦截器interceptors,这是复数,可以配置多个拦截器-->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**"/>
<bean class="com.anye.interceptor.UserInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>
<bean id="InternalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
6、配置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">
<servlet>
<servlet-name>springmvc</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>
<load-on-startup>1</load-on-startup>
</servlet>
<!--配置过滤器-->
<filter>
<filter-name>myFilter</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>
<!--/* 包括.jsp-->
<filter-mapping>
<filter-name>myFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
7、启动toncat测试
进入首页
首先强制登录,会被拦截并返回登录界面
输入用户名和密码登录
注销后
拦截器与过滤器
SpringMVC的处理器拦截器类似于Servlet开发中我们使用过的过滤器Filter,用于对处理器进行预处理和过后处理。
过滤器:
- 过滤器是servlet规范中的一部分,任何javaweb工程都可以使用
- 在web.xml的url-pattern中可以配置过滤器,/*可以对所有访问的资源进行拦截
拦截器:
- 拦截器属于SpringMVC框架独有的,只有使用了SpringMVC框架的工程才可以使用
- 拦截器只会拦截访问控制器的方法,如果访问的是静态资源是不会拦截的
拦截器和过滤器的区别:
- 拦截器是基于Java反射机制的,而过滤器是基于函数回调
- 拦截器不依赖于servlet容器,过滤器依赖于servlet容器
- 拦截器只能对action请求起作用,而过滤器几乎可以对所有的请求起作用
- 拦截器可以访问action上下文,而过滤器不能访问
- 在action的生命周期里,拦截器可以多次被调用,而过滤器只能在容器初始化时被调用一次
- 拦截器可以获取IOC容器中的各个bean,而过滤器就不行(这点很重要,在拦截器里注入一个service,可以调用业务逻辑)