基於springboot配置攔截器


1.編寫攔截器類:

public class loginHandlerInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        if(session.getAttribute("username")==null){
            request.setAttribute("msg","請先登錄");
            request.getRequestDispatcher("/").forward(request,response);
            return  false;
        }
        else return true;
    }
}

2.在mvc配置類中添加攔截器

//導入配置
@Configuration
//繼承WebMvcConfigurer
public class mvcConfig implements WebMvcConfigurer {

    //添加自定義攔截器
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new loginHandlerInterceptor()).addPathPatterns("/**")
                //配置不攔截的路徑
                .excludePathPatterns("/","/login","/css/**","/js/**","/fonts/**","images/**");
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM