How to create my own filter with Spring MVC?

前端 未结 7 1558
名媛妹妹
名媛妹妹 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:50

    Alternative to Filters, you can use HandlerInterceptor.

    public class SessionManager implements HandlerInterceptor{
    
        // This method is called before the controller
        @Override
        public boolean preHandle(HttpServletRequest request,
                HttpServletResponse response, Object handler) throws Exception {
    
            String xHeader = request.getHeader("X-Auth-Token");
            boolean permission = getPermission(xHeader);
            if(permission) {
                return true;
            }
            else {
                response.setStatus(HttpStatus.UNAUTHORIZED.value());
                return false;
                // Above code will send a 401 with no response body.
                // If you need a 401 view, do a redirect instead of
                // returning false.
                // response.sendRedirect("/401"); // assuming you have a handler mapping for 401
    
            }
            return false;
        }
    
        @Override
        public void postHandle(HttpServletRequest request,
                HttpServletResponse response, Object handler,
                ModelAndView modelAndView) throws Exception {
    
        }
    
        @Override
        public void afterCompletion(HttpServletRequest request,
                HttpServletResponse response, Object handler, Exception ex)
                throws Exception {
    
        }
    }
    

    And then add this interceptor to your webmvc config.

    @EnableWebMvc
    @Configuration
    public class WebConfig extends WebMvcConfigurerAdapter {
    
        @Bean
        SessionManager getSessionManager() {
             return new SessionManager();
        }
    
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            registry.addInterceptor(getSessionManager())
            .addPathPatterns("/**")
            .excludePathPatterns("/resources/**", "/login");
         // assuming you put your serve your static files with /resources/ mapping
         // and the pre login page is served with /login mapping
        }
    
    }
    

提交回复
热议问题