2024.3.25 Monday
目录
- 9.拦截器
9.拦截器
9.1.概述
- SpringMVC的处理器拦截器类似于Servlet开发中的过滤器Filter,用于对处理器进行预处理和后处理。开发者可以自己定义一些拦截器来实现特定的功能。
- 过滤器与拦截器的区别:拦截器是AOP思想的具体应用。
- 过滤器
- servlet规范中的一部分,任何java web工程都可以使用
- 在url-pattern中配置了/*之后,可以对所有要访问的资源进行拦截
- 拦截器
- 拦截器是SpringMVC框架自己的,只有使用了SpringMVC框架的工程才能使用
- 拦截器只会拦截访问的控制器Controller方法,如果访问的是jsp/html/css/image/js是不会进行拦截的
9.2.自定义拦截器
9.2.1.如何实现拦截器
自定义一个类然后继承HandlerInterceptor接口
9.2.2.新建module
9.2.2.1.新建springmvc-07-interceptor模块
9.2.2.2.添加web支持
和springmvc-06-ajax中的web.xml位置、内容都相同
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.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:applicationContext.xml</param-value>
</init-param>
<!--启动加载-->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<filter>
<filter-name>encoding</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>encoding</filter-name>
<url-pattern>/*</url-pattern> <!--过滤所有请求-->
</filter-mapping>
</web-app>
9.2.2.3.添加applicationContext.mxl,新建controller文件夹
和springmvc-06-ajax中的web.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
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 自动扫描指定的包,下面所有注解类交给IOC容器管理 -->
<context:component-scan base-package="P27.controller"/>
<!--静态资源过滤-->
<mvc:default-servlet-handler />
<mvc:annotation-driven/>
<!-- 视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
id="internalResourceViewResolver">
<!-- 前缀 -->
<property name="prefix" value="/WEB-INF/jsp/" />
<!-- 后缀 -->
<property name="suffix" value=".jsp" />
</bean>
</beans>
9.2.2.4.添加jar包
9.2.2.5.配置tomcat
9.2.3.新建TestController.java
package P27.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestController {
@GetMapping("/t1")
public String test(){
System.out.println("TestController/test() is running");
return "done";
}
}
验证spring配置成功
http://localhost:8080/springmvc_07_interceptor_war_exploded/t1
server栏输出
9.2.4.新建MyInterceptor.java和MyFilter.java
9.2.4.1.MyFilter必须要引入三个方法
9.2.4.2.MyInterceptor则不需要,在此处进行重写体验
Ctrl+O(快捷键)插入三个方法
package P27.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 MyInterceptor implements HandlerInterceptor {
//在请求处理的方法之前执行
//如果 return true 则执行下一个拦截器
//如果 return false 就不执行下一个拦截器
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
System.out.println("------------preHandle处理前------------");
return true;
}
//在请求处理方法执行之后执行
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
System.out.println("------------postHandle处理后------------");
}
//在dispatcherServlet处理后执行,做清理工作.
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
System.out.println("------------afterCompletion清理------------");
}
}
9.2.5.修改applicationContext.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
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 自动扫描指定的包,下面所有注解类交给IOC容器管理 -->
<context:component-scan base-package="P27.controller"/>
<!--静态资源过滤-->
<mvc:default-servlet-handler />
<mvc:annotation-driven/>
<!-- 视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
id="internalResourceViewResolver">
<!-- 前缀 -->
<property name="prefix" value="/WEB-INF/jsp/" />
<!-- 后缀 -->
<property name="suffix" value=".jsp" />
</bean>
<!-- 拦截器配置 -->
<mvc:interceptors>
<mvc:interceptor>
<!--"/**"包括这个请求下的所有请求,都会被拦截-->
<!--以下两行为举例:"/admin/* "拦截的是/admin/add等等这种 , /admin/add/user不会被拦截-->
<!--"/admin/**" 拦截的是/admin/下的所有-->
<mvc:mapping path="/**"/>
<!--定义被过滤的类-->
<bean class="P27.interceptor.MyInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>
</beans>
9.2.6.修改index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Test1$</title>
</head>
<body>
<a href="${pageContext.request.contextPath}/t1">Interceptor Test</a>
</body>
</html>
9.2.7.运行
http://localhost:8080/springmvc_07_interceptor_war_exploded/
http://localhost:8080/springmvc_07_interceptor_war_exploded/t1
server栏输出:
9.2.7.1.修改MyInterceptor
将第一个方法preHandle的返回值改为false,拦截请求,则:
server栏输出:
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
System.out.println("------------preHandle处理前------------");
// return true;
return false;
}
9.3.验证用户是否登录(认证用户)
9.3.1.实现思路
- 有一个登陆页面,需要写一个controller访问页面。
- 登陆页面有一提交表单的动作。需要在controller中处理。判断用户名密码是否正确。如果正确,向session中写入用户信息。返回登陆成功。
- 拦截用户请求,判断用户是否登陆。如果用户已经登陆。放行, 如果用户未登陆,跳转到登陆页面。
9.3.2.新建登录页面login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<%--在WEB-INF下的所有页面或资源只能通过controller或者servlet进行访问--%>
<h1>登录页面</h1>
<form action="${pageContext.request.contextPath}/user/login" method="post">
用户名: <input type="text" name="username">
密码: <input type="password" name="pwd">
<input type="submit" value="SUBMIT">
</form>
</body>
</html>
9.3.3.新建LoginController.java处理请求
package P27.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpSession;
@Controller
@RequestMapping("/user")
public class LoginController {
//跳转到登陆页面
@RequestMapping("/jumplogin")
public String jumpLogin() throws Exception {
return "login";
}
//跳转到成功页面
@RequestMapping("/jumpSuccess")
public String jumpSuccess() throws Exception {
return "success";
}
//登陆提交
@RequestMapping("/login")
public String login(HttpSession session, String username, String pwd) throws Exception {
// 向session记录用户身份信息
System.out.println("接收前端==="+username);
session.setAttribute("user", username);
return "success";
}
//退出登陆
@RequestMapping("logout")
public String logout(HttpSession session) throws Exception {
// session 过期
session.invalidate();
return "login";
}
}
9.3.4.新建LoginInterceptor.java
package P27.interceptor;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
public class LoginInterceptor implements HandlerInterceptor {
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("uri: " + request.getRequestURI());
//判断登录的情况:判断Session是否为null,不为null就return true
//放行
//1.在登录页面时
if (request.getRequestURI().contains("login")){
return true;
}
HttpSession session = request.getSession();
//2.已登录时
if (session.getAttribute("user")!=null){
return true;
}
//不放行
request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request,response);
return false;
}
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
}
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
}
}
9.3.5.新建success.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>登录成功页面</h1>
<hr>
<h1><a href="${pageContext.request.contextPath}/index.jsp">TO HOME PAGE</a></h1>
<h1><a href="${pageContext.request.contextPath}/user/logout">EXIT</a></h1>
</body>
</html>
9.3.6.修改index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>verify information</title>
</head>
<body>
<h1>HOME PAGE</h1>
<hr>
<h1><a href="${pageContext.request.contextPath}/user/jumplogin">Login Page</a> </h1>
<h1><a href="${pageContext.request.contextPath}/user/jumpSuccess">User Page</a> </h1>
</body>
</html>
9.3.7.在Springmvc的配置文件中注册拦截器
(和9.2.5.修改applicationContext.xml处几乎相同,仅路径不同)
添加以下代码进图中相应位置
<!--AJAX验证用户是否登录-->
<mvc:interceptor>
<mvc:mapping path="/**"/>
<bean id="loginInterceptor" class="P27.interceptor.LoginInterceptor"/>
</mvc:interceptor>
9.3.8.运行
http://localhost:8080/springmvc_07_interceptor_war_exploded/
无论点击哪个选项都将跳转到如下页面,要求用户登录
http://localhost:8080/springmvc_07_interceptor_war_exploded/user/jumplogin
输入用户信息,点击SUBMIT
点击TO HOME PAGE回到主页面,此时点选User Page时不需要重新输入用户信息
http://localhost:8080/springmvc_07_interceptor_war_exploded/user/jumpSuccess
点击EXIT退出登录,将自动转入输入信息页面
至此,功能展示部分结束,退出后的其他操作和未登录时完全相同。