The use of filter in the Web and the solution of garbled problem

Source: Internet
Author: User

First, the filter Filter1. Introduction to Filter

Filter is the filtering of the client access resources, conforms to the conditional release, does not conform to the condition not released, and can be logically processed before and after access to the target resource

2. Quick Start

Steps:

1) Write a filter class to implement the filter interface

2) Implement methods that are not yet implemented in the interface (focus on implementing the Dofilter method)

3) configuring in Web. XML (primarily configuring which resources to filter)

(1) Create filter implementation filter

After the interception to release.

 Packagefilter;Importjava.io.IOException;ImportJavax.servlet.Filter;ImportJavax.servlet.FilterChain;ImportJavax.servlet.FilterConfig;Importjavax.servlet.ServletException;Importjavax.servlet.ServletRequest;ImportJavax.servlet.ServletResponse; Public classFirstfilterImplementsFilter {@Override Public voidInit (Filterconfig filterconfig)throwsservletexception {//TODO auto-generated Method Stub} @Override Public voidDoFilter (servletrequest request, servletresponse response, Filterchain chain)throwsIOException, servletexception {//Automatic intercept requestsSYSTEM.OUT.PRINTLN ("Filter Running ...");//ReleaseChain.dofilter (request, response); } @Override Public voiddestroy () {//TODO auto-generated Method Stub    }}

(2) Web. XML Configure a bit
<filter>      <filter-name>FirstFilter</filter-name>      <filter-class>filter. firstfilter</filter-class>  </filter>  <filter-mapping>      <filter-name >FirstFilter</filter-name>      <url-pattern>/*</url-pattern>  </ Filter-mapping>

/* represents all requests, and if not released, the client is not responding.

3. Filter's API details (1) Filter life cycle and its life cycle related methods

The filter interface has three methods, and this three is a method associated with the life of the filter

Init (Filterconfig): Represents the Filter object initialization method that is executed when the filter object is created

DoFilter (Servletrequest,servletresponse,filtercha): The core method to perform filtering on behalf of filter, if a resource is already configured to filter on this filter, Then each access to this resource will execute the Dofilter method

Destory (): Represents the filter Destroy method when the filter object is destroyed when the method is executed

The life cycle of the filter object:

When filter is created: The Filter object is created when the server starts

Intermediate call Dofilter method when a client accesses a resource filtered by a filter

When filter is destroyed: Filter is destroyed when the server shuts down

(2) Filter's API explanation

1) init (filterconfig)

Where the parameter config represents the configuration information for the filter object, the internal encapsulation is the configuration information for that filter.

2) Destory () method

Executed when the filter object is destroyed

3) Dofilter method

DoFilter (Servletrequest,servletresponse,filterchain)

The parameters are:

Servletrequest/servletresponse: Each time the Dofilter method is executed, the Web container is responsible for creating a request and a response object that is passed in as a parameter of the Dofilter. The request for this response is the request and response when accessing the service method of the target resource.

Filterchain: The filter Chain object, through which the Dofilter method of the object can release the request

4. Configuration of filter
<Filter>      <Filter-name>Filter2</Filter-name>      <Filter-class>Filter. Filter2</Filter-class>       <Init-param>          <Param-name>Name</Param-name>          <Param-value>Dahua</Param-value>      </Init-param>  </Filter>  <filter-mapping>      <Filter-name>Filter2</Filter-name>      <Url-pattern>/*</Url-pattern>      <Dispatcher>REQUEST</Dispatcher>  </filter-mapping>

You can also intercept servlets directly (equivalent to URL-PATTERN/SERTVLE1)

< filter-mapping >      < Filter-name > Filter2</filter-name>      <servlet-name> servlet</servlet-name>  </filter-mapping  >
①url-pattern configuration (do not write project name, direct write path)

1) Exact Match/sertvle1

2) directory matching/aaa/bbb/*----the most

/user/*: Access to the front-desk resources into this filter

/admin/*: Execute this filter when accessing resources in the background

3) filename extension matches *.abc *.jsp

Note: Url-pattern can be replaced with servlet-name or mixed

Dispatcher: How to access (learn)

REQUEST: Default value, which represents the execution of a filter when accessing a resource directly

Forward intercept once, redirect 2 times

FORWARD: Filter is executed only when forwarding

Include: Execute filter When a resource is included

Error: A jump is performed when a fault occurs when the filter is executed

5. Summarize the role of filter?

1) Extraction of public code

2) The methods in request and response can be enhanced (decorator mode/dynamic proxy)

3) Control of permissions

6. Summary

1.Filter Write implementation method, and then configure in Web. XML (name, map, and intercept requests)

Do not write project name when Url-pattern configuration

1) Exact Match/sertvle1

2) directory matching/aaa/bbb/*----the most

/user/*: Access to the front-desk resources into this filter

/admin/*: Execute this filter when accessing resources in the background

3) filename extension matches *.abc *.jsp

2. The order in which the filters are executed is based on the order in which you map them in Web. Xml.

3. User requests can be filtered:

 PackageWeb.filter;Importjava.io.IOException;ImportJavax.servlet.Filter;ImportJavax.servlet.FilterChain;ImportJavax.servlet.FilterConfig;Importjavax.servlet.ServletException;Importjavax.servlet.ServletRequest;ImportJavax.servlet.ServletResponse;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;Importjavax.servlet.http.HttpSession;ImportDaomain. User; Public classRequestfilterImplementsFilter {@Override Public voidInit (Filterconfig filterconfig)throwsservletexception {//TODO auto-generated Method Stub} @Override Public voidDoFilter (servletrequest request, servletresponse response, Filterchain chain)throwsIOException, servletexception {//TODO auto-generated Method StubHttpServletRequest req =(httpservletrequest) request; HttpServletResponse Res=(httpservletresponse) response; HttpSession Session=req.getsession (); User User= (user) Session.getattribute ("user")); if(user==NULL) {Request.getrequestdispatcher ("/index.jsp"). Forward (request, response); }        Else{System.out.println (user);    } chain.dofilter (request, response); } @Override Public voiddestroy () {//TODO auto-generated Method Stub            }    }

Two, set the encoding format 1. Post Submission (1) Writing filter code
@Override      Public void DoFilter (servletrequest request, servletresponse response, Filterchain chain)             throws IOException, servletexception {        request.setcharacterencoding ("Utf-8");        Chain.dofilter (request, response);    }
(2) Web. XML Squadron All request interception (3) background directly accept post submitted in Chinese data 2. Get Commit

Receive Front end:

String para = Request.getparameter ("name"new String (para.getbytes ("iso-8859-1"), "Utf-8");

Send To front end
// Set the Code table         for the response query // response.setcharacterencoding ("UTF-8");                 // tell the client what code table        to use with a header Content-type // Response.setheader ("Content-type", "Text/html;charset=utf-8");         // This sentence is         equivalent to the above sentence, only in the development of writing this sentence, Tomcat automatically set the first sentence        response.setcontenttype ("Text/html;charset=utf-8");

Third, decorator mode to solve garbled
 Packagefilter;Importjava.io.IOException;Importjava.io.UnsupportedEncodingException;ImportJavax.servlet.Filter;ImportJavax.servlet.FilterChain;ImportJavax.servlet.FilterConfig;Importjavax.servlet.ServletException;Importjavax.servlet.ServletRequest;ImportJavax.servlet.ServletResponse;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletRequestWrapper; Public classEncodingfilterImplementsfilter{@Override Public voidDoFilter (servletrequest request, servletresponse response, Filterchain chain)throwsIOException, servletexception {//request.setcharacterencoding ("UTF-8"); //enhance the GetParameter method of the request before passing the request        /** Decorator Mode (PACKAGING) * * 1, enhanced class and enhanced class to implement unified interface * 2, in the enhanced class to pass in the enhanced class * 3, requiring enhanced method overrides do not require enhanced method invocation The enhanced object's **/                //objects that are enhancedHttpServletRequest req =(httpservletrequest) request; //Enhanced ObjectsEnhancerequest enhancerequest =Newenhancerequest (req);            Chain.dofilter (enhancerequest, response); } @Override Public voiddestroy () {} @Override Public voidInit (Filterconfig filterconfig)throwsservletexception {}}classEnhancerequestextendshttpservletrequestwrapper{PrivateHttpServletRequest request;  Publicenhancerequest (HttpServletRequest request) {Super(Request);  This. Request =request; }        //for getparaameter Enhancement@Override Publicstring GetParameter (string name) {string parameter= Request.getparameter (name);//garbled        Try{parameter=NewString (Parameter.getbytes ("iso8859-1"), "UTF-8"); } Catch(unsupportedencodingexception e) {e.printstacktrace (); }        returnparameter; }    }

The use of filter in the Web and the solution of garbled problem

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.