Javaweb Filter Quick Start (17)

Source: Internet
Author: User
Tags set cookie

Filter 1. Introduction to Filters
1. The filter is one of the three components of the Java Web, which in many respects is similar to the servlet 2. Filters can be understood as interceptors, in fact the code of the filter is around the resources being accessed before and after the access to the resources to provide enhanced role (such as filters like a floor security, all personnel through the floor must be security) 3. Filter Application Scenario: 1). Pre-processing is done before the target resource is executed, such as setting the encoding, which is usually released, just before the target resource is executed for 2. Pass conditions to determine whether the release, such as verifying whether the current user is logged on, or whether the user IP has been disabled 3). After the target resource is executed, do some follow-up special processing, for example, the data that the target resource outputs is processed
2. Filter writing steps
1. Write a class to implement the Javax.servlet.Filter interface. Write the filter code 2 in the Dofilter method. What resources are configured in Web. XML to go through the filter <filter><filter-name> name </filter-name><filter-class> package name. Class Name </ Filter-class></filter><filter-mapping><filter-name> named </filter-name><url-pattern > Intercepted resources </url-pattern></filter-mapping> a target resource can specify multiple filters, the order in which the filters are executed is in the Web. xml File </filter-mapping > Deployment Order
3. Filter execution process and life cycle
1. Filters are instantiated and initialized at application startup 2, each access to a resource within a filter range is called DoFilter3, and the application is uninstalled when the Destory method is called
4. Filterconfig&filterchain
Servletconfigservletcontext Getservletcontext (): method to obtain ServletContext;? String getfiltername (): Gets the configuration name of the filter, corresponding to the <filter-name> element; String Getinitparameter (string name): Gets the initialization configuration of the filter, corresponding to the <init-param> element; Enumeration Getinitparameternames (): Gets the name of all initialization parameters The parameter of the Filterchaindofilter () method has a parameter of type Filterchain. It has only one method: DoFilter (servletrequest,servletresponse) Difference: 1. The number of different  filter interface DoFilter is 3 parameters: ServletRequest, Servletresponse,filterchainfilterchian's Dofilter is a 2 parameter: ServletRequest, ServletResponse2. Effect of different filter interface Dofilter interception function Filterchian The release effect of Dofilter
5. Filter other configuration
Four types of filtering: REQUEST FORWARD INCLUDE  error<filter-mapping>    <filter-name>filter06_typetest</ filter-name>    <url-pattern>/*</url-pattern>    <dispatcher>REQUEST</dispatcher> <!--default request, if other types are configured, the default is no--    <dispatcher>INCLUDE</dispatcher>    <dispatcher >ERROR</dispatcher></filter-mapping>
6. Consolidation of packaging design patterns
1, decorative pattern formula A, define a class to implement the same as the wrapper class interface B, define a variable to remember the wrapper class object reference C, define the construction method, passing in the wrapper class object instance D, for the method to be rewritten, rewrite can E, for the method that does not need to overwrite, call the corresponding method of the wrapped object 2, Decoration mode changes the method of rewriting the class, itself is a wrapper class A, define a class, Inherit the Class B to wrap, define a variable, remember the wrapper class reference C, define the constructor method, pass in the wrapper class instance D, overwrite the method to overwrite
Case of the filter 1. Filter simple case (coded/static and dynamic cache control)
1. The implementation of the filter to set the encoding strong to request and response strong to request and response, initialize the container when the Assignment Config property string encoding = Config.getinitparameter (" Encoding "); request.setcharacterencoding (encoding); Response.setcontenttype (" text/html;charset= "+encoding); Chain.dofilter (request, response); 2. Full station dynamic resource no cache strong transfer request and Responseresponse.setheader ("Expires", "0"), Response.setheader ("Cache-control", "No-cache"); Response.setheader ("Pragma", "no-cache"); Chain.dofilter (request, response); 3. Static resource settings cache time strong transfer request and responsestring URI = Request.getrequesturi (); String extendsionname = uri.substring (Uri.lastindexof (".") +1); String time = "0"; time = Config.getinitparameter (extendsionname); Request.setcharacterencoding ("UTF-8"); Response.setcontenttype ("Text/html;charset=utf-8"), if (time! = null) {Response.setdateheader ("Expires", System.currenttimemillis () +integer.parseint (time) *60*60*1000);} Chain.dofilter (request, response); Finally, do not forget to configure the Web. xml file
2. Automatic User Login
User Auto-Login Case 1.  The table in the new database and the corresponding JavaBean object CREATE database day19;use day19;create table user (ID int primary key,username varchar) NOT NULL Unique,password varchar (+) NOT null);p rivate int id;private string Username;private string password;2. The data access layer Userdaoimpl class void Save (user user) User find (string username, string password) 3. The tool class introduces the Dbutils/c3p0util/encodingutil tool Class 4. The business logic layer Businessserviceimpl class public void register (user user) public user Finduser (string username, string password) 5. Loginservlet class Filter solves garbled problem 5.1 Get request parameter 5.2 Call business logic determine if login successful 5.3 set user name and password in cookie information cookie c = new Cookie ("Logininfo", Logininfo) ; 5.4 Determine the way the user chooses, set the appropriate validity period 5.5 Set cookie path 5.6 Adds a cookie to the response header 5.7 redirects to the first page 6. Logoutservlet Class 6.1 Removes the user6.2 new empty cookie information in the session domain, sets the cookie's validity period to expire 0, sets the cookie path, and adds the response header information to the 6.3 redirect to the first page 7. Filter class, processing code 7.1 Gets the initialization of the parameter 7.2 after setting the encoding before releasing 8. Automatic Login Filter Class AutoLoginFilter8.1 force request,response8.2 to get the requested URI information 8.3 if the requested parameter is not in login.jsp login 8.4 Gets the user8.5 in the session domain If user is null 8.6 Gets the requested cookie information 8.7 if the obtained cookie is a null redirect login page 8.8 Iterates through all cookies, if the user's cookie is assigned to a new cookie,break;8.9 if the assignment of a new cookie is not NULL, get the value in the cookie 8.10 cut values get username and password in the value 8.11 decode the user name, call the business logic layer method to determine the user name and password 8.12 If the obtained user name is not empty, set the user to the session field 8.13 chain release page design 1. The login.jsp User Login page provides a choice of validity period, submitted to Loginservlet Class 2. Top.jsp header, if the user in session domain is empty, prompt login, if not empty, prompt welcome interface, provide logout function 3. Index.jsp introduced top.jsp, providing post link 4. 1.jsp Post Links
3. Filter expansion case (full-site coding/Sensitive Vocabulary/html tag filter)
1. Full station coding problem 1). Strong turn Request/response2). Set the encoding in order to resolve the post coding problem 3). To resolve the Get commit encoding problem, wrap the Request object 4 before Dofilter release. Define Myhttpservletrequest inheritance HttpServletRequestWrapper5). Override the GetParameter method Super.getparameter (name), receive the value of the parameter requested by the user if NULL directly returns NULL to determine the way the request is Super.getmethod (), if the GET request, encode the requested value and then decode 2. Sensitive Vocabulary Filter 1). Strong turn Request/response2). Wrap the Request object 3 before Dofilter release). Define Myhttpservletrequest inheritance HttpServletRequestWrapper4). Define Thesaurus Vocabulary 5). Gets the value of the request parameter, or, if NULL, returns null 6 directly. Traverse the thesaurus, replacing the value of the request parameter 7). Finally returns the value of the request parameter 3. HTML tag filter 1). Strong turn Request/response2). Wrap the Request object 3 before Dofilter release). Define Myhtmlservletrequest inheritance HttpServletRequestWrapper4). Call the filter method to replace the value of the request parameter 5). The filter method is Tomcat\webapps\examples\web-inf\classes\util\htmlfilter.java
4. Full-Station compression
1. Set up gzip compression filter class GzipFilter2. Rewrite the response before releasing, then pass the rewritten response to DoFilter3. For Httpservletresponsewrapper, rewrite the class as Myhttpservletresponse, overriding Getoutputstream and Getwriter method 3.1 to define the staging container 3.2 Defines the data getbufferbyte () 6 that gets the staging container. Implementation of Httpservletresponsewrapper for temporary containers, providing write method for writing data to a temporary container

Javaweb Filter Quick Start (17)

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.