tomcat采用UTF-8编码

时间:2022-02-26 11:11:11

总算找到个看起来比较靠谱的说明:http://wiki.apache.org/tomcat/FAQ/CharacterEncoding

另外还参考了:http://www.iteye.com/topic/179279

 

1.页面乱码,要在页面前端加上

JSP:

<%@page language="java" pageEncoding="UTF-8"%>

 

HTML:

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

 

2.页面form传入参数乱码(主要是由于tomcat默认采用ISO-8859-1编码)

可以采用以下代码将获得参数test:

String theParam = new String(request.getParameter("someParam").getBytes("ISO-8859-1"), "UTF-8");

 

由于以上方法需要在取每个参数的时候都进行类似操作,整体修改的方法是写一个过滤器:

package filters;import java.io.*;import javax.servlet.*;/* * 字符编码设置过滤器 */public class SetCharacterEncodingFilter implements Filter {@Overridepublic void destroy(){}@Overridepublic void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException{request.setCharacterEncoding("utf-8");//将编码统一设置为UTF-8chain.doFilter(request, response);}@Overridepublic void init(FilterConfig config) throws ServletException{}}

同时在web.xml中配置此过滤器:

<filter>    <filter-name>SetCharacterEncoding</filter-name>    <filter-class>filters.SetCharacterEncodingFilter</filter-class></filter><filter-mapping>    <filter-name>SetCharacterEncoding</filter-name>    <url-pattern>/*</url-pattern></filter-mapping>

过滤器方式仅对POST方法有效,要使FORM的GET方法也可以正确读取参数,要在TOMCAT的server.xml中修改Connector元素,为其加上URI-ENCODING="UTF-8"属性

    <Connector port="8080" protocol="HTTP/1.1"                connectionTimeout="20000"                redirectPort="443"  URIEncoding="UTF-8"/>