SpringBoot拦截器实现登录拦截

  • 源码

GitHub:https://github.com/291685399/springboot-learning/tree/master/springboot-interceptor01

  • SpringBoot拦截器可以做什么

可以对URL路径进行拦截,可以用于权限验证、解决乱码、操作日志记录、性能监控、异常处理等

  • SpringBoot拦截器实现登录拦截

pom.xml


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0modelVersion>
    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>2.0.0.RELEASEversion>
        <relativePath/>
    parent>
    <groupId>com.wyjgroupId>
    <artifactId>springboot-interceptor01artifactId>
    <version>0.0.1-SNAPSHOTversion>
    <name>springboot-interceptor01name>
    <description>springboot拦截器description>

    <properties>
        <java.version>1.8java.version>
    properties>

    <dependencies>
        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-devtoolsartifactId>
            <scope>runtimescope>
            <optional>trueoptional>
        dependency>

        
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <optional>trueoptional>
        dependency>

        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-thymeleafartifactId>
        dependency>
    dependencies>

    <build>
        <finalName>springboot-interceptor01finalName>
        <plugins>
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
            plugin>
        plugins>
    build>
project>

WebMvcConfigurer:继承WebMvcConfigurationSupport类,重写addInterceptors方法

/**
 * 在springboot2.0.0之后,WebMvcConfigurerAdapter已经过时了
 * 会使用WebMvcConfigurer或者WebMvcConfigurationSupport替代
 *
 * @author wyj
 * @create 2019-06-01 21:48
 */
@Configuration
public class WebMvcConfigurer extends WebMvcConfigurationSupport {

    /**
     * 在springboot2.0.0之前继承WebMvcConfigurerAdapter类,重写addInterceptors方法
     *
     * @param registry
     */
//    @Override
//    public void addInterceptors(InterceptorRegistry registry) {
//        /**
//         * 拦截器按照顺序执行,如果不同拦截器拦截存在相同的URL,前面的拦截器会执行,后面的拦截器将不执行
//         */
//        registry.addInterceptor(new AuthorityInterceptor())
//                .addPathPatterns("/user/**");
//        super.addInterceptors(registry);
//    }

    /**
     * 在springboot2.0.0之后实现WebMvcConfigurer接口,重写addInterceptors方法
     *
     * @param registry
     */
//    @Override
//    public void addInterceptors(InterceptorRegistry registry) {
//        /**
//         * 拦截器按照顺序执行,如果不同拦截器拦截存在相同的URL,前面的拦截器会执行,后面的拦截器将不执行
//         */
//        registry.addInterceptor(new AuthorityInterceptor())
//                .addPathPatterns("/user/**");
//    }

    /**
     * 在springboot2.0.0之后继承WebMvcConfigurationSupport类,重写addInterceptors方法
     *
     * @param registry
     */
    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        /**
         * 拦截器按照顺序执行,如果不同拦截器拦截存在相同的URL,前面的拦截器会执行,后面的拦截器将不执行
         */
        registry.addInterceptor(new AuthorityInterceptor())
                .addPathPatterns("/user/**");
        super.addInterceptors(registry);
    }
}

AuthorityInterceptor:实现HandlerInterceptor接口,重写preHandlepostHandleafterCompletion方法

preHandle:在请求处理之前进行调用(Controller方法调用之前)
postHandle:请求处理之后进行调用,但是在视图被渲染之前(Controller方法调用之后)
afterCompletion:在整个请求结束之后被调用,也就是在DispatcherServlet 渲染了对应的视图之后执行(主要是用于进行资源清理工作)

@Slf4j
public class AuthorityInterceptor implements HandlerInterceptor {

    private static final Set<String> NOT_INTERCEPT_URI = new HashSet<>();//不拦截的URI

    static {
        NOT_INTERCEPT_URI.add("/user/login.html");
        NOT_INTERCEPT_URI.add("/user/login");
    }

    /**
     * 在请求处理之前进行调用(Controller方法调用之前)
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object object) throws Exception {
        String uri = request.getRequestURI();
        if (NOT_INTERCEPT_URI.contains(uri)) {
            log.info("不拦截" + uri);
            return true;
        }
        log.info("拦截" + uri);
        HttpSession session = request.getSession();
        UserInfo userInfo = (UserInfo) session.getAttribute("user_info_in_the_session");
        if (userInfo == null) {
            throw new RuntimeException("用户未登陆");
        }
        return true;
    }

    /**
     * 请求处理之后进行调用,但是在视图被渲染之前(Controller方法调用之后)
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object object, ModelAndView mv) throws Exception {
    }

    /**
     * 在整个请求结束之后被调用,也就是在DispatcherServlet 渲染了对应的视图之后执行
     * (主要是用于进行资源清理工作)
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object object, Exception ex) throws Exception {
    }
}

UserController

@Controller
@RequestMapping(value = "/user")
public class UserController {

    @RequestMapping(value = "/login.html")
    public String index() {
        return "login";
    }

    @RequestMapping(value = "/login")
    public String login(User user) {
        //查询数据库,我这里直接写死
        User dbUser = new User(1, "zhangsan", "123456", "admin");
        if (dbUser.getPassword().equals(user.getPassword())) {
            UserInfo userInfo = new UserInfo(dbUser.getId(), dbUser.getUsername(), dbUser.getRole());
            HttpSession session = getRequest().getSession();
            session.setAttribute("user_info_in_the_session", userInfo);
            return "admin";
        }
        return "login";
    }

    @RequestMapping(value = "/userInfo")
    @ResponseBody
    public String userInfo() {
        HttpSession session = getRequest().getSession();
        UserInfo userInfo = (UserInfo) session.getAttribute("user_info_in_the_session");
        return userInfo.toString();
    }

    private HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
    }
}

User:

@Data
@NoArgsConstructor
@AllArgsConstructor
public class User implements Serializable {

    private int id;
    private String username;
    private String password;
    private String role;

}

UserInfo: 用于存在用户信息储存在session中

@Data
@NoArgsConstructor
@AllArgsConstructor
public class UserInfo implements Serializable {

    private int id;
    private String username; 
    private String role;

}

login.html:只是一个很简单的登录表单


<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登陆页面title>
head>
<body>
<form action="/user/login" method="post">
    登陆:<br/>
    用户名:<input name="username" id="username" type="text"/><br/>   码:<input name="password" id="password" type="password"/><br/>
    <input type="submit" value="登陆"/>
form>
body>
html>

admin.html:


<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>首页title>
head>
<body>
<form action="/user/userInfo" method="get">
    <input type="submit" value="用户信息"/>form>
body>
html>

你可能感兴趣的:(SpringBoot)