How to create my own filter with Spring MVC?

前端 未结 7 1542
名媛妹妹
名媛妹妹 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 07:49

    Your approach looks correct.

    Once I have used something similar to following (Removed most of the lines and kept it simple).

    public class MvcDispatcherServletInitializer  extends AbstractAnnotationConfigDispatcherServletInitializer {
    
        @Override
        public void onStartup(ServletContext servletContext) throws ServletException {
            super.onStartup(servletContext);
    
            EnumSet dispatcherTypes = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.ERROR);
    
            FilterRegistration.Dynamic monitoringFilter = servletContext.addFilter("monitoringFilter", MonitoringFilter.class);
            monitoringFilter.addMappingForUrlPatterns(dispatcherTypes, false, "/api/admin/*");
        }
    
        @Override
        protected Class[] getRootConfigClasses() {
            return new Class[] { WebMvcConfig.class };
        }
    
        @Override
        protected Class[] getServletConfigClasses() {
            return null;
        }
    
        @Override
        protected String[] getServletMappings() {
            return new String[] { "/" };
        }
    
    }
    

    Also you need a custom filter looks like below.

    public class CustomXHeaderFilter implements Filter {
    
            @Override
            public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
                HttpServletRequest request = (HttpServletRequest) req;
                HttpServletResponse response = (HttpServletResponse) res;
    
                String xHeader = request.getHeader("X-Auth-Token");
                if(YOUR xHeader validation fails){
                    //Redirect to a view
                    //OR something similar
                    return;
                }else{
                    //If the xHeader is OK, go through the chain as a proper request
                    chain.doFilter(request, response);
                }
    
            }
    
            @Override
            public void destroy() {
            }
    
            @Override
            public void init(FilterConfig arg0) throws ServletException {
            }
    
        }
    

    Hope this helps.

    Additionally you can use FilterRegistrationBean if you Spring Boot. It does the same thing (I think so) which FilterRegistration.Dynamic does.

提交回复
热议问题