Filter wrappers in the Javaweb

Source: Internet
Author: User

Things to do with filters:
Request Filter: Complete security check, and again format the request header or body. Create a request audit or log
Response Filter:
Compress the response stream, append or alter the response stream to create a completely different response.

Filter and servlet three similar places:
1. The container knows the API of the filter, the other members of the filter API can access the ServletContext and can also link with other filters
2. Container Management filter life cycle, filter has init and destroy method. and a Dofilter method.
3.web applications can have very many filters. Need to be configured in config file

Life cycle of filters
When the Init container instantiates a filter. All initialization tasks before the call filter are completed in the Init method.

Save Filterconfig Object
A reference for filtering to be used later.
The second call to DoFIlter is able to save the username record into a file, compressing the response output.


Finally destroy deletes a filter instance,

Filterchain's Dofilter method is responsible for understanding the next call to whom the Dofilter zooms in, assuming that the end of the chain is reached, then determine which Servlet's service method to invoke.



Determine the order of the filters in the configuration file
Do three things in the config file
1. Declaring filters
2. Map the filters to the Web resources you want to filter
3, organize these mappings, create a filter call sequence
Declaring filters
<filter>
<filter-name>BeerRequest</filter-name>
<filter-class>com.gac.test.BeerRequestFilter</filter-class>
<init-param>
<param-name>LogFileName</param-name>
<param-value>UserLog.txt</param-value>
</init-param>
</filter>
Filter mappings for declaring URL patterns
<filter-mapping>
<filter-name>BeerRequest</filter-name>
<url-pattern>*.do</url-pattern>
</filter-mapping>
Filter mappings that declare the corresponding servlet names
<filter-mapping>
<filter-name>BeerRequest</filter-name>
<servlet-name>AdviceServlet</servlet-name>
</filter-mapping>




To declare a filter map for Web resources that request dispatch requests
<filter-mapping>
<filter-name>MonitorFilter</filter-name>
<url-pattern>*.do</url-pattern>
<dispatcher>REQUEST</dispatcher>
and/or
<dispatcher>INCLUDE</dispatcher>
and/or
<dispatcher>FORWARD</dispatcher>
and/or
<dispatcher>ERRO</dispatcher>
</filter-mapping>
Claim rules:
Must have Filter-name
Must have one of the Url-pattern or servlet-name elements.
Capable of having 0-4 dispatcher
The request value indicates that the filter is enabled on client requests, assuming that the <dispatcher> element is not specified. Zemer Think
Rquest

The include value indicates that a filter is enabled for requests sent by an include () call
The forward value indicates that a filter is enabled for a request sent by a forward () call
The error value indicates that the filter is enabled on the fault-handling call resource


Filter Request Path Sample
<filter-mapping>
<filter-name>Filter1</filter-name>
<url-pattern>/Recipes/*<url-pattern>/recipes/hopsreport.do Filter Sequence 1 5

</filter-mapping>/recipes/hopslist.do Filter 15 2
<filter-mapping>
<filter-name>Filter2</filter-name>/recipes/modify/modrecipes.do Filter 1 5 4
<url-pattern>/Recipes/HopsList.do<url-pattern>/hopslist.do Filter 5
</filter-mapping>
<filter-mapping>/recipes/add/addrecipes.do Filter 1 3 5
<filter-name>Filter3</filter-name>
<url-pattern>/Recipes/Add/*<url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>Filter4</filter-name>
<url-pattern>/Recipes/Modify/ModRecipes.do<url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>Filter5</filter-name>
<url-pattern>/*<url-pattern>

</filter-mapping>

/**************************************************************/

Filters must implement the filter interface
public class Beerrequestfilter implements filter{

Private Filterconfig FC;
Finish the cleanup work.
@Override
public void Destroy () {
TODO auto-generated Method Stub

}

Detailed business logic
@Override
public void DoFilter (ServletRequest req, Servletresponse resp,
Filterchain chain) throws IOException, Servletexception {
TODO auto-generated Method Stub
HttpServletRequest httpreq = (httpservletrequest) req;//ability to cast request and response objects to HTTP type
String name = Httpreq.getremoteuser ();
if (name! = null) {
Fc.getservletcontext (). log ("User" +name + "is updating");
}
Chain.dofilter (req, resp);//The next filter or servlet to invoke

}

Init must be implemented typically only in the configuration Config object is saved
@Override
public void init (Filterconfig config) throws servletexception {
TODO auto-generated Method Stub
this.fc = config;
}


}


/***************************************************************/


Compress the data response for the filter in order not to implement too many functions to reduce complexity can take advantage of wrappers.
Demo sample using the wrapper
public class Compressfilter implements filter{

Private ServletContext CTX;
Private Filterconfig cfg;
@Override
public void Destroy () {
TODO auto-generated Method Stub
CFG = null;
CTX = null;
}


The filter core is a decorative wrapper response object, which wraps the output stream with a compressed IO stream.
Output stream compression is completed when and only if the customer includes a accept-encoding header
@Override
public void DoFilter (ServletRequest request, servletresponse response,
Filterchain chain) throws IOException, Servletexception {
TODO auto-generated Method Stub
HttpServletRequest req = (httpservletrequest) request;
HttpServletResponse resp = (httpservletresponse) response;

String valid_encodings = Req.getheader ("accept-encoding");//Whether the customer receives gzip compression
if (Valid_encodings.indexof ("gzip") >-1) {
Compressresponsewrapper Wrappedresp = new Compressresponsewrapper (RESP);
Wrappedresp.setheader ("content-encoding", "gzip");
Chain.dofilter (req, WRAPPEDRESP);

Gzipoutputstream Gzos = Wrappedresp.getgzipoutputstream ();
Gzos.finish ();
Ctx.log (Cfg.getfiltername () + ": finished the request. ");

}else{
Ctx.log (Cfg.getfiltername () + ": no encoding performed.");
}
}

The Init method saves the configuration object and saves a direct reference to the Servlet context object to complete the logging
@Override
public void init (Filterconfig filterconfig) throws Servletexception {
TODO auto-generated Method Stub
This.cfg = Filterconfig;
CTX = Cfg.getservletcontext ();
Ctx.log (Cfg.getfiltername () + "initialized.");
}

}






public class Compressresponsewrapper extends httpservletresponsewrapper{

Private Gzipservletoutputstream Servletgzipos = compressed output stream for null;//servlet response
private PrintWriter PW = null;

Public Compressresponsewrapper (HttpServletResponse response) {
Super (response);
TODO auto-generated Constructor stub
}

public void setcontentlength (int len) {}

/* Filter using this adorner method the compression filter provides a handle to the gzip output stream so that the filter finishes and refreshes the output gzip stream */
Public Gzipoutputstream Getgzipoutputstream () {
return This.servletGzipOS.internalGzipOS;

}

Private Object streamused = null;//agreed to visit the decorated servlet output stream
Public Servletoutputstream Getoutputstream () throws ioexception{
Consent to servlet access to the servlet output stream only if the servlet has not yet visited the print writer
if ((null! = streamused) && (STREAMUSED!=PW)) {
throw new IllegalStateException ();
}

Wrap the original servlet output stream with our compressed output stream
if (Servletgzipos = = null) {
Servletgzipos =
New Gzipservletoutputstream (GetResponse (). Getoutputstream ());

streamused = Servletgzipos;
}
return servletgzipos;
}

Perform an interview with the decorated print writer
Public PrintWriter getwriter () throws ioexception{
if (streamused! = null) && (streamused! = Servletgzipos)) {
throw new IllegalStateException ();
}
if (PW = = null) {
Servletgzipos =
New Gzipservletoutputstream (GetResponse (). Getoutputstream ());
OutputStreamWriter OSW =
New OutputStreamWriter (Servletgzipos,getresponse (). getcharacterencoding ());
PW = new PrintWriter (OSW);
streamused = PW;
}
return PW;
}

}
Class Gzipservletoutputstream extends servletoutputstream{

/*internalgzipos saves a reference to the original gzip stream. This instance variable is private within the scope of the package, so the response wrapper can access this variable */
Gzipoutputstream Internalgzipos;
Adorner constructors
Gzipservletoutputstream (Servletoutputstream SOS) throws ioexception{
This.internalgzipos = new Gzipoutputstream (SOS);
}
This method puts the write call to the GZIP compression stream to achieve compression decoration gzip compressed Stream packaging the original Servletoutputstream
@Override
public void Write (int b) throws IOException {
TODO auto-generated Method Stub
Internalgzipos.write (b);
}

}





Filter wrapper in Javaweb

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.