How to create my own filter with Spring MVC?

前端 未结 7 1522
名媛妹妹
名媛妹妹 2020-12-14 07:40

I use Spring MVC (4.0.1) as a backend for rest services and angularjs as frontend.

every request to my server backend has a http-header with a session id

I c

相关标签:
7条回答
  • 2020-12-14 08:11

    Below is the filter to perform the logic you have mentioned

    @WebFilter("/*")
    public class AuthTokenFilter implements Filter {
    
        @Override
        public void destroy() {
            // ...
        }
    
        @Override
        public void init(FilterConfig filterConfig) throws ServletException {
            //
        }
    
        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
            String xHeader = ((HttpServletRequest)request).getHeader("X-Auth-Token");
            if(getPermission(xHeader)) {
                chain.doFilter(request, response);
            } else {
                request.getRequestDispatcher("401.html").forward(request, response);
            }
        }
    }
    

    And you got it right, the spring config should be following.

    public class MyWebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
        @Override
        protected Filter[] getServletFilters() {
            return new Filter[]{new AuthTokenFilter()};
        }
    }
    
    0 讨论(0)
提交回复
热议问题