Development of simple Servlet2.3 filter: Run a name: Introduction of new Java Servlet 2.3 specification, many of the most exciting features, one of which is filter (filter). Filter can change a request or modify response (Response). Filter is not a servlet, it is just a servlet to accept the pre-processes before the request. That is to say, when the user sends a request to servlet, this Filter is executed before the servlet is processed, and then the execution of the servlet. 2: The role FILTER can be used in the following aspect 1: Access to a specific resource (web page, JSP page, servlet) 2: Accessing resources record 3: Converting the resource 3: Write a Filter a filter must implement Javax. The servlet.filter interface, that is, the three methods below: 1: DOFILTER (ServletRequest, servletResponse, filterchain): This is a method of completing the filtering behavior. This is also the method of upstream filter call. The introduced Filterchain object provides information to be called by the subsequent filters. 2: INIT (FilterConfig): This is an initialization method called by a container. It guarantees that the container is called before the first DOFILTER () call is called. You can get the initialization parameters specified in the web.xml file. 3: DESTROY (): The container is called before the instance is terminated before the filter instance is destroyed.
4: Sample function: Restrict client IP access code as follows: package com.servlet.filter; import java.io. *; import javax.servlet. *; Import javax.servlet.http. *; Import javax.servlet.filter ; public class myfilter implements Filter {private FilterConfig filterConfig = null; public void init (FilterConfig filterConfig) {this.filterConfig = filterConfig;} public void doFilter (ServletRequest req, ServletResponse res, FilterChain chain) throws ServletException, IOException {try {res. SetContentType ("text / html; charset = GBK"); PrintWriter Out = Res.GetWriter (); string remoteaddr = (httpservletRequest) REQ) .GETREMOTEADDR (); if ((RemoteAddr.indexof ("127.0.0.1")! = -1) || ("LocalHost")! = -1)) {// Here to determine out.println ("
head> "); OUT. Println ("