The best practice of Java8 design pattern-design pattern overview (the sixth day of learning records)

Implementing the intercepting filter pattern using Java EE 8

To implement this pattern with the best practices of Java EE 8, we will use the servlet filter
to implement this pattern with the best practices of javaee8 , we will use the servlet filter
from the Java Servlet specification. With the servlet filter, we can create an ordered request
comes from the Javaservlet specification. Using servlet filters, we can create an orderly request
interceptor to treat the requests and responses. These interceptors are mapped by the URL
interceptor to process requests and responses. These interceptors are mapped by URL
pattern or servlet name. The servlet filter can be configured with XML (on web.xml) or
pattern or servlet name. The servlet filter can be configured as XML (onweb.xml file) or
annotation. In our case, we will imagine that we want to create a log of all the requests that
annotations. In our example, we assume that we want to create a log that records all requests
are sent to the server. We will also have two filters—one to log the access time and another
sent to the server. We will also have two filters, one
to log the access time and the other to log the information about the browser that the client is using. To log the access time, we log the information about the browser that the client is using
. To record the access time, we
will create a filter called LogAccessFilter, and to log the browser information we will
we will
create a filter called LogAccessFilter create a filter called LogBrowserFilter.
Create a filter called LogBrowserFilter to filter browser information.

Implementing LogAccessFilter

Here, we have the implementation of LogAccessFilter:

package com.gary.book.chapter01;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Date;

@WebFilter(filterName = "LogAccess", urlPatterns = "/*")
public class LogAccessFilter implements javax.servlet.Filter {
    
    
    private static Logger logger =
            LogManager.getLogger(LogAccess.class);

    public void destroy() {
    
    
    }

    public void doFilter(javax.servlet.ServletRequest req,
                         javax.servlet.ServletResponse resp, javax.servlet.FilterChain
                                 chain) throws javax.servlet.ServletException, IOException {
    
    
        //Gets the initial date of request.
        Date dateInitRequest = new Date();
        //Get IP of Client that sent a resquest.
        String ip = ((HttpServletRequest) req).getRemoteAddr();
        //Following to next filter. If none next filter exist, follows
        //for main logic.
        chain.doFilter(req, resp);
        //Gets the end date of request.
        Date dateEndRequest = new Date();
        //Logging the informations of IP and access time.
        logger.info("IP: " + ip + " Access time : "
                + Long.toString(dateEndRequest.getTime()
                - dateInitRequest.getTime())
                + " ms");
    }

    public void init(javax.servlet.FilterConfig config) throws
            javax.servlet.ServletException {
    
    
    }
}

As we can see in the code, to create one servlet filter, we need to create a class that
, as we see in the code, to create a servlet filter, we need to create a class that
extends javax.servlet.Filter and puts the @WebFilter annotation with filterName
inherits javax.servlet.Filter and puts the @WebFilter annotation with filterName
and urlPatterns parameters, which define the filter name and the URLs to filter, before
and urlPatterns parameters, which define the filter name and requirements Filtered url
the definition of class. The following is a snippet of code that demonstrates how to do that
class definition. Below is a piece of code that demonstrates how to do this

@WebFilter(filterName = "LogAccess", urlPatterns = "/*")
public class LogAccessFilter implements javax.servlet.Filter{
    
    
 ...
}

Note that the servlet filter uses the chain of responsibility pattern to walk throughout the
servlet filter
(objects that are servlet filter). The following is a snippet of code that uses a chain of
filter ( servlet filter object). The following is the use of
responsibility pattern:
responsibility mode:

chain.doFilter(req, resp);

In the preceding line of code, we established the filter name as LogAccess through. In the preceding line of code, we set the filter name as
LogAccess through
the filterName parameter. This will filter all requests, because the
filterName parameter. This will filter all requests because
the urlPatterns parameter has the "/ "value. If we filter according to servlet name, the we
urlPatterns parameter has the "/
" value. If we filter based on the servlet name, then
need to use the following annotation
:

//Servlet1 and Servlet2 are the servlets to filter.
@WebFilter(filterName = "LogAccess", servletNames =
{
    
    "servlet1","servlet2"})

Responsible for the doFilter IS Method of The pre-POST-Processing and Processing and
the doFilter method is responsible for pre and post processing and
establishes when to follow the request to the next filter or servlet (main logic). To follow the
determining when the tracking request to A filter or servlet (main logic). Following
request to the next filter or servlet, the following code needs be executed: When
requesting the next filter or servlet, the following code needs to be executed :

//Following to next filter or servlet.
chain.doFilter(req, resp);

When the preceding code is executed, the current filter executes only the next line when the
previous code is executed, the current filter executes only the next line when the
other filters and servlets finish their processing.
Other filters and servlets finish their processing .

Implementing LogBrowserFilter

The implementation of LogBrowserFilter is as follows:

package com.gary.book.chapter01;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@WebFilter(filterName = "LogBrowser", urlPatterns = "/*")
public class LogBrowserFilter implements Filter {
    
    
    private static Logger logger = LogManager.getLogger(LogBrowser.class);

    public void destroy() {
    
    
    }

    public void doFilter(ServletRequest req, ServletResponse resp,
                         FilterChain chain) throws ServletException, IOException {
    
    
        //Get userAgent that contain browse informations.
        String userAgent = ((HttpServletRequest) req).getHeader("UserAgent");
        //Get IP of Client that sent a resquest.
        String ip = ((HttpServletRequest) req).getRemoteAddr();
        //Logging the informations of IP and Browser.
        logger.info("IP: " + ip + " Browser info: " + userAgent);
        //Following to the next filter. If none next filter exist, follow to main logic.
        chain.doFilter(req, resp);
    }

    public void init(FilterConfig config) throws ServletException {
    
    
    }
}


In the preceding filter, we get the client IP and browser information and log them. The preceding filter, we get the client IP and browser information and log them
. This
LogBrowserFilter operation is similar to that of LogAccessFilter.
The operation of LogBrowserFilter is similar to that of LogAccessFilter .
To define the order of filter execution, we need to configure the web.xml and add the filter
you want to define the order of execution of the filter, we need to configure web.xml file plus filter
mapping information. Here, we can see web. xml with its configuration:
mapping information. Here, we can see the configuration of the web.xml file:

<web-app version="3.1"
 xmlns="http://xmlns.jcp.org/xml/ns/javaee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
 <filter>
 <filter-name>LogBrowser</filter-name>
 <filter-class>com.rhuan.filter.LogBrowserFilter</filter-class>
 </filter>
 <filter>
 <filter-name>LogAccess</filter-name>
 <filter-class>com.rhuan.filter.LogAccessFilter</filter-class>
 </filter>
</web-app>

The configurations defined in web.xml override the annotation configurations. Thus, if the configuration defined in the web.xml file overrides the annotation configurations
. Therefore, if we
put the urlPattern configuration on web.xml, then the configuration considered
enable urlPattern configuration web.xml file, and then consider the configuration
is web.xml's configuration. We don't put the filter mapping information on web.xml
is web. The configuration of the xml file. We do not put the filter mapping information in the web.xml file
because this is already on the annotation configuration in the code.
Because this is already on the annotation configuration in the code .
The web.xml configuration defines the order-LogBrowserFilter will be called first,
the configuration definition file web.xml LogBrowserFilter the first call sequence,
the Followed by LogAccessFilter, and the then The main Logic (the servlet).
Next is LogAccessFilter, then the main logic (Servlet).

Deciding filter mapping

Filter defined mapping
Defining the mapping method is crucial to implementing the intercepting filter pattern.
Defined mapping method is the key to intercept filtration mode.
This is because a bad method for mapping can impact the project directly and cause. This is because a bad method for mapping can
directly affect the project and cause
rework. We have two filter mapping types—UrlPattern and servlet name
. We have two filter mapping types: UrlPattern and servlet name.
The use of UrlPatterns is indicated when we want to filter the HTTP Requests to nonspecific resources or files, but we also want to filter various unknown resources. Here are
When we want to filter the HTTP Requests to nonspecific resources or files, UrlPatterns is There are instructions, but we also want to filter various unknown resources. Give you
some examples of this:
Some examples of this are:
.jsp:. This Filters All Requests to the If JSP Pages and the IS added to One Page at The JSP
.jsp: It filters all requests to jsp pages. If a JSP page is added to the
server, then the filter will filter the new JSP page without making any
server, the new filter will filter JSP page, without any
Modifications.
Modifications.
/
: This Filters All Requests to All Files Resources or the If ON at The One Resource Server or.
/
: This will filter all requests for resources or all files on the server. If a resource or
file is added to the server, then the filter will filter this new resource or
file has beenadded to the server, then the filter will filter this new resource or
file without performing any modifications
.
/ the User / : This Filters All Requests to ON at The All Resources Files or Server that have have A
/ the User /
: This will be screened on the server
URI beginning with / user If one resource
URIs beginning with /user. If a resource or file is accessed by URI
beginning with /user is added on servlet, then the filter will filter this new
to add the beginning with /user on the servlet, then the filter will filter this new
resource or file without performing any modifications .
Do not execute any modified resources or files.
The servlet name used to map the filter indicates when you want to filter a specific servlet,
the servlet name mapping filter when the filter indicates the particular servlet,
Independent of ITS urlPattern. This Way of Mapping to Modify android.permission US One
independent Its urlPattern. This mapping method allows us to modify a
urlPattern of the mapped servlet without performing any modifications on the filter. The urlPattern of the mapped servlet without performing any modifications on the filter
.
Here are some examples:
The following are some examples:
{} servlet1: This Maps The only the If the servlet The servlet1 the named AS.
{servlet1}: This only maps the servlet named servlet1. If
urlPatterns of servlet1 are modified, then the filter doesn't need to be
servlet1's urlPatterns are modified, then the filter does not need to be
modified
.
servlet1 {,} servlet2: This Maps TWO servlets named servlet1 and
{servlet1, servlet2}: This map and the two named servlet1
servlet2 Its behavior is similar to the previous example shown, in which only.
Services 2. Its behavior is similar to the previous example, where only
one servlet was mapped.
One servlet was mapped.

Guess you like

Origin blog.csdn.net/Coder_Boy_/article/details/110382614