在做WEB 开发是通常会遇到页面乱码问题!只要写一个过滤器乱码轻松搞定!
public class SetCharacterEncodingFilter implements Filter {
private FilterConfig config;
public static final String CHARSET_DEFAULT = "UTF-8";
/* (non-Javadoc)
* @see javax.servlet.Filter#destroy()
*/
@Override
public void destroy() {
}
/* (non-Javadoc)
* @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
*/
@Override
public void doFilter(ServletRequest arg0, ServletResponse arg1,
FilterChain arg2) throws IOException, ServletException {
String enable = config.getInitParameter("enable");
String charset = config.getInitParameter("charset");
if(enable != null && "true".equals(enable)){
if(charset != null && !"".equals(charset)){
arg0.setCharacterEncoding(charset);
}else{
arg0.setCharacterEncoding(CHARSET_DEFAULT);
}
}
arg2.doFilter(arg0, arg1);
}
/* (non-Javadoc)
* @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
*/
@Override
public void init(FilterConfig arg0) throws ServletException {
config = arg0;
}
在web.xml 中的配置
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>com.liuc.web.common.SetCharacterEncodingFilter</filter-class>
<init-param>
<param-name>enable</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>charset</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>