黑马程序员技术交流社区
标题:
乱码过滤器! 你懂的 源码!Filter(过滤器)
[打印本页]
作者:
l396262632
时间:
2013-8-13 12:00
标题:
乱码过滤器! 你懂的 源码!Filter(过滤器)
选择菜单 File > New > Class,来创建一个名为TomcatFormFilter 的类,包名为
filters。然后把类的代码修改为如下所示:
package filters;
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.HttpServletRequestWrapper;
public class TomcatFormFilter implements Filter {
/**
* Request.java
* 对 HttpServletRequestWrapper 进行扩充, 不影响原来的功能并能提供所
有的HttpServletRequest
* 接口中的功能. 它可以统一的对 Tomcat 默认设置下的中文问题进行解决而只
需要用新的Request 对象替换页面中的
* request 对象即可.
*/
class Request extends HttpServletRequestWrapper
{
public Request(HttpServletRequest request) {
super(request);
}
/**
* 转换由表单读取的数据的内码.
* 从 ISO 字符转到 GBK.
*/
public String toChi(String input) {
try {
byte[] bytes = input.getBytes("ISO8859-1");
return new String(bytes, "GBK");
}
catch (Exception ex) {
}
return null;
}
/**
* Return the HttpServletRequest holded by this object.
*/
private HttpServletRequest getHttpServletRequest()
{
return (HttpServletRequest)super.getRequest();
}
/**
* 读取参数 -- 修正了中文问题.
*/
public String getParameter(String name)
{
return
toChi(getHttpServletRequest().getParameter(name));
}
/**
* 读取参数列表- 修正了中文问题.
*/
public String[] getParameterValues(String name)
{
String values[] =
getHttpServletRequest().getParameterValues(name);
if (values != null) {
for (int i = 0; i < values.length; i++) {
values[i] = toChi(values[i]);
}
}
return values;
}
}
public void destroy() {
}
public void doFilter(ServletRequest request, ServletResponse
response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpreq = (HttpServletRequest)request;
if(httpreq.getMethod().equals("POST")) {
request.setCharacterEncoding("GBK");
} else {
request = new Request(httpreq);
}
chain.doFilter(request, response);
}
public void init(FilterConfig filterConfig) throws
ServletException {
}
}
然后修改 web.xml 加入Servlet 定义,修改后的代码清单如下所示:
<filter>
<filter-name>TomcatFormFilter</filter-name>
<filter-class>filters.TomcatFormFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>TomcatFormFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2