过滤器类是对请求资源或则响应资源执行过滤任务,过滤器类通过doFilter方法执行过滤任务。过滤器访问FilterConfig对象,获得初始化参数。FilterConfig对象是一个servletContext的引用,用它可以导入过滤任务需要的初始化参数。
代码:
EncodingFilter.java
package com.test;
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;
public class EncodingFilter implements Filter {
String encoding = null;
FilterConfig filterConfig = null;
//初始化方法
public void init(FilterConfig filterConfig) throws ServletException {
// TODO Auto-generated method stub
this.filterConfig = filterConfig;
this.encoding = filterConfig.getInitParameter("encoding");
}
//过滤处理方法
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
// TODO Auto-generated method stub
if (encoding!=null){
//对请求进行编码设置
request.setCharacterEncoding(encoding);
}
//将处理权转交给下一个处理器
chain.doFilter(request,response);
}
//销毁方法
public void destroy() {
// TODO Auto-generated method stub
this.encoding = null;
this.filterConfig = null;
}
}
index.htm
<html>
<head>
<title>编码过滤器测试</title>
<meta http-equiv="content-type" content="text/html; charset=gb2312">
</head>
<body>
<form name="form1" action="process.jsp" method="POST">
请输入姓名:<input name="name" type="text">
<input name="submit" value="提交" type="submit">
</form>
</body>
</html>
process.jsp
<%@ page language="java" import="java.util.*" pageEncoding="gb2312"%>
<html>
<head>
<title>编码过滤器测试</title>
</head>
<body>
<%=request.getParameter("name")%>,你好!<br>
</body>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>com.test.EncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>gb2312</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>