登陸攔截器Interceptor


攔截器的目的是什么?

當然是,攔截非法操作,我們需要登陸的,和不需要登陸的需求。

開始進行操作:

第一步:

建立需要攔截的對象,如我自己建立的Iterceptor

public class LoginInterceptor implements HandlerInterceptor{

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        // TODO Auto-generated method stub
        HttpSession session=request.getSession();
        String contextPath=session.getServletContext().getContextPath();
        String[] requirePath=new String[] {
                "admin_userlist",
                "admin_reservelist",
                "admin_about",
                "admin_post_list",
                "admin_config_list"
        };
        String uri=request.getRequestURI();
        uri=org.apache.commons.lang3.StringUtils.remove(uri, contextPath+"/");
        String page=uri;
        if(Beginwith(page,requirePath)) {
            User user=(User) session.getAttribute("user");
            if(user== null) {
                response.sendRedirect("hello");
                return false;
            }
        }
        return true;
    }
    private boolean Beginwith(String page,String[] requirePath) {
        boolean result=false;
        for(String requirePa :requirePath) {
            if(StringUtils.startsWith(page, requirePa)) {
                result=true;
                return result;
            }
        }
        return result;
        
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
            ModelAndView modelAndView) throws Exception {
        // TODO Auto-generated method stub
        
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        // TODO Auto-generated method stub
        
    }

}

代碼不講解,low

第二步,配置攔截器configure

@Configuration
public class WebMvcConfigurer extends WebMvcConfigurerAdapter {

    @Bean
    public LoginInterceptor loginInterceptor() {
        return new LoginInterceptor();
    }
    
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(loginInterceptor())
        .addPathPatterns("/**");
    }
}
該攔截器在springboot框架基礎上進行配置


免責聲明!

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



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