Javaweb three main components
1. All need to be configured in Web. xml
Servlet
Listener
Filter
2. Filter
It manages a large resource through Web. XML, which executes in front of a set of resources (JSP, servlet,. css,. html, and so on)! It intercepts the processing when you want to access the resources it manages. It allows the request to get the target resource, or it can not get the request to reach! It's like a doorman. As long as you are working on a lot of resources, you should think of filter
How filters are written
1. Write a class to implement the filter interface
2. What resources are configured to manage in Web. xml
1. Filter interface
| 123456 |
publicvoiddoFilter(ServletRequest request, ServletResponseresponse, FilterChain chain) throwsIOException, ServletException{ System.out.println("filterstart..."); chain.doFilter(request,response);//放行 System.out.println("filterend..."); } |
void Init (Filterconfig)
* Once created, execute immediately; filter will be created when the server is started!
void Destory ()
* Destroy before execution! Destroy when the server shuts down
void DoFilter (Servletrequest,servletresponse,filterchain)
* Each filter will be executed
Filter is single-case! Like the servlet.
2. Web. xml
<filter>
<filter-name>xxx</filter-name>
<filter-class>web.filter.AFitler</fitler-class>
</servlet>
<fitler-mapping>
<filter-name>xxx</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
This configuration represents which resources are managed by this filter. When you access these resources, the filter executes Dofilter ().
Filterconfig--> is similar to ServletConfig
* Get initialization parameters: Getinitparameter ()
* Get Filter Name: Getfiltername ()
* Get Appliction:getservletcontext ()
Filterchain (this is for release)
* DoFilter (ServletRequest, servletresponse): Release!
is equivalent to invoking the service () method of the target servlet!
-------------------------------
-------------------------------
Multi-Filter Case Filterchain Dofilter () method: Execute the target resource, or execute the next filter! If there is no next filter then the target resource is executed, and if so, then the next filter is executed!
-------------------------------
Four Ways to intercept filters
<dispatcher>REQUEST</dispatcher> Default! Intercept Direct requests
<dispatcher>FORWARD</dispatcher> Intercept Request Forwarding
<dispatcher>INCLUDE</dispatcher> interception request contains
<dispatcher>ERROR</dispatcher> Intercept Error forwarding
Configure in <filter-mapping>!
-------------------------------
Order of execution for multiple filters
The order in which the <filter-mapping> is configured determines the order in which the filters are executed!
Application Scenarios for filters:
pre-processing is done before the target resource is executed, for example, by setting the encoding, which is usually released , only to do some preparation before the target resource is executed;
Pass the conditions to determine whether the release, many Java tutorials say, such as verifying whether the current user is logged in, or whether the user IP has been disabled;
After the target resource is executed, do some follow-up special processing, for example, the data that the target resource outputs is processed
Instance:
Statistics IP
Loop through the map in ServletContext, where key is the IP address and value is the number of accesses
JSP page
| 123456789101112131415 |
<body><table align="center"width="50%"border="1"> <tr> <th>IP地址</th> <th>次数</th> </tr><c:forEach items="${aplicationScope.ipCountMap}"var="entry"> <tr> <td>${entry.key }</td> <td>${entry.value }</td> </tr></c:forEach> </table> </body> |
Filter code
| 12345678910111213141516171819202122232425262728 |
public voidinit(FilterConfig fConfig) throwsServletException { context = fConfig.getServletContext(); Map<String, Integer> ipCountMap = newLinkedHashMap<String, Integer>(); context.setAttribute("ipCountMap", ipCountMap); } publicvoiddoFilter(ServletRequest request, ServletResponseresponse, FilterChain chain) throwsIOException, ServletException{ HttpServletRequest req = (HttpServletRequest) request; String ip = req.getRemoteAddr(); Map<String, Integer> ipCountMap = (Map<String,Integer>) context .getAttribute("ipCountMap"); Integer count = ipCountMap.get(ip); if(count == null) { count = 1; } else{ count += 1; } ipCountMap.put(ip, count); context.setAttribute("ipCountMap", ipCountMap); chain.doFilter(request, response); } publicvoiddestroy() {}} |
Solve the whole station character garbled
Garbled problem:
L GET the garbled problem in the request parameter;
Post request: request.setcharacterencoding ("Utf-8");
Get Request: NewString (request.getparameter ("xxx"). GetBytes ("Iso-8859-1"), "Utf-8");
L Response garbled problem: Response.setcontexttype ("Text/html;charset=utf-8").
It is simple to process a POST request, but it takes parameters to process a GET request, and it is not possible for the filter to get parameters for all of the filtered resources. You can switch the request to the servlet. Enhance the Request object (change Getparamater () method. Let's solve the garbled problem every time I get the parameter.
There are three ways to enhance an object: (Enhancement of a object, Fun1 () method)
-
Inheritance: aa class inherit a class, then overrides fun1 () method, where the overridden fun1 () method is an enhanced method. However, inheritance must know the true type of a objects before they can be inherited. If we do not know the exact type of a object, and only know a object is ia interface, then cannot use inheritance to enhance a objects;
-
Decorator mode: AA class to implement a objects the same interface: ia interface, also need to give aa class a objects, the implementation of all methods of the AA class is the same method of invoking the A object implementation, only the FUN1 () method needs to change the next content, Enhancements to FUN1 ();
-
Dynamic proxy: Similar to enhancer mode
The request object is enhanced here by inheriting the decorator class of the request object, which is the wrapper class for the interface, but it does not make any enhancements, and by inheriting it and then rewriting the methods that need to be enhanced, you do not have to rewrite the methods that need to be enhanced.
(Enhanced when a look at inheriting classes, two see there is no interface of the wrapper class, three-interface decorator mode)
| 1234567891011121314151617181920212223242526272829 |
publicclassEncodingFilter implementsFilter { publicvoiddestroy() { } publicvoiddoFilter(ServletRequest request, ServletResponse response, FilterChain chain) throwsIOException, ServletException { // 处理post请求编码问题 request.setCharacterEncoding("utf-8"); HttpServletRequest req = (HttpServletRequest) request; /* * 处理GET请求的编码问题 */// String username = request.getParameter("username");// username = new String(username.getBytes("ISO-8859-1"), "UTF-8"); /* * 调包request */ if(req.getMethod().equals("GET")) { EncodingRequest er = newEncodingRequest(req); chain.doFilter(er, response); } elseif(req.getMethod().equals("POST")) { chain.doFilter(request, response); } } publicvoidinit(FilterConfig fConfig) throwsServletException { }} |
Inherit wrapper class enhancement request
| 123456789101112131415161718192021 |
/** * 装饰reqeust */public classEncodingRequest extendsHttpServletRequestWrapper { privateHttpServletRequest req; publicEncodingRequest(HttpServletRequest request) { super(request); this.req = request; } publicString getParameter(String name) { String value = req.getParameter(name); // 处理编码问题 try{ value = newString(value.getBytes("iso-8859-1"), "utf-8"); } catch(UnsupportedEncodingException e) { thrownew RuntimeException(e); } returnvalue; }} |
Filter for Java