关于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…

【腾讯云】轻量 2核2G4M,首年65元

阿里云限时活动-云数据库 RDS MySQL  1核2G配置 1.88/月 速抢

本文由乐趣区整理发布,转载请注明出处,谢谢。

您可能还喜欢...

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据