本文参考网络文章整理而成。
本文所有编码格式均为UTF-8
第一步:编写过滤器类。具体如下:
package com.filter;
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.HttpServletResponse;
public class txtFilter implements Filter {
/*
* (non-Javadoc)
*
* @see javax.servlet.Filter#destroy()
*/
public void destroy() {
// TODO Auto-generated method stub
}
/*
* (non-Javadoc)
*
* @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
* javax.servlet.ServletResponse, javax.servlet.FilterChain)
*/
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
// TODO Auto-generated method stub
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
req.setCharacterEncoding("UTF-8");
res.setCharacterEncoding("UTF-8");
chain.doFilter(req, res);
}
/*
* (non-Javadoc)
*
* @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
*/
public void init(FilterConfig filterConfig) throws ServletException {
// TODO Auto-generated method stub
}
}
第二步,配置web.xml,在其中加入如下配置代码段。具体如下:
<!-- 编码过滤 避免出现乱码 -->
<filter>
<filter-name>txtFilter</filter-name>
<filter-class>
com.filter.txtFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>txtFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>