亲宝软件园·资讯

展开

SpringBoot登录拦截器

鸣鼓ming 人气:0

1.相关概念

1.实现效果

当没有输入正确的账号密码登录成功时, 除了登录页,其他页面都无法访问(静态资源要放行)

2.实现步骤

2.代码实现

1.配置文件

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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.0</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.limi</groupId>
    <artifactId>springboot-test2</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot-test2</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
            <!-- 下面插件作用是工程打包时,不将spring-boot-configuration-processor打进包内,让其只在编码的时候有用 -->
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.springframework.boot</groupId>
                            <artifactId>spring-boot-configuration-processor</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

application.properties

server.port=8080

2.java代码

SpringbootTest2Application

package com.limi.springboottest2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
@SpringBootApplication
public class SpringbootTest2Application {
    public static void main(String[] args) {
        //1、返回我们IOC容器
        ConfigurableApplicationContext run = SpringApplication.run(SpringbootTest2Application.class, args);
    }
}

LoginInterceptor

package com.limi.springboottest2.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 LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("=========LoginInterceptor preHandle==========");
        HttpSession session = request.getSession();
        if(session.getAttribute("username")==null) //未登录
        {
            //未登录, 重定向到登录页
            response.sendRedirect("/index");  //重定向到登录controller
            return false;//拦截
        }
        return true;
    }
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("==========LoginInterceptor postHandle==========");
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("==========LoginInterceptor afterCompletion==========");
    }
}

WebConfig

package com.limi.springboottest2.config;
import com.limi.springboottest2.interceptor.LoginInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginInterceptor())//拦截器注册到容器中
                .addPathPatterns("/**")  //所有请求都被拦截包括静态资源
                .excludePathPatterns("/index", "/login") //放行的网络请求,
                .excludePathPatterns("/view/index.html","/css/**","/images/**", "/js/**"); //放行的资源请求
    }
}

HelloController

package com.limi.springboottest2.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpSession;
@Controller
public class HelloController {
    @GetMapping("/index")
    public String index(){
        return "/view/index.html";  //没有使用模板引擎, 所以要带上后缀
    }
    @PostMapping("/login")
    public String login(HttpSession session, String username, String password){
        System.out.println("username:"+username+"   password:"+password);
        if("andy".equals(username)&&"123456".equals(password)) { //账号密码匹配成功
            session.setAttribute("username", username);
            return "redirect:/success";
        }
        return "redirect:/index";
    }
    @GetMapping("/success")
    public ModelAndView test1(HttpSession session){
        System.out.println("======执行控制器中方法success======");
        String name = (String)session.getAttribute("username");
        ModelAndView mv = new ModelAndView();
        mv.addObject("name", name);
        mv.setViewName("/view/success.html");
        return mv;
    }
}

3.前端代码

index.css

h1{
    color: blueviolet;
}

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="./css/index.css" rel="external nofollow" >
</head>
<body>
    <h1>请输入账号密码进行登录!</h1>
    <form action="login" method="post">
        账号<input type="text" name="username"><br>
        密码<input type="password" name="password"><br>
        <input type="submit" value="提交"><br>
    </form>
</body>
</html>

success.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <h1>登录成功!</h1>
</head>
<body>
</body>
</html>

3.运行测试

1.直接通过网址访问登录成功页面

被重定向到登录页

2.输入错误账号密码

被重定向到登录页

3.输入正确账号密码

加载全部内容

相关教程
猜你喜欢
用户评论