Filter

Filters, as the name implies, are Java classes executed by the servlet container for each incoming HTTP request and each HTTP response. This allows you to manage HTTP incoming requests before they reach resources, such as JSP pages, servlets, or simple static pages; In the same way, HTTP outbound responses can be managed after resource execution.

This behavior allows you to implement common functionality that can be reused in many different contexts.

The Filter only works around the Servlet. Filters typically treat request/response as black boxes, and Filters typically do not consider servlet implementations.

As shown in the figure above, the filter runs in the Web container, so its definition will also be included in the web.xml file.

<filter>
    <filter-name>CORSFilter</filter-name>
    <filter-class>com.listfeeds.components.CORSFilter</filter-class>
    <init-param>
        <param-name>fake-param</param-name>
        <param-value>fake-param-value</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>CORSFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
Copy the code

In the filter is defined by com. Listfeeds. Filters. CORSFilter class implements the filter with satisfy all endpoints of expression: / * (in this case, for all)

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;

public class CORSFilter implements Filter {

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

        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin"."*");
        response.setHeader("Access-Control-Allow-Methods"."POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age"."3600");
        response.setHeader("Access-Control-Allow-Headers"."x-requested-with");
        chain.doFilter(req, res);
    }

    public void init(FilterConfig filterConfig) {}

    public void destroy() {}}Copy the code

Filter consists of three main methods:

  • Init: Executes to initialize the filter with the init-param element in the filter definition
  • DoFilter: This command is executed for all incoming HTTP requests that meet urL-pattern
  • Destroy: Releases the resources used by the filter

Filter Application scenarios:

  • Authentication: Blocks requests based on user identity.
  • Logging and auditing: Tracking users of Web applications.
  • Image conversion: Zoom map, etc.
  • Data compression: Smaller downloads.
  • Localization: Locating requests and responses to specific locales.

Request Filters can:

  • Perform safety inspection
  • Reformat the request header or body
  • Request logging and auditing

Response Filters can:

  • Compressed response flow
  • Append or change the response stream
  • Completely create a different response

The Filter’s wheels are:

  • Authentication Filters
  • Logs and requests audit the Filters
  • Image conversion Filters
  • Data compression Filters
  • Encryption FIlter
  • .

Interceptor

Spring interceptors are similar to Servlet filters, but they work in the Spring Context, so they are very powerful for managing HTTP requests and responses, but they can achieve much softer behavior because they have access to all Spring contexts.

Interceptor can drill in and out of methods, throw exceptions, etc., so interceptors have more flexibility. Interceptors allow users to hook into the lifecycle of a request, getting information during the request. Interceptors are usually more coupled to the request.

Spring interceptors are executed in the SpringMVC context, so they are defined in the spring-servlet.xml file:

<mvc:interceptors>
    <bean class="com.listfeeds.interceptors.LogContextInterceptor" />
    <bean class="com.listfeeds.interceptors.TimedInterceptor" />
</mvc:interceptors>
Copy the code

Com. Listfeeds. Interceptors. LogContextInterceptor interceptor class, used to Log4j Thread context add parameters.

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.MDC;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

public class LogContextInterceptor extends HandlerInterceptorAdapter {

    private static final Logger log = LoggerFactory.getLogger(LogContextInterceptor.class);

    public static final String LOG_IDENTIFYING_TOKEN = "logIdentifyingToken";

    @Override
    public void afterCompletion(
            HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {

        HandlerMethod methodHandler = (HandlerMethod) handler;
        log.debug("END EXECUTION method {} request: {}", methodHandler.getMethod().getName(), request.getRequestURI());

        Boolean settato = (Boolean) request.getAttribute(LOG_IDENTIFYING_TOKEN);
        if(settato ! = null && settato) { MDC.remove(LOG_IDENTIFYING_TOKEN); } } @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { try {if( MDC.get(LOG_IDENTIFYING_TOKEN) == null ) {

                /* Retrieve parameters useful for logging */
                @SuppressWarnings("unchecked")
                Map<String,String> pathVariables = 
                (Map<String, String>) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);

                String applicationId = null;
                if( pathVariables ! = null ) applicationId = pathVariables.get("applicationId");

                if ( StringUtils.isEmpty(applicationId) ) 
                    applicationId = request.getParameter("applicationId");

                String loggingToken = 
                        String.format("ApplicationId: %s", applicationId);

                MDC.put(LOG_IDENTIFYING_TOKEN, loggingToken);
                request.setAttribute(LOG_IDENTIFYING_TOKEN, Boolean.TRUE);
            }


        }
        catch ( IllegalArgumentException e)
        {
            log.warn("Prehandle",e);
            return true;
        }
        finally {
            HandlerMethod methodHandler = (HandlerMethod) handler;
            //logger.debug("START EXECUTION " + methodHandler.getMethod().getName());
            log.debug("START EXECUTION method {} request: {}", methodHandler.getMethod().getName(), request.getRequestURI());


        }


        return true; }}Copy the code

Interceptor contains the following main methods:

  • PreHandle: Executed before the target resource is executed
  • AfterCompletion: Execute after executing the target resource (after rendering the view)
  • PosttHandle: Intercepts handler execution