Fun SpringBoot 2 rapid integration of Filter

Outline

SpringBoot no web.xml, we can not configure the Filter in web.xml according to the original way. But we can be configured by JavaConfig (@Configuration + @ Bean) mode. Filter to add custom SpringBoot filtered through a chain FilterRegistrationBean.

Combat operations

By defining a combat operation to intercept the URL Filter all access to the project to carry out presentation.

First define a unified access URL Filter blocked. code show as below:

public class UrlFilter implements Filter {
    private Logger log =  LoggerFactory.getLogger(UrlFilter.class);
 
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
    HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String requestURI = httpServletRequest.getRequestURI();
        StringBuffer requestURL = httpServletRequest.getRequestURL();
        log.info("requestURI:" +requestURI+" "+"requestURL:"+requestURL);
        chain.doFilter(httpServletRequest, response);
    }
 
}

Configuration chain based FilterRegistrationBean SpringBoot filtered through javaConfig embodiment, specific code as follows:

@Configuration
public class FilterConfig {
    @Bean
    public FilterRegistrationBean filterRegistration() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(new UrlFilter());
        List<String> urlList = new ArrayList<String>();
        urlList.add("/*");
        registration.setUrlPatterns(urlList);
        registration.setName("UrlFilter");
        registration.setOrder(1);
        return registration;
    }
}

FilterRegistrationBean method described in:

registration.setFilter (Filter filter): We set up a custom Filter objects.

registration.setUrlPatterns(Collection urlPatterns): Set Custom Collection URL Filter needs of interception.

registration.setName (String name): Set Custom Filter name.

registration.setOrder (int order): set a custom order intercept Filter.

test

Start SpirngBoot project and access the index.html under our project through the tour is.
Here Insert Picture Description
Here Insert Picture Description

Guess you like

Origin www.cnblogs.com/jerry126/p/11460247.html