Spring 4 autofilter for filter

I am creating an application with Spring 4.1.6, I have all the configuration in the java class. My AppConfig:

    @Configuration
    @EnableWebMvc
    @ComponentScan(basePackages = "pl.wrweb.springrest")
    public class AppConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {

    }

    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }

    @Bean(name = "messageSource")
    public ReloadableResourceBundleMessageSource getMessageSource() {
        ReloadableResourceBundleMessageSource resource = new ReloadableResourceBundleMessageSource();
        resource.setBasename("classpath:messages");
        resource.setDefaultEncoding("UTF-8");
        return resource;
    }

}

      

AppInitializer:

public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    public void onStartup(ServletContext container) throws ServletException {


        AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
        ctx.register(AppConfig.class);
        ctx.setServletContext(container);
        ServletRegistration.Dynamic servlet = container.addServlet("dispatcher", new DispatcherServlet(ctx));
        servlet.setLoadOnStartup(1);
        servlet.addMapping("/");

        container.addFilter("customFilter",  new DelegatingFilterProxy(new CustomFilter())).addMappingForUrlPatterns(null, true, "/*");

    }

    @Override
    protected String[] getServletMappings() {
        return new String[0];
    }


    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class<?>[0];
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class<?>[0];
    }
}

      

and my CustomFilter:

@Configuration
@EnableWebSecurity
public class CustomFilter implements  Filter {

    @Autowired
    UserService userService;

    public void init(FilterConfig fc) throws ServletException {

    }

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain fc) throws IOException, ServletException {

        HttpServletRequest httpServletRequest = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;

        if (httpServletRequest.getRequestURI().contains("/employee/")) {
            String token = httpServletRequest.getHeader("x-token");
            System.out.println("token " + token);
            Long userId = TokenUtils.getUserNameFromToken(token);
            System.out.println("ObjectStore.token " + ObjectStore.token);

            if (token!=null) {
                if (token.equals(String.valueOf(ObjectStore.token))) {
                    int index = ObjectStore.token++;
                    ObjectStore.token = index+1;
                    System.out.println("index " +ObjectStore.token + "token " + token);
                    response.setHeader("x-token", String.valueOf(ObjectStore.token));
                    fc.doFilter(req, response);
                } else {
                    response.sendError(HttpStatus.FORBIDDEN.value());
                    fc.doFilter(req, response);
                    return;
                }
            } else {
                response.sendError(HttpStatus.FORBIDDEN.value());
                fc.doFilter(req, response);
                return;
            }
        } else {
            fc.doFilter(req, res);
        }
    }

    public void destroy() {

    }

}

      

Everything works fine, but I cannot enter userService and it is null, I need this to validate the token in the request.

+3


source to share


1 answer


hi you must use code like this !!!

private UserService userService;

      



and then

public void init(FilterConfig fc) throws ServletException {
  ApplicationContext app =  WebApplicationContextUtils.getRequiredWebApplicationContext(fc.getServletContext());
     userService= app.getBean(UserService.class);
}

      

+1


source







All Articles