设置springboot的过滤器

1:在SpringApplication启动类中,添加一个Bean,注册一下:

@Bean
public FilterRegistrationBean loginFilter() {
    FilterRegistrationBean reg = new FilterRegistrationBean();
    reg.setFilter(new LoginFilter());
    reg.addUrlPatterns("/user");//意思是这个URL要用过滤器过滤
    reg.addUrlPatterns("/user/*");

    return reg;
}

2:编辑过滤器LoginFilter

public class LoginFilter implements Filter {


    RoleService roleService;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        ServletContext context = filterConfig.getServletContext();
        ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(context);
        roleService = (RoleService) ctx.getBean("roleService");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        String url = request.getRequestURI();
        if (null == user) {

            if (request.getQueryString() != null) {
                url += "?" + request.getQueryString();
            }
            request.setAttribute("raw", url);
            request.getRequestDispatcher("/gologin").forward(request, response);
            return;
        } else {
            //权限判断

            filterChain.doFilter(request, response);


        }
    }

    @Override
    public void destroy() {
        roleService = null;
    }

发表评论

电子邮件地址不会被公开。 必填项已用*标注