当前位置: 代码迷 >> Java Web开发 >> java 中文(乱码)有关问题!
  详细解决方案

java 中文(乱码)有关问题!

热度:47   发布时间:2016-04-17 15:24:50.0
java 中文(乱码)问题!!
我把数据填充到struts的一个FormBean   中,然后用hibernate   的save方法把数据写到数据库中,产生了乱码,然后我把FormBean   的每个值取出来有   new   String(string.getBytes( "ISO-8859-1 "), "gb2312 ")转换,结果产生异常,报错为不认识iso-8859-1这种编码方式,请问各位大侠有什么好的解决办法???

------解决方案--------------------
使用过滤器(Filter)的解决方案吧,参照struts提供的example。
------解决方案--------------------
web.xml
加入
<filter>
<filter-name> Set Character Encoding </filter-name>
<filter-class> com.test.filters.SetCharacterEncodingFilter </filter-class>
<init-param>
<param-name> encoding </param-name>
<param-value> UTF-8 </param-value>
</init-param>
</filter>
----------
SetCharacterEncodingFilter.java
package com.test.filters;

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;
//import javax.servlet.UnavailableException;

public class SetCharacterEncodingFilter implements Filter {
protected String encoding = null;
protected FilterConfig filterConfig = null;
protected boolean ignore = true;
public void destroy() {

this.encoding = null;

this.filterConfig = null;

}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException,
ServletException {
// Conditionally select and set the character encoding to be used

if (ignore || (request.getCharacterEncoding() == null)) {

String encoding = selectEncoding(request);

if (encoding != null) {

request.setCharacterEncoding(encoding);

}

}

// Pass control on to the next filter

chain.doFilter(request, response);
}
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
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.ignore = true;
} else {
this.ignore = false;
}

}

protected String selectEncoding(ServletRequest request) {

return (this.encoding);

}

}

------解决方案--------------------
最好的解决方案是在web.xml中写个过滤器,如:zhaochunhui(没有烟抽的日子)
你用的new String(string.getBytes( "ISO-8859-1 "), "gb2312 ")转换,应该放在Action里就可以了....
------解决方案--------------------
e...解决了还不结帖=。=
  相关解决方案