下面是一个的Spring Boot登录拦截器的例子。
- 创建一个登录拦截器类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;
}
}
- 创建一个控制器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,表示用户信息。
- 在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");
}
}
- 在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
- 创建登录页面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>
- 测试登录拦截器功能
启动Spring Boot应用,并访问http://localhost:8080/home,会自动重定向到登录页面。在登录页面输入用户名密码(正确的为admin/123456),登录成功后会跳转到主页,显示欢迎信息和“Logout”按钮。点击“Logout”按钮,注销登录后会再次跳转到登录页面。
以上就是一个完整的Spring Boot登录拦截器的例子