The memory is inferior to the bad writer filter in 29-java application (1)

Source: Internet
Author: User

Filter, which is very powerful, is one of the most important technologies in the Servlet, and Web application developers use the filter technology to manage all Web resources on the Web server: JSP, Servlet, Static image files or static HTML files, etc. to intercept, so as to achieve some special functions. For example, the implementation of URL-level access control, filtering sensitive words, compressed response information and other advanced features.

Servlet API provides a filter interface that, when developing a Web application, if the Java class you write implements this interface, call this Java Class A filter filter. Filter technology enables developers to intercept requests and responses to access before they access a target resource.

1. Filter ways to implement interception

Filter There is a Dofilter method in the interface , and when we write the filter and configure which Web resource to intercept, the Web server calls the filter's Dofilter method every time before invoking the service method of the Web resource. Therefore, writing code within the method can achieve the following purposes:

Let a piece of code execute before invoking the target resource.

whether to invoke the target resource (that is, whether to let the user access the Web Resource).

After invoking the target resource, let a piece of code execute.

Web When the server calls the Dofilter method, a Filterchain object is passed in, and the Filterchain object is the most important object in the filter interface, and it also provides a Dofilter method. The developer can decide whether to call this method on demand or not, and the Web server invokes the Web resource's service method, which means that the Web resource will be accessed or the Web resource will not be accessed.

2. Filter Development Steps

Filter development consists of two steps:

Write the Java class to implement the filter interface and implement its Dofilter method.

Use the <filter> and <filter-mapping> elements in the Web. XML file to register the filter class that was written and set the resources it can intercept.

3. JAVA example of a filter implemented

Java code for the filter :

Package com.filter;

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;

/**

 * a simple filter

* @author Fan Fangming

*/

public class Easyfilter implementsfilter{

@Override

public void init (Filterconfig filterconfig) throws Servletexception {

System.out.println ("---- Filter Initialization----");

}

   // filter functions are implemented here

@Override

public void DoFilter (ServletRequest request, servletresponse response,

Filterchain chain) Throwsioexception, servletexception {

       // Some preprocessing of request and response

Request.setcharacterencoding ("UTF-8");

Response.setcharacterencoding ("UTF-8");

Response.setcontenttype ("Text/html;charset=utf-8");

System.out.println ("# # # filter before execution!!! ");

Chain.dofilter (request, response);// let the target resource execute, release

System.out.println ("--- filter after execution!!!" ");

}

@Override

public void Destroy () {

System.out.println ("---- Filter Destruction----");

}

}

4. Add a filter to the Web. XML

<?xml version= "1.0" encoding= "UTF-8"?>

<web-app version= "3.0"

Xmlns= "Http://java.sun.com/xml/ns/javaee"

Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"

Xsi:schemalocation= "Http://java.sun.com/xml/ns/javaee

Http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd ">

<display-name></display-name>

<welcome-file-list>

<welcome-file>index.jsp</welcome-file>

</welcome-file-list>

<!-- Configure Filters -

<filter>

<filter-name>easyFilter</filter-name>

<filter-class>com.filter.EasyFilter</filter-class>

</filter>

<!-- Map Filters --

<filter-mapping>

<filter-name>easyFilter</filter-name>

<!-- "/*" means to intercept all requests--

<url-pattern>/*</url-pattern>

</filter-mapping>

<servlet>

<servlet-name>change</servlet-name>

<servlet-class>com.servlet.RequestDispatcher</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>change</servlet-name>

<url-pattern>/change</url-pattern>

</servlet-mapping>

</web-app>

5. servlet for test filters

Package com.servlet;

Import java.io.IOException;

Import javax.servlet.ServletException;

Import Javax.servlet.http.HttpServlet;

Importjavax.servlet.http.HttpServletRequest;

Importjavax.servlet.http.HttpServletResponse;

/**

 * Get the client request information through the request object and forward it to another page

* @author Fan Fangming

*/

public class RequestDispatcher Extendshttpservlet {

Privatestatic final Long serialversionuid = -4150164731865037680l;

Publicvoid doget (httpservletrequest request, httpservletresponse response)

Throwsservletexception, IOException {

Stringrealip = This.getrealip (request);

Request.setattribute ("Realip", Realip);

        // request forwarded to change.jsp

Request.getrequestdispatcher ("/change.jsp"). Forward (Request,response);

}

Publicvoid DoPost (httpservletrequest request, httpservletresponse response)

Throwsservletexception, IOException {

Doget (Request,response);

}

    // If the IP address is changed by proxy, etc.

Publicstring Getrealip (HttpServletRequest request) {

STRINGIP = Request.getheader ("X-forwarded-for");

if (IP = = NULL | | ip.length () = = 0 | | "Unknown". Equalsignorecase (IP)) {

ip= Request.getheader ("Proxy-client-ip");

}

if (IP = = NULL | | ip.length () = = 0 | | "Unknown". Equalsignorecase (IP)) {

ip= Request.getheader ("Wl-proxy-client-ip");

}

if (IP = = NULL | | ip.length () = = 0 | | "Unknown". Equalsignorecase (IP)) {

ip= request.getremoteaddr ();

}

Returnip;

}

}

6. Test Results

### filter execution before!!!

--- after the filter is executed!!!

The filter has been executed.

The memory is inferior to the bad writer filter in 29-java application (1)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.