Servlet编码:
public class SetcharEncodingFilter extends HttpServlet implements Filter {
protected String encoding=null;//要定制的编码,在web.xml中配置
protected FilterConfig fillterConfig=null;
public void destory(){//销毁编码设置
this.encoding=null;
this.fillterConfig=null;
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
if(request.getCharacterEncoding()==null){
String encoding=getEncoding();//得到指定的编码名字
if(encoding!=null){
request.setCharacterEncoding(encoding);
//设置request的编码
}
chain.doFilter(request, response);//有机会执行下一个Filter
}
}
private String getEncoding() {
return (this.encoding);//得到指定的编码
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
this.fillterConfig=filterConfig;
this.encoding=fillterConfig.getInitParameter(encoding);
//得到web.xml中配置的编码
}
}
web.xml配置
<filter>
<filter-name>SetcharEncodingFilter</filter-name><!--过滤器名 -->
<filter-class>Filter.SetcharEncodingFilter</filter-class><!--过滤器类名 -->
<init-param>
<param-name>encoding</param-name><!-- 初始化变量名 -->
<param-value>UTF-8</param-value><!-- 初始化变量值-->
</init-param>
</filter>
<filter-mapping>
<filter-name>SetcharEncodingFilter</filter-name><!--过滤器名 -->
<url-pattern>/*</url-pattern><!-- 指定所有页面都应用该过滤器 -->
</filter-mapping>