springboot、拦截器

1.添加配置文件

//@Configuration 声明这是一个配置类,相当于一个xml文件
@Configuration
public class WebConfiguraion {

    @Bean
    public FilterRegistrationBean testFilterRegistrationBean(){
        
        //加载自定义过滤器
        FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        //设置过滤器
        registrationBean.setFilter(new MyFilter());
        //指定过滤连接
        registrationBean.addUrlPatterns("/*");
        registrationBean.addInitParameter("paraname", "paramvalue");
        registrationBean.setName("MyFilter");
        
        //设置优先级
        registrationBean.setOrder(1);
        return registrationBean;
    }
    
}

2.配置我的过滤器

public class MyFilter implements Filter {

    @Override
    public void destroy() {
        // TODO Auto-generated method stub
        System.out.println("销毁!");
        
    }

    @Override
    public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
            throws IOException, ServletException {
        // TODO Auto-generated method stub
        System.out.println("执行你的过滤器!");
        
        //进行转换
        HttpServletRequest request=(HttpServletRequest) arg0;
        HttpServletResponse response=(HttpServletResponse) arg1;
        //设置字符编码
        request.setCharacterEncoding("UTF-8");  
        response.setCharacterEncoding("UTF-8"); 
        
        String path=request.getRequestURI();
        System.out.println("被拦截的地址是:"+path);
       if(path.indexOf("/us/login")>-1){//登录页面不过滤
            System.out.println("放行:/us/login");
            arg2.doFilter(request, arg1);//递交给下一个过滤器
            return;
        }
        if ("/us/checklogin".equals(request.getRequestURI())) {
            System.out.println("放行:us/checklogin");
            arg2.doFilter(request, arg1);
            return;
        }
        
        User user = (User) request.getSession().getAttribute("users");  
        
        
        if (user !=null) {
            //放行
            System.out.println("已登录!");
            arg2.doFilter(request, arg1);
        }else {
            System.out.println("不放行!!");
            //arg2.doFilter(request, arg1);
            System.out.println("重定向到:/us/login");
            response.sendRedirect(request.getContextPath()+"/us/login");
        
        }
        
        
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {
        // TODO Auto-generated method stub
        
    }
    

}

 

上一篇:增长***国内落地实践


下一篇:Java服务器端如何实现跨越