首先:pageEncoding,contentType,request.setCharacterEncoding();区别。
1.pageEncoding:表示为jsp在编译成java文件时候应该采取的何种编码方式。如果为gbk则会根据gbk的编码为java文件
2.contentType:表示为输出浏览器的html的编码方式。也会为表单提交时要采用的编码方式。如果为utf-8则会用utf-8的编码方式传递表单参数
3. request.setCharacterEncoding();:表示设置请求的参数的编码方式(只会对post方式有效,get方式无效)。
get方式:
如用get方式提交表单,只需要在Tomcat的server.xml文件中添加一句"URLEcoding="UTF-8""即可!
因为它会将请求的url进行utf-8的编码。
post方式:
如果为post方式提交表单,每个jsp的contentType=“text/html;charset=utf-8”必须这样设置
还有就是处理请求的jsp中必须request.setCharacterEncoding("utf-8");(要与contentType中的设置的一致)。
如果程序里则必须String str = new String(name.getBytes("ISO-8859-1"),"utf-8");进行转码。
过滤器方法:
package com.accphr.util; import java.io.IOException; import java.util.Iterator; import java.util.Map; 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; /** * * 字符集过滤器 * */ public class CharacterEncodingFilter implements Filter { /* 设置的字符集 */ private String encoding = "UTF-8"; public void destroy() { } @SuppressWarnings("unchecked") public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // 处理服务器到客户端 response.setContentType("text/html;charset=" + this.encoding); // 处理客户端到服务器 HttpServletRequest req = (HttpServletRequest) request; String s = req.getMethod();// 获得表单提交方式 if (s.equalsIgnoreCase("post")) { req.setCharacterEncoding(this.encoding); } else if (s.equalsIgnoreCase("get")) { Map<String, String[]> map = (Map<String, String[]>) req.getParameterMap(); Iterator<String[]> it = map.values().iterator(); while (it.hasNext()) { String[] paramValues = it.next(); for(int i = 0; i < paramValues.length; i++) { byte[] b = paramValues[i].getBytes("ISO-8859-1"); paramValues[i] = new String(b, this.encoding); } } } chain.doFilter(request, response); } public void init(FilterConfig config) throws ServletException { // String encoding = config.getInitParameter("encoding"); // if (StringUtils.isNotBlank(encoding)) { // this.encoding = StringUtils.trimToBlank(encoding); } } }