_jsp Podcast Java Web Filter programming

Source: Internet
Author: User
Tags stub java web
is not conducive to use, the servlet should have been created to simplify the work Ah! I thought it was my design framework that created a problem. The next day I asked the teacher, there are indeed some problems in use. For example, to display the access count, I wrote it separately as a servlet, and where it was needed, the servlet.include reference to the counted servlet. But this will always produce some problems and inconvenience in use. For example, the include servlet must use the same stream, and any output will not be valid if the forward is used.
Fang's teacher then suggested that some features be written together. But at last I mentioned the filter, then I was interested in the filter, and today I finally see the! People like it very much!
Servletfilter,servlet Filter:
Filter is also known as filters, it is the most exciting technology in the Servlet technology, Web developers through the filter technology can be managed by the Web server All Web resources: JSP, Servlet, static picture files or static HTML files, etc. to intercept, In order to realize some special functions. such as the implementation of URL-level access control, filtering sensitive words, compressed response information, and other advanced features.
SERVLETAPI provides a filter interface, and the servlet that implements this interface is a filter. The filter is as follows in the Web application access process:
As shown by the diagram, as long as we write a filter, we can filter all the connections that access the Web application. For example, user access rights, unified Web Coding ...
How does the filter achieve interception?
The servlet that implements the filter interface is a filter because the filter interface has a dofilter (ServletRequest request, servletresponse response, Filterchain chain) method, the server invokes the Dofilter method of the filter whenever the user accesses the mapping directory that we configured in Web.xml. We implement the filtering function code here, when we call Chain.dofilter (request, response), and then the request is reversed to the server server to invoke the equivalent servlet. If we do not call this method, the user's request is denied.
Introduction to filter development:
To add a filter to a Web application, there are two steps to complete:
1. Write a servlet--filter that implements the filter interface.
2. Configure the filter in Web.xml:
(1). <filter> Label Add device
(2). <filter-mapping> Register the filter directory (filter directories), the same as the registered servlet.
In real-world Web applications, we may need to write multiple filters, such as: 1. Unified Web-coded filters (filter all Access) 2. User access Rights Management. In this way, the user's access needs to be filtered by filter 1 and then filtered by filter 2. Dofilter has a filterchain parameter, which is the filter chain that the server generates sequentially according to the filters configured in Web.xml. When we call Chain.dofilter (request, response) in the Dofilter method, the server looks for filters in the filter chain, if there is a continuation call to the next filter, if the corresponding servlet is not invoked to process the user request.
Other details of the filter interface:
1.Filter Init (Filterconfig filterconfig) method:
Like the Init method of the servlet, it is invoked at creation time and then stored in memory until the server restarts or shuts down, and the filter instance is destroyed. Unlike a servlet, all of the filter is instantiated when the server is started, and the servlet is instantiated when the user accesses it for the first time. We can get it through filterconfig by using the initialization parameters of the <init-param> filter configuration in Web.xml.
The Filterconfig methods are:
String getfiltername (): Gets the name of the filter.
String Getinitparameter (string name): Returns the value of the initialization parameter that specifies the name in the deployment description. Returns null if it does not exist.
Enumeration Getinitparameternames (): An enumeration collection that returns the names of all initialization parameters for a filter.
Public ServletContext Getservletcontext (): Returns a reference to the Servlet context object.
2.Filter Destroy () method:
This method is called before the filter is destroyed when the server restarts or shuts down.
To write a configuration filter practice program:
1. Write a filter for unified Web character encoding:
Copy Code code as follows:

Package cn.itcast.cc.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;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;
public class Encoding implements Filter {
public void Destroy () {
TODO auto-generated Method Stub
}
public void Dofilter (ServletRequest arg0, Servletresponse arg1,
Filterchain arg2) throws IOException, Servletexception {
Parameter conversion as we have it is definitely the HTTP protocol request.
HttpServletRequest request = (httpservletrequest) arg0;
HttpServletResponse response = (httpservletresponse) arg1;
The encoding used to set up the request and response is UTF-8.
Request.setcharacterencoding ("UTF-8");
Response.setcharacterencoding ("UTF-8");
Response.setcontenttype ("Text/html;charset=utf-8");
When the settings are complete, return them to the server.
Arg2.dofilter (arg0, arg1);
}
public void init (Filterconfig arg0) throws Servletexception {
TODO auto-generated Method Stub
}
}

2. Configure the Web.xml file and add the following sections:
Copy Code code as follows:

<filter>
<filter-name>encoding</filter-name>
<filter-class>cn.itcast.cc.filter.Encoding</filter-class>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

3. The above is a simple way to use the filter, followed by advanced applications.
Filter Advanced Development:
Parameter conversion as we have it is definitely the HTTP protocol request.
HttpServletRequest request = (httpservletrequest) arg0;
HttpServletResponse response = (httpservletresponse) arg1;
The two fragment code above is because we already know that request and response are the two HTTP request objects that the server has encapsulated for us. We have expanded it in a functional sense. If we don't know what the specific content of the request and response is, how should we expand their capabilities? There are two ways we can expand:
1. Write a subclass that overrides the method you want to overwrite.
2. Use the decorator design pattern to expand the functionality we want.
Decorator design mode:
We sometimes cannot use Method 1, because we do not know the class of an object, such as it is an interface object, the implementation class is Who? So we'd better use Method 2, before we have contacted the factory design pattern and the single example design pattern, Java is the perfect embodiment of the advanced application. What is the decorator design pattern? The Chinese name is "decorative" mode, we use this mode to do the functional expansion for request:
1. We implement inheritance request interface type ServletRequest. Oh my God, servletrequest there are so many ways, do we have to implement every method? The servlet designers came up with this and gave us a wrapper class--httpservletrequestwrapper. Let's use it as a parent class!
2. Add a HttpServletRequest type member inside our custom class, because we're going to decorate it.
3. Write the way I want to cover, which is the way we want to provide special features.
For example, there is a problem with the unified Web coded filter that we have written above, and if we submit a form and the form is submitted in a get, then the encoding of the request is not working. So here we use the Decorator design pattern to perfect the unified coding function:
Write a custom class Myservletrequest.java class:
Copy Code code as follows:

Class Myservletrequest extends Httpservletrequestwrapper {
We want to decorate the object
HttpServletRequest Myrequest;
Public myservletrequest (HttpServletRequest request) {
Super (Request);
This.myrequest = Request;
}
We want to enhance the functional approach
@Override
public string GetParameter (string name) {
Use the decorated member to get the data
String value = this.myrequest.getParameter (name);
if (value = = null)
return null;
Returns data after transcoding
try {
Value = new String (value.getbytes ("iso8859-1"), "UTF-8");
catch (Unsupportedencodingexception e) {
E.printstacktrace ();
}
return value;
}
}

Our code for modifying the Encoding.java filter is as follows:
Copy Code code as follows:

public class Encoding implements Filter {
public void Destroy () {
TODO auto-generated Method Stub
}
public void Dofilter (ServletRequest arg0, Servletresponse arg1,
Filterchain arg2) throws IOException, Servletexception {
Arg2.dofilter (New Myservletrequest (httpservletrequest) request), arg1);
}
public void init (Filterconfig arg0) throws Servletexception {
TODO auto-generated Method Stub
}
}

Oh, see the decorator design mode of the powerful bar! This part belongs to the advanced application of filter, and a day's course tomorrow will explain the advanced application of filter. I did not think so much, that the request and response have enough to use, even if sufficient, but the efficiency and code is not beautiful, coupled with these advanced applications become more beautiful, procedures and writing and maintenance are very convenient!
The content of the course is still very exciting, although the teacher's content has already understood. But most of the students are still a bit too much, because I have some software development experience, learning to now feel more relaxed. Because the last few days are learning their unfamiliar basic knowledge, now to the advanced application, but also deserved to come! Desktop development or Web applications, the program logic is the same. But the work flow is not the same. More is the need to practice, today's teacher has left everyone homework, the content is to modify the last practice of automatic login and user Rights Management. Well, I should have done my homework.

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.