日期:2014-05-18  浏览次数:20706 次

在线求救:中文乱码问题
用post提交时在java中得到的是乱码,action默认提交时不是乱码,我用的都是utf-8,在tomcat的server.xml的Connector中设置了   URIEncording= "UTF-8 "还是不行,我用的是netbeans5.5,tomcat是netbeans捆绑的。
各位大侠帮帮忙啊

------解决方案--------------------
Tomcat中以POST方式提交表单出现的乱码问题
----过滤器的使用
方法一
A.EncodingFilter.java
package 包名.util;

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 EncodingFilter implements Filter {

public void init(FilterConfig arg0) throws ServletException {
// TODO 自动生成方法存根

}

public void doFilter(ServletRequest arg0, ServletResponse arg1,
FilterChain arg2) throws IOException, ServletException {
// TODO 自动生成方法存根
arg0.setCharacterEncoding( "UTF-8 ");
arg2.doFilter(arg0,arg1);
}

public void destroy() {
// TODO 自动生成方法存根

}

}
B.配置项目中的/WEB-INF/web.xml文件,在文件中添加以下代码即可
<filter>
<filter-name> encodingFilter </filter-name>
<filter-class> 包名.util.EncodingFilter </filter-class>
</filter>
<filter-mapping>
<filter-name> encodingFilter </filter-name>
<url-pattern> /* </url-pattern>
</filter-mapping>

方法二
A.CharacterFilter.java
/**
* 中文编码处理
*/
package 包名.util;

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;

/**
* @author cankongyun
*
*/
public class CharacterFilter implements Filter {

protected String encoding=null;
protected FilterConfig filterConfig=null;
protected boolean ignore=true;


/* (非 Javadoc)
* @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
* 初始化方法,通过配置的参数设置标识变量
*/
public void init(FilterConfig _filterConfig) throws ServletException {
// TODO 自动生成方法存根
this.filterConfig=_filterConfig;
this.encoding=_filterConfig.getInitParameter( "encoding ");
String value=filterConfig.getInitParameter( "ignore ");
if(value==null)
this.ignore=false;
else if(value.equalsIgnoreCase( "false "))
this.ignore=true;
else if(value.equalsIgnoreCase( "no "))
this.ignore=true;
else
this.ignore=false;

}


/**
* 得到配置文件的编码类型
* @param request
* @return
*/
protected String selectEncoding(ServletRequest _request){
return this.encoding;
}


/* (非 Javadoc)
* @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
* Filter的主体操作
*/
public void doFilter(ServletRequest _request, ServletResponse _response,
FilterChain _filterChain) throws IOExcepti