1.jsp字符编码设定为“UTF-8”
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
2.准备资源文件,进行编码转换时用了一个Eclipse的插件Jinto,很方便。
3.写了一个SetCharacterEncodingFilter,调用HttpServletRequest的setCharacterEncoding("UTF-8")方法,能够把用求的请求数据也封装为UTF-8.这样,WEB应用中的输入和输出都采用同一种编码,就无需在程序中进行编码转换。这一功能也可在Servlet过滤器来完成,国为它可以预处理所有HTTP请求,这样能避免在每个组件中设置请求数据编码。
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.UnavailableException;
public class SetCharacterEncodingFilter implements Filter {
public void init(FilterConfig arg0) throws ServletException {
// TODO 自动生成方法存根
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
// TODO 自动生成方法存根
request.setCharacterEncoding("UTF-8");
chain.doFilter(request,response);
}
public void destroy() {
// TODO 自动生成方法存根
}
}
web.xm中配置SetCharacterEncodingFilter过滤器,这个过滤器处理所有的URL
<filter>
<filter-name>Set Character Encoding</filter-name>
<filter-class>SetCharacterEncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>Set Character Encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
OK!