springBoot+thymleaf 实现简单 登陆认证+登陆拦截器功能

引入依赖

<?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.5.3</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</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-data-redis</artifactId>
        </dependency>
        <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-starter-thymeleaf</artifactId>
        </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>
        </plugins>
    </build>

</project>

controller层

@Controller
public class WebController {

    // 实现localhost:8080 跳转到login.html
    @GetMapping({"/","/login"})
    public String login() {
        return "login";
    }

    // login.html form表单跳转过来
    @PostMapping("/login")
    public String loginUser(User user, Model model, HttpSession session) {
        if (user.getPassword().equals("123456")) {
            session.setAttribute("loginUser", user);
            // 重定向到/main.html,可以在main.html 页面刷新,不会访问到/login
            return "redirect:/main.html";
        }
        model.addAttribute("msg", "密码错误");
        return "login";
    }

    @GetMapping("/main.html")
    public String toMain() {
        return "main";
    }
}

实体类

@Data
public class User {
//    @NotNull(message = "用户名不能为空!")
    private String userName;
//    @Size(min=6, max = 10, message = "密码长度必须6到10位")
    private String password;
}

登陆拦截器

/**
 * 登陆拦截器
 * 简单实现未登录返回登录页面
 */
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        Object loginUser = session.getAttribute("loginUser");
        if (loginUser == null) {
            request.setAttribute("msg", "请登陆");
            request.getRequestDispatcher("/").forward(request, response);
            return false;
        }
        return true;
    }
}

注册登陆拦截器

@Configuration
public class WebConfig implements WebMvcConfigurer {

    //注册拦截器
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginInterceptor()).addPathPatterns("/**")
                .excludePathPatterns("login.html", "/", "/login");
    }
}

简单前端登陆页面login.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form th:action="@{login}" method="post">
        <div>
            <span style="color: red" th:text="${msg}"></span>
        </div>
        <div>
            <input id="user_name" name="userName" type="text" placeholder="用户名" />
        </div>
        <div>
            <input id="password" name="password" type="password" placeholder="密码" />
        </div>
        <button type="submit">登 陆</button>
    </form>
</body>
</html>

main.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>main页面</h1>
    <h1 th:text="${session.loginUser.userName}"></h1>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值