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

java中UTF8转GBK
我们现在开发的web系统是使用struts2+spring+hibernate,我们想使用struts2中带的ajax控件,但是这些控件提交到后台的数据都是UTF-8编码的,比如:我在前台的文本框中输入 你好 ,在后台的action中打印出的是 你好
试了很多的编码方式,都没有转化了
System.out.println("1 - zxm = "+this.tabForm.getZxm());
System.out.println("2 - zxm = "+new String(this.tabForm.getZxm().getBytes("ISO-8859-1"),"UTF-8"));
System.out.println("3 - zxm = "+new String(this.tabForm.getZxm().getBytes("GBK"),"UTF-8"));
System.out.println("4 - zxm = "+new String(this.tabForm.getZxm().getBytes("UTF-8"),"ISO-8859-1"));
System.out.println("5 - zxm = "+new String(this.tabForm.getZxm().getBytes("UTF-8"),"GBK"));
System.out.println("6 - zxm = "+new String(this.tabForm.getZxm().getBytes("UTF-16BE"),"GBK"));
String gbkString = IOUtils.toString(IOUtils.toInputStream(this.tabForm.getZxm(), "UTF-8"));
System.out.println("gbkString = "+gbkString);
String urlString = URLDecoder.decode(URLEncoder.encode(this.tabForm.getZxm(),"GBK"),"GBK");
System.out.println("urlString = "+urlString);
上面的转码有些明显是错误的,望大家不要见笑。
后台打印结果
1 - zxm = 你好
2 - zxm = 你好
3 - zxm = 你好
4 - zxm = 你好
5 - zxm = 你好
6 - zxm = 你好
gbkString = 你好
urlString = 你好

难为高人帮着解决一下,用什么办法把UTF-8的转成GBK 的哈?!
谢谢!!!



------解决方案--------------------
用DB2312试试!!
new String(rinm.getBytes("ISO8859_1"),"GBK");
------解决方案--------------------
将你前台页面编码也改成UTF-8
------解决方案--------------------
用这个方法试一试
定义一个类
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 SetCharacterEncodingFilter implements Filter {

/*
* (非 Javadoc)

* @see javax.servlet.Filter#destroy()
*/
public void destroy() {

this.encoding = null;
this.filterConfig = null;

}

public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
// 选择使用的字符编码
if (ignore || (request.getCharacterEncoding() == null)) {
String encoding = selectEncoding(request);
if (encoding != null) {
request.setCharacterEncoding(encoding);

}
// 将控制权交给下一个Filter
chain.doFilter(request, response);
}

}

// 将这个filter放置在服务中
/*
* (非 Javadoc)

* @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
*/
public void init(FilterConfig filterConfig) throws ServletException {
this.encoding = filterConfig.getInitParameter("encoding");
String value = filterConfig.getInitParameter("ignore");
if (value == null)
this.ignore = true;
else if (value.equalsIgnoreCase("true"))
this.ignore = true;
else if (value.equalsIgnoreCase("yes"))
this