java web filter

  • 2020-05-24 05:57:58
  • OfStack

Servlet should have been created to simplify work. I thought my design framework was the problem. The second day I asked the teacher, is really on the use of some problems. For example, to display the access count, I wrote it as a separate Servlet, and where it is needed, it is counted by the Servlet of that Servlet.include reference. But this will always cause 1 some problems and inconvenience on the use. For example, include's Servlet must use the same stream, and any output will be invalid if forward is used.
Teacher fang at that time suggested that some functions write 1. But finally mentioned the filter, then I was interested in the filter, today also finally 1 look! Let a person 10 points like!
ServletFilter, Servlet filters:
Also known as filters, Filter is one of the most exciting technologies in Servlet technology. WEB developers use Filter technology to intercept all web resources managed by web servers: Jsp, Servlet, static image files, or static html files. For example, the implementation of URL level access control, filtering sensitive words, compressed response information and other advanced functions.
ServletAPI provides an Filter interface, and Servlet, which implements this interface, is a filter. The filter in the WEB application access flow is as follows:
As you can see from the diagram, once you write a filter, you can filter the connection that has access to the WEB application. For example, user access rights, unified 1WEB code...
How does Filter implement interception?
The Servlet that implements the Filter interface is the filter, because the Filter interface has an doFilter(ServletRequest request, ServletResponse response, FilterChain chain) method, and the server calls the doFilter method of the filter whenever the user accesses the mapping directory that we configured in web.xml. Here we implement the override function code, when we call chain.doFilter (request, response); Method, send the request back to the server and the server calls the equivalent Servlet. If we do not call this method, the user's request is denied.
Introduction to Filter development:
Adding a filter to the WEB application requires two steps:
1. Write Servlet -- filter that implements Filter interface.
2. Configure the filter in web.xml:
(1). < filter > Label adder
(2). < filter-mapping > Register the filter's mapping directory (filter directory), like register Servlet1.
In a real WEB application, we might need to write multiple filters, such as: 1. A filter encoded in 1WEB (filtering all access); 2. User access management. Thus, the user's access needs to be filtered through filter 1 and then filtered through filter 2. There is one FilterChain parameter in doFilter, which is the filter chain generated by the server in sequence according to the filters configured in web.xml. When we call chain.doFilter (request, response) in the doFilter method; Method, the server will look to see if there are any filters in the filter chain, if so, continue to call the next filter, if not, the corresponding Servlet will be called to process the user request.
Other details of the Filter interface:
1. Init(FilterConfig filterConfig) method for Filter:
Like Servlet's Init method 1, the Filter instance is called at creation time and then stored in memory until the server is restarted or shut down. Unlike Servlet, all Filter is instantiated when the server is started, whereas in Servlet it is instantiated the first time the user accesses it. We use it by web.xml < init-param > The initialization parameters for the Filter configuration can be obtained by FilterConfig.
The methods of FilterConfig are:
String getFilterName() : get the name of filter.
String getInitParameter(String name) : returns the value of the initialization parameter specified in the deployment description. Return null if it does not exist.
Enumeration getInitParameterNames() : returns an enumerated collection of the names of all initialization parameters of the filter.
public ServletContext getServletContext() : returns a reference to the Servlet context object.
2. destroy() method of Filter:
When the server is restarted or shut down, this method is called before Filter is destroyed.
Write the configuration Filter exercise program:
1. Write an Filter for the unified 1WEB character encoding:
 
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, because we already know that it must be Http Protocol request.  
HttpServletRequest request = (HttpServletRequest)arg0; 
HttpServletResponse response = (HttpServletResponse)arg1; 
// Set up the request and response The codes used are all UTF-8 .  
request.setCharacterEncoding("UTF-8"); 
response.setCharacterEncoding("UTF-8"); 
response.setContentType("text/html;charset=UTF-8"); 
// When the setup is complete, hand it back 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:
 
<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 simple use of Filter is shown above, and advanced applications will be covered later.
Filter advanced development:
// parameter conversion, because we have already it must be the request of Http protocol.
HttpServletRequest request = (HttpServletRequest)arg0;
HttpServletResponse response = (HttpServletResponse)arg1;
The two code snippets above are because we already know that request and response are the two Http request objects that the server has encapsulated for us. We expanded it functionally. If we don't know who created request and response and what they do, how can we extend their functionality? We can expand in two ways:
1. Write a subclass that overrides the method to be overridden.
2. Use Decorator design pattern to extend the functions we want.
Decorator design mode:
Sometimes we can't use method 1 because we don't know the utility class of an object, such as it is an interface object. Who is the implementation class? . So we had better use method 2. We have touched on factory design pattern and singleton design pattern before, Java is a perfect embodiment of advanced application. What is the Decorator design pattern? The Chinese name is "decoration" mode. We will use this mode to expand the function of request:
1. We implement the inheritance of request interface type ServletRequest. Oh my god, ServletRequest has so many methods, are we going to implement every one of them? The designers of Servlet thought of this point and gave us a wrapper class, HttpServletRequestWrapper. Let's use it as the parent class.
2. Add a member of type HttpServletRequest inside our custom class, because we are going to decorate it.
3. Write the method we want to cover, that is, the method we want to provide special functions.
For example, there is a problem with filter encoded in system 1WEB. If we submit a form and the form is submitted in GET, the encoding of request will not work. So here we use Decorator design pattern to improve the function of unified 1 coding:
Write custom class MyServletRequest.java class:
 
class MyServletRequest extends HttpServletRequestWrapper { 
//  The object we want to decorate  
HttpServletRequest myrequest; 
public MyServletRequest(HttpServletRequest request) { 
super(request); 
this.myrequest = request; 
} 
//  We want to enhance the functional methods  
@Override 
public String getParameter(String name) { 
//  Get the data using the decorated member  
String value = this.myrequest.getParameter(name); 
if (value == null) 
return null; 
//  Transcode the data and return it  
try { 
value = new String(value.getBytes("ISO8859-1"), "UTF-8"); 
} catch (UnsupportedEncodingException e) { 
e.printStackTrace(); 
} 
return value; 
} 
} 

We modify the code of Encoding.java filter 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 power of Decorator design mode! This part belongs to the advanced application of Filter, and the advanced application of Filter will be explained in another day's class tomorrow. I thought request and response were enough to use. Even if they were, the efficiency and the code were not beautiful enough. In addition, these advanced applications become beautiful.
The content of the course is still 10 points excellent, although the content of the teacher has been understood. But most of the students still some unbearable, because I have some software development experience, learning to now feel more relaxed 1. Because before a few days are learning oneself unfamiliar foundation knowledge, arrived now advanced application, return calculate to deserve to come! Desktop development or WEB applications, the logic is the same. It's just that the workflow isn't quite the same. More practice is needed. Teacher fang left homework for everyone today, which is to modify the automatic login and user permission management of the last exercise. Well, I should go do my homework... .

Related articles: