SpringBoot background login interception

Directory structure is as follows:
Here Insert Picture Description
LoginInterceptor packet interceptor under the code as follows:

package com.yx.blog.interceptor;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor extends HandlerInterceptorAdapter
{
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler)throws Exception {

        if(request.getSession().getAttribute("user")==null)
        {//如果没有登录,响应admin
            response.sendRedirect("/admin");
            return false;//失败
        }
        return true;//成功
    }
}

WebConfig Code:

package com.yx.blog.interceptor;


import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginInterceptor())
                .addPathPatterns("/admin/**")//所有的admin路径都不能越过登录,直接操作后台
                .excludePathPatterns("/admin")//排除路径admin
                .excludePathPatterns("/admin/login");//排除/admin/login
    }
}

Published 53 original articles · won praise 18 · views 10000 +

Guess you like

Origin blog.csdn.net/YUEXILIULI/article/details/103166916