springboot拦截器登录验证
时间: 2023-11-19 14:57:23 浏览: 47
以下是在Spring Boot中实现拦截器进行登录验证的步骤:
1. 创建一个实现HandlerInterceptor接口的拦截器类,重写preHandle方法,在该方法中进行登录验证。如果验证通过,返回true,否则返回false。
```java
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;
}
}
```
2. 在Spring Boot的配置类中注册拦截器。
```java
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginInterceptor()).addPathPatterns("/**").excludePathPatterns("/login", "/register");
}
}
```
在上面的代码中,我们创建了一个WebMvcConfig类,并实现了WebMvcConfigurer接口。在该类中,我们重写了addInterceptors方法,并在其中注册了我们创建的LoginInterceptor拦截器。我们使用addPathPatterns方法指定需要拦截的请求路径,使用excludePathPatterns方法指定不需要拦截的请求路径。
3. 在登录页面中添加登录表单,并在登录表单中提交用户名和密码。
```html
<form action="/login" method="post">
<input type="text" name="username" placeholder="Username">
<input type="password" name="password" placeholder="Password">
<button type="submit">Login</button>
</form>
```
4. 在登录请求的Controller中进行登录验证,并将用户信息存储到Session中。
```java
@PostMapping("/login")
public String login(@RequestParam String username, @RequestParam String password, HttpSession session) {
if ("admin".equals(username) && "123456".equals(password)) {
session.setAttribute("user", username);
return "redirect:/home";
} else {
return "redirect:/login";
}
}
```
在上面的代码中,我们创建了一个/login的POST请求处理方法,并在该方法中进行登录验证。如果用户名和密码正确,我们将用户信息存储到Session中,并重定向到/home页面。否则,我们重定向到登录页面。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)