(0基础保姆教程)-JavaEE开课啦!--13课程(Interception拦截器)-完结

一、Interception(拦截器)是什么?

拦截器(Interceptor)是一种用于在请求到达目标方法之前或之后执行特定逻辑的机制。它是基于Java反射机制,属于面向切面编程(AOP)的一种应用。拦截器可以用于多种应用场景,例如验证用户登录状态、权限验证、记录系统日志、通用处理等。

二、任务要求

1.在登录界面对用户名和密码进行验证

2.未登录状态下,直接访问main页面,拦截回login页面

3.在登录状态下,直接跳转到main页面,在页面显示用户名

三、实现代码

目录结构

1.创建Spring项目

2.在pom文件中引入相关依赖

java 复制代码
<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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.ljl</groupId>
  <artifactId>SpringMVC_class_interceptor</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>SpringMVC_class_interceptor Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>

    <!--    Spring 基础配置-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.3.10</version>
    </dependency>
    <!--    SpringMVC工具插件-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.3.10</version>
    </dependency>
    <!--    servlet插件-->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.1</version>
    </dependency>

    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.32</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.11</version>
    </dependency>
    <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter</artifactId>
      <version>RELEASE</version>
      <scope>compile</scope>
    </dependency>

    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.15.4</version>
    </dependency>

    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.15.4</version>
    </dependency>

    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.4</version>
    </dependency>
  </dependencies>
  <build>
    <finalName>SpringMVC_class_interceptor</finalName>
  </build>
</project>

3.在Web.xml文件中配置相关依赖

java 复制代码
<?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_3_1.xsd"
         version="3.1">


  <!--允许访问jpg。 并且必须加在springmvc的servlet之前-->
  <servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>*.jpg</url-pattern>
  </servlet-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:spring-mvc.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>chinese_encoder</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>chinese_encoder</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>

4.创建spring-mvc.xml文件,对springmvc进行配置

java 复制代码
<?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">
    <mvc:annotation-driven/>
    <context:component-scan base-package="com.ljl.controller"/>
    <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping" />
    <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter" />
<!--    配置视图解释器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="UTF-8"/>
        <property name="maxUploadSize" value="2097152"/>
    </bean>
    <mvc:default-servlet-handler/>

    <!--  配置拦截器-->
    <mvc:interceptors>
        <bean class="com.ljl.interceptor.LoginInterceptor"/>
    </mvc:interceptors>


</beans>

5.创建pages/login.jsp 和 pages/main.jsp前端界面

login.jsp

html 复制代码
<%--
  Created by IntelliJ IDEA.
  User: ljl
  Date: 2024/12/9
  Time: 下午4:24
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>login</title>
</head>
<body>
<form action="login" method="post">
    <div>${msg}</div>
    用户名:<input type="text" name="username"><br>
    密 码:<input type="password" name="password"><br>
    <input type="submit" value="登录">
</form>
</body>
</html>

main.jsp

html 复制代码
<%--
  Created by IntelliJ IDEA.
  User: ljl
  Date: 2024/12/9
  Time: 下午4:23
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>main</title>
</head>
<body>
<ul>
    <li>您好:${USER_SESSION.username}</li>
    <li><a href="${pageContext.request.contextPath}/logout">退出</a> </li>
</ul>
</body>
</html>

6.创建Entity/UserEntity实体类

java 复制代码
package com.ljl.Entity;

public class User {

    private String username;
    private String password;

    public User() {
    }

    public User(String username, String password) {
        this.username = username;
        this.password = password;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString() {
        return "User{" +
                "username='" + username + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}

7.创建Controller/UserController控制器

java 复制代码
package com.ljl.controller;


import com.ljl.Entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;

@Controller
public class UserController {

    @RequestMapping("/main")
    public String toMainPage(){
        return "main";
    }

//    检查是否存在cookies,存在的话直接跳转主页
    @RequestMapping("/tologin")
    public String toLoginPage(HttpSession session){
        if (session.getAttribute("USER_SESSION") != null){
            return "main";
        }
        return "login";
    }

    @RequestMapping("/login")
    public String login(User user, Model model, HttpSession session){
        String username = user.getUsername();
        String password = user.getPassword();
        if (username != null && username.equals("pjl") && password != null && password.equals("123")){
           session.setAttribute("USER_SESSION", user);
           return "main";
        }
        model.addAttribute("msg", "用户名或密码错误!");
        return "login";
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session){
        session.invalidate();
        return "redirect:tologin";
    }
}

8.创建interceptor/LoginInterceptor拦截控制器*******

java 复制代码
package com.ljl.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginInterceptor implements HandlerInterceptor {

    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        String uri = httpServletRequest.getRequestURI();
        if (uri.indexOf("/login") >= 0){
            return true;
        }
        HttpSession hs = httpServletRequest.getSession();
        if (hs.getAttribute("USER_SESSION") != null){
            return true;
        }
        httpServletRequest.setAttribute("msg", "没有登录!");
        httpServletRequest.getRequestDispatcher("/WEB-INF/pages/login.jsp").forward(httpServletRequest, httpServletResponse);
        return false;
    }
}

四、运行测试

1.部署项目,对tomcat进行配置

2.进行账户验证

(http://localhost:8090/SpringMVC_class_interceptor_war_exploded/tologin)

错误账号:ljl 错误密码:123

正确账户:pjl 正确密码:123

3.成功登录后,退出登录,直接访问main页面,拦截回login页面

4.成功登录后,重新访问login页面,系统判断到已登录状态,直接跳转到main页面,显示用户名

五、本Java EE基础完结

相关推荐
杉之3 分钟前
SpringBlade 数据库字段的自动填充
java·笔记·学习·spring·tomcat
圈圈编码24 分钟前
Spring Task 定时任务
java·前端·spring
俏布斯36 分钟前
算法日常记录
java·算法·leetcode
276695829241 分钟前
美团民宿 mtgsig 小程序 mtgsig1.2 分析
java·python·小程序·美团·mtgsig·mtgsig1.2·美团民宿
爱的叹息42 分钟前
Java 连接 Redis 的驱动(Jedis、Lettuce、Redisson、Spring Data Redis)分类及对比
java·redis·spring
程序猿chen1 小时前
《JVM考古现场(十五):熵火燎原——从量子递归到热寂晶壁的代码涅槃》
java·jvm·git·后端·java-ee·区块链·量子计算
松韬1 小时前
Spring + Redisson:从 0 到 1 搭建高可用分布式缓存系统
java·redis·分布式·spring·缓存
绝顶少年2 小时前
Spring Boot 注解:深度解析与应用场景
java·spring boot·后端
心灵宝贝2 小时前
Tomcat 部署 Jenkins.war 详细教程(含常见问题解决)
java·tomcat·jenkins
天上掉下来个程小白2 小时前
Redis-14.在Java中操作Redis-Spring Data Redis使用方式-操作列表类型的数据
java·redis·spring·springboot·苍穹外卖