中文乱码问题解决,过滤器配置,get post提交乱码,filter,struts乱码,jsp乱码

过滤器配置

 

<filter>
 <filter-name>encoding</filter-name>
 <filter-class>
  filter.FilterEncoding
 </filter-class>
 <init-param>
  <param-name>encoding</param-name>
  <param-value>gbk</param-value>
 </init-param>
</filter>

 

 

package filter;

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 FilterEncoding implements Filter 
{ 
 protected String encoding;          // 接收字符编码
 protected boolean ignore;            // 是否忽略大小写
 protected FilterConfig filterConfig; // 初始化配置

 public void init(FilterConfig filterConfig) throws ServletException 
 {
  // 从web.xml文件中读取encoding的值
  encoding = filterConfig.getInitParameter("encoding"); 
  // 从web.xml文件中读取ignore的值
  String value = filterConfig.getInitParameter("ignore"); 
  // 以下三种情况均为忽略大小写
  if(value == null) 
  { 
   ignore = true; 
  }
  else if(value.equalsIgnoreCase("yes")) 
  { 
   ignore = true; 
  } 
  else if(value.equalsIgnoreCase("true")) 
  { 
   ignore = true; 
  } 
 } 
 // doFilter方法
 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException 
 {
  if(ignore || request.getCharacterEncoding() == null) 
  {
   // 如果为空先从web.xml中得到
   String encoding = selectEncoding(request); 
   if(encoding != null) 
   {
    // 设置字符集编码
    request.setCharacterEncoding(encoding); 
   }
  }
  // 继续执行
  chain.doFilter(request, response); 
 } 
 // 得到字符编码
 private String selectEncoding(ServletRequest request) 
 { 
  return encoding; 
 } 
 public void destroy() 
 { 
  
 } 
}

 

如果是url的get提交参数带中文的
可以改下面这个文件,加入一个URIEncoding="GBK"
X:\Tomcat 5.5\conf\Server.xml 
 

<Connector 
        port="8080" 
        redirectPort="8443" 
        minSpareThreads="25" 
        connectionTimeout="30" 
        maxThreads="150" 
        maxSpareThreads="75" 
URIEncoding="GBK"> 

 

jsp头文件

<%@ page contentType="text/html;charset=gbk"%>   //此处的charset的值要和web.xml里的  <param-value></param-value>值一样

 

单个类的乱码可以这样来解决:tempStr = new String(str.getBytes("iso-8859-1"),"gb2312");

 

黑色头发  http://heisetoufa.iteye.com

如果发现本文有误,欢迎批评指正

你可能感兴趣的:(jsp,Web,xml,servlet,struts)