Article Directory
For management systems or other systems that require user login, login verification is an indispensable link. In the project developed by SpringBoot, user login interception and verification are achieved by implementing interceptors.
1. The principle of SpringBoot's implementation of login interception
SpringBoot HandlerInterceptor
implements the interceptor by implementing the WebMvcConfigurer
interface, implements a configuration class by implementing the interface, injects the interceptor into the configuration class, and finally injects the configuration through the @Configuration annotation.
1.1, implement the HandlerInterceptor
interface
Implement HandlerInterceptor
the interface need to implement three preHandle
methods: postHandle
, , afterCompletion
.
The functions of each of the three methods are as follows:
package blog.interceptor;
import blog.entity.User;
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 UserLoginInterceptor implements HandlerInterceptor {
/***
* 在请求处理之前进行调用(Controller方法调用之前)
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("执行了拦截器的preHandle方法");
try {
HttpSession session = request.getSession();
//统一拦截(查询当前session是否存在user)(这里user会在每次登录成功后,写入session)
User user = (User) session.getAttribute("user");
if (user != null) {
return true;
}
response.sendRedirect(request.getContextPath() + "login");
} catch (Exception e) {
e.printStackTrace();
}
return false;
//如果设置为false时,被请求时,拦截器执行到此处将不会继续操作
//如果设置为true时,请求将会继续执行后面的操作
}
/***
* 请求处理之后进行调用,但是在视图被渲染之前(Controller方法调用之后)
*/
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("执行了拦截器的postHandle方法");
}
/***
* 整个请求结束之后被调用,也就是在DispatchServlet渲染了对应的视图之后执行(主要用于进行资源清理工作)
*/
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("执行了拦截器的afterCompletion方法");
}
}
preHandle
It is executed before the Controller, so the function of the interceptor is mainly implemented in this part:
- Check whether there is an
user
object in the session ; - If it exists, return
true
, and then the Controller will continue the subsequent operation; - If it does not exist, it will be redirected to the login interface. It
is through this interceptor that the Controller will be executed before it is executedpreHandle
.
1.2. Implement the WebMvcConfigurer
interface and register the interceptor
Implement the WebMvcConfigurer
interface to implement a configuration class, and register an object of the interceptor implemented above to this configuration class.
package blog.config;
import blog.interceptor.UserLoginInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class LoginConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
//注册TestInterceptor拦截器
InterceptorRegistration registration = registry.addInterceptor(new UserLoginInterceptor());
registration.addPathPatterns("/**"); //所有路径都被拦截
registration.excludePathPatterns( //添加不拦截路径
"/login", //登录路径
"/**/*.html", //html静态资源
"/**/*.js", //js静态资源
"/**/*.css" //css静态资源
);
}
}
Register the interceptor in the interceptor list, and specify which access paths are blocked, which access paths are not blocked, and which resource files are not blocked; finally, the configuration is injected with the @Configuration annotation.
1.3, keep logged in
You only need to log in once. If you have logged in, you do not need to log in again when you visit again next time, you can directly access the content of the website.
After the correct login, it will be user
saved session
in. When the page is accessed again, the login interceptor can find this user
object, and there is no need to intercept the login interface again.
@RequestMapping(value = {
"", "/", "/index"}, method = RequestMethod.GET)
public String index(Model model, HttpServletRequest request) {
User user = (User) request.getSession().getAttribute("user");
model.addAttribute("user", user);
return "users/index";
}
@RequestMapping(value = {
"/login"}, method = RequestMethod.GET)
public String loginIndex() {
return "users/login";
}
@RequestMapping(value = {
"/login"}, method = RequestMethod.POST)
public String login(@RequestParam(name = "username")String username, @RequestParam(name = "password")String password,
Model model, HttpServletRequest request) {
User user = userService.getPwdByUsername(username);
String pwd = user.getPassword();
String password1 = MD5Utils.md5Code(password).toUpperCase();
String password2 = MD5Utils.md5Code(password1).toUpperCase();
if (pwd.equals(password2)) {
model.addAttribute("user", user);
request.getSession().setAttribute("user", user);
return "redirect:/index";
} else {
return "users/failed";
}
}
2. Code implementation and examples
The code implementation is shown above.
After the login is successful, save the user
information session
in, the next time you log in, the browser SESSIONID
can find the corresponding according to your own session
, so don't log in again, you can see it in the Chrome browser.
3. Effectiveness verification
3.1. Visit the localhost:8081/index page:
Was redirected to localhost:8081/login, which realized login interception.
3.2. Enter the user name and password correctly to log in
3.3, visit localhost:8081/index again
It is not intercepted by the login interceptor again, which proves that the login can be maintained.