一个简单的JAVA字符集过滤器实现
程序员文章站
2024-02-20 21:38:16
复制代码 代码如下:package dw05prj.util.filter; import javax.servlet.filter; import javax.servl...
复制代码 代码如下:
package dw05prj.util.filter;
import javax.servlet.filter;
import javax.servlet.filterconfig;
import javax.servlet.servletexception;
import javax.servlet.servletrequest;
import javax.servlet.servletresponse;
import javax.servlet.filterchain;
import java.io.ioexception;
/*页面字符集过滤流*/
/*
在web.xml中配制的例子
<filter>
<filter-name>charencodingfilter</filter-name>
<filter-class>dw05prj.util.filter.charencodingfilter</filter-class>
<init-param>
<param-name>charset</param-name>
<param-value>gbk</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>charencodingfilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
*/
public class charencodingfilter implements filter {
private string charset ;
public void init(filterconfig parm1) throws servletexception {
charset = parm1.getinitparameter("charset") ;
if (charset == null && charset.length() < 1)
{
charset = "utf-8" ;
}
system.out.println ("charencodingfilter--字符集: " + this.getcharset()) ;
}
public void dofilter(servletrequest parm1, servletresponse parm2,
filterchain parm3) throws ioexception, servletexception {
// 设定字符集
parm1.setcharacterencoding(this.getcharset());
parm3.dofilter(parm1, parm2);
//页面中每个向服务器的请求都被过滤 -- 如 图片,js,html/jsp等等
//system.out.println ("---charencodingfilter: " + this.getcharset()) ;
}
public void destroy() {
// todo: add your code here
this.setcharset(null) ;
}
public void setcharset(string charset) {
this.charset = charset;
}
public string getcharset() {
return (this.charset);
}
}