乐趣区

关于springboot:SpringBoot实现登录拦截器实战版

对于管理系统或其余须要用户登录的零碎,登录验证都是必不可少的环节,在 SpringBoot 开发的我的项目中,通过实现拦截器来实现用户登录拦挡并验证。

Spring Boot 实现登录拦挡原理

SpringBoot 通过实现 HandlerInterceptor 接口实现拦截器,通过实现 WebMvcConfigurer 接口实现一个配置类,在配置类中注入拦截器,最初再通过 @Configuration 注解注入配置。

实现 HandlerInterceptor 接口

实现 HandlerInterceptor 接口须要实现 3 个办法:preHandle、postHandle、afterCompletion.3 个办法各自的性能如下: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 在 Controller 之前执行,因而拦截器的性能次要就是在这个局部实现:查看 session 中是否有 user 对象存在;如果存在,就返回 true,那么 Controller 就会持续前面的操作;如果不存在,就会重定向到登录界面。就是通过这个拦截器,使得 Controller 在执行之前,都执行一遍 preHandle.

1.2、实现 WebMvcConfigurer 接口,注册拦截器

实现 WebMvcConfigurer 接口来实现一个配置类,将下面实现的拦截器的一个对象注册到这个配置类中.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 动态资源
    );
}

} 将拦截器注册到了拦截器列表中,并且指明了拦挡哪些拜访门路,不拦挡哪些拜访门路,不拦挡哪些资源文件;最初再以 @Configuration 注解将配置注入。Spring Boot 基础教程和示例代码看这里:https://github.com/javastacks…

1.3、放弃登录状态

只需一次登录,如果登录过,下一次再拜访的时候就无需再次进行登录拦挡,能够间接拜访网站外面的内容了。在正确登录之后,就将 user 保留到 session 中,再次拜访页面的时候,登录拦截器就能够找到这个 user 对象,就不须要再次拦挡到登录界面了.@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、代码实现及示例代码实现如上所示。

在登录胜利之后,将 user 信息保留到 session 中,下一次登录时浏览器依据本人的 SESSIONID 就能够找到对应的 session,就不要再次登录了,能够从 Chrome 浏览器中看到。

3、成果验证

3.1、拜访 localhost:8081/index 页面:

被重定向到了 localhost:8081/login,实现了登录拦挡。

3.2、正确输出用户名和明码登录

3.3、再次拜访 localhost:8081/index

没有再次被登录拦截器拦挡,证实能够放弃登录。
版权申明:本文为 CSDN 博主「Kant101」的原创文章,遵循 CC 4.0 BY-SA 版权协定,转载请附上原文出处链接及本申明。
原文链接:https://blog.csdn.net/qq_2719…

退出移动版