1、首先要检查tomcat-->conf-->server.xml中字符集要改为一致,比如:UTF-8
2、在servlet的doGet或service中要设置
request.setCharacterEncoding("UTF-8")
3、web.xml中设置servlet的初始化参数
<servlet>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</servlet>
4、jsp页面需要注意的是
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" %>
按照以上四点检查完毕后如果还是不行,就要写过滤器了:
package jspServletConnnectionCommons;
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;
public class CharacterEncodingFilter implements Filter{
private String encode;
//初始化
@Override
public void init(FilterConfig filterConfig) throws ServletException {
encode = filterConfig.getInitParameter("encode");
}
//执行过滤
@Override
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain filterChain) throws IOException, ServletException {
req.setCharacterEncoding(encode);
filterChain.doFilter(req, res);
}
//销毁
@Override
public void destroy() {
encode = null;
}
}
再在web.xml中配置filter如下:
<filter>
<filter-name>characterEncodingFilter</filter-name>
<filter-class>org.itfuture.examples.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encode</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>