创建类CharacterFilter
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class CharacterFilter implements Filter{
String encoding = null;
@Override
public void destroy() {
encoding = null;
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
if (encoding != null) {
request.setCharacterEncoding(encoding);
response.setContentType("text/html;charset=" + encoding);
}
chain.doFilter(request, response);
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
encoding = filterConfig.getInitParameter("encoding");
}
}
在web.xml的web-app标签添加如下代码
<filter>
<filter-name>CharacterFilter</filter-name>
<filter-class>util.CharacterFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>