springboot登录拦截器,未登录会自动跳转

下面是一个的Spring Boot登录拦截器的例子。

  1. 创建一个登录拦截器类LoginInterceptor
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        Object user = session.getAttribute("user");
        if (user == null) {
            // 用户未登录,重定向到登录页面
            response.sendRedirect("/login");
            return false;
        }
        return true;
    }
}
  1. 创建一个控制器UserController,处理用户登录和退出登录请求
@Controller
public class UserController {

    @GetMapping("/login")
    public String login() {
        return "login";
    }

    @PostMapping("/login")
    public String doLogin(@RequestParam String username, @RequestParam String password, HttpSession session) {
        // 校验用户名和密码
        if ("admin".equals(username) && "123456".equals(password)) {
            // 登录成功,把用户信息存入Session中
            session.setAttribute("user", new User(username, password));
            return "redirect:/home";
        } else {
            // 登录失败,返回登录页,并显示错误信息
            return "redirect:/login?error";
        }
    }

    @GetMapping("/logout")
    public String logout(HttpSession session) {
        // 注销登录,清除Session中的用户信息
        session.removeAttribute("user");
        return "redirect:/login";
    }
}

其中,User是一个简单的JavaBean,表示用户信息。

  1. 在Spring Boot的配置类WebConfig中注册登录拦截器
@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Autowired
    private LoginInterceptor loginInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(loginInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns("/login", "/logout", "/error");
    }
}

  1. 在application.properties中配置Thymeleaf视图解析器
spring.thymeleaf.check-template-location=true
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.mode=HTML
spring.thymeleaf.cache=false

  1. 创建登录页面login.html和主页home.html
<!-- login.html -->
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Login</title>
</head>
<body>
    <form method="post" action="/login">
        <label>Username</label>
        <input type="text" name="username"><br>
        <label>Password</label>
        <input type="password" name="password"><br>
        <button type="submit">Login</button>
        <span th:if="${param.error}">Username or password is incorrect</span>
    </form>
</body>
</html>
<!-- home.html -->
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Home</title>
</head>
<body>
    <h1>Welcome, <span th:text="${user.username}"></span>!</h1>
    <form method="post" action="/logout">
        <button type="submit">Logout</button>
    </form>
</body>
</html>

  1. 测试登录拦截器功能

启动Spring Boot应用,并访问http://localhost:8080/home,会自动重定向到登录页面。在登录页面输入用户名密码(正确的为admin/123456),登录成功后会跳转到主页,显示欢迎信息和“Logout”按钮。点击“Logout”按钮,注销登录后会再次跳转到登录页面。

以上就是一个完整的Spring Boot登录拦截器的例子

 

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一只java小菜鸡

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值