Detailed explanation of filters in web.xml and demo of common filters

Detailed explanation of filters in web.xml


First, filter introduction (what is it)

filter function. It allows users to change a request and modify a response. Filter is not a servlet, it cannot generate a response, it can preprocess a request before a request reaches the servlet, or Handle the response when leaving the servlet. In other words, a filter is actually a "servlet chaining" (servlet chaining). A filter consists of:
1. Intercepting the servlet before it is called;
2. Checking the servlet request before the servlet is called;
3. Modify the request header and request data
as needed; 4. Modify the response header and response data as needed;
5. Intercept after the servlet is called.


2. Execution steps

① Project startup instantiation
② Call the init method to initialize (to prepare for filtering)
3. Call dofilter to execute the filtering method (when the user interacts with the front and back ends)
4. Call the destroy method to destroy (when the thread exits, times out or stops the project)


3. Filter configuration

1. Register declaration and mapping operations in xml
2. Implemented in the filter Implement the filter interface in the class


4. Introduction to the filter interface

1. init (used to initialize)
2. dofilter (used to perform specific operations)
This method is provided to the developer by the servlet container and is used to sequentially call the resource request filter chain. The next filter in the filter chain is called through the FilterChain. If it is the last filter, the next one will call the target resource.
3. Destory (used to destroy)


Important Note: ::
In web.xml you can configure a filter to one or more servlets; a single servlet or servlet group can be used by multiple filters.
This example will be attached:
1 , character set encoding format filter
2, sql anti-injection filter
3, filter that does not cache pages



Specific code case
1. Configuration

<filter>//Filter implementation, and address
		<filter-name>patronliFilter</filter-name>//Define name
		<filter-class>com..servlet.FwpFilter</filter-class>//implementation class
</filter>
<filter-mapping>//Mapping filter interception rules
		<filter-name>patronliFilter</filter-name>
		<url-pattern>/*</url-pattern>
		<dispatcher>REQUEST</dispatcher>
		<dispatcher>FORWARD</dispatcher>
</filter-mapping>
//If you want to configure multiple interceptors, you can write down in sequence


2. The specific implementation class and the implemented interception function (character set encoding format filtering)
package com.patronli.servlet;

import java.io.IOException;
import java.util.Map;
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;

import org.apache.commons.lang.StringEscapeUtils;

public class patronliFilter implements Filter {

	@Override
	public void destroy() {
		System.out.println("The initialization method was executed...");
	}

	@Override
	public void doFilter(ServletRequest arg0, ServletResponse arg1,
			FilterChain arg2) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) arg0;
		HttpServletResponse response = (HttpServletResponse) arg1;
		// set character set encoding
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		// HttpSession session = request.getSession();
		// String url = request.getServletPath();
		Map<String, String[]> map = request.getParameterMap();
		// The following method can print out the parameters requested and returned by the user and the response request address
		// It's easy to find problems in production testing
		System.out.println("The address of the request or response is:::" + request.getRequestURI());
		for (Map.Entry<String, String[]> entry : map.entrySet()) {
			for (String str : entry.getValue()) {
				System.out.println("The parameters of the request or response are:::" + entry.getKey() + ":" + str);
				str = StringEscapeUtils.escapeHtml(str);
			}
		}
		// will execute the filtering below the current filter sequentially
		arg2.doFilter(arg0, arg1);
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		System.out.println("Destruction method executed...");
	}

}


(sql anti-injection filtering)

package com.patronli.servlet;


import java.io.IOException;
import java.util.Enumeration;

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;

import com.fuiou.fwp.util.ConfigReader;

/**
 * Filter to filter sql keywords
 *
 */
public class PatronliFilter implements Filter {
	
	public void init(FilterConfig filterConfig) throws ServletException {
		// throw new UnsupportedOperationException("Not supported yet.");
	}
	
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

			HttpServletRequest req = (HttpServletRequest) request;
			HttpServletResponse res = (HttpServletResponse) response;
			String requestUri = req.getRequestURI();
			// get all request parameter names
				Enumeration params = req.getParameterNames();
				System.out.print(req.getRequestURL());
				String str = "";
				while (params.hasMoreElements()) {
					String name = params.nextElement().toString();
					String[] value = req.getParameterValues(name);
					for (int i = 0; i < value.length; i++) {
						str = str + value[i];
					}
				}
				if (sqlValidate(str)) {
				//return to error page
				res.sendRedirect(req.getContextPath() + "/500.jsp");
				} else {
					chain.doFilter(req, res);
				}
	}

	// validation
	protected static boolean sqlValidate(String str) {
		// uniformly convert to lowercase
		str = str.toLowerCase();
		System.out.println("Anti-sql injection filter: "+str);
		// Filtered sql keywords can be added manually
		String badStr = "'|and|exec|execute|insert|select|delete|update|count|drop|*|%|chr|mid|master|truncate|"
				+ "char|declare|sitename|net user|xp_cmdshell|;|or|+|,|like'|and|exec|execute|insert|create|drop|"
				+ "table|from|grant|use|group_concat|column_name|"
				+ "information_schema.columns|table_schema|union|where|select|delete|update|order|by|count|*|"
				+ "chr|mid|master|truncate|char|declare|or|;|-|--|+|,|like|//|/|%|#|=|(|scrip";
		String[] badStrs = badStr.split("\\|");
		for (int i = 0; i < badStrs.length; i++) {
			if (str.indexOf(badStrs[i]) >= 0) {
				System.out.println(str+" ==== violates sql injection rules==""+badStrs[i]);
				return true;
			}
		}
		return false;
	}
	public void destroy() {
		// throw new UnsupportedOperationException("Not supported yet.");
	}
}


(filters that do not cache pages - there are references)

package com.patronli.servlet;


import java.io.IOException;
import java.util.Enumeration;

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;

import com.fuiou.fwp.util.ConfigReader;

       
       
/**   
* Filter used to make Browser not cache pages   
*/       
public class patronliFilter implements Filter {         
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException,ServletException  {        
        ((HttpServletResponse) response).setHeader("Cache-Control","no-cache");        
        ((HttpServletResponse) response).setHeader("Pragma","no-cache");        
        ((HttpServletResponse) response).setDateHeader ("Expires", -1);        
        filterChain.doFilter(request, response);        
    }        
           
    public void destroy() {        
    }        
           
    public void init(FilterConfig arg0) throws ServletException {        
    }        
}  

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326611958&siteId=291194637