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

再线等,网上找了2天,仍然没解决的乱码问题,快疯了
我使用的是struts
我在tomcat的server.xml中加了URIEncoding= "UTF-8 "
在web.xml中写了过滤器,过滤器中加了
request.setCharacterEncoding( "UTF-8 ");
都没能解决。

在FormAction.java中的set方法中直接出来乱码
public   void   setGo_timehm(String   go_timehm)   {
this.go_timehm   =   go_timehm
}
也就是说,从页面过来的值已经是乱码了。
于是我添加了这个方法来转码
private   String   toGBK(String   str)   throws   java.io.UnsupportedEncodingException
{
return   new   String(str.getBytes( "ISO-8859-1 "), "GBK ");
}

但是在set方法中引用的时候却报错
public   void   setGo_timehm(String   go_timehm)   {
this.go_timehm   =   new   String( "123 ".getBytes( "ISO-8859-1 "), "GBK ");
}
unhandled   exception   type   unsupportedEncodingException这个错误
小弟百思不得其解,现在我快疯了,大哥们救救我把

------解决方案--------------------
大哥,方法throws异常了,下面得catch处理下把,错误报的很清楚
public void setGo_timehm(String go_timehm) throws UnsupportedEncodingException{
this.go_timehm = this.toGBK(go_timehm);
}
------解决方案--------------------
sturts.cfg.xml下添加
<controller processorClass= "common.Trans " />
添加类
package common;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.RequestProcessor;

public class Trans extends RequestProcessor{
public Trans(){}

protected boolean processPreprocess( HttpServletRequest request,
HttpServletResponse response ){

try{
request.setCharacterEncoding( "UTF-8 ");

}
catch(Exception ex){
ex.printStackTrace();

}
return true;
}
}
试下
------解决方案--------------------
启动NetBeans
打开原来的SimpleWebSite_web项目,将所依赖的SimpleWebSite_dao与SimpleWebSite_service两个项目同时打开
右键点SimpleWebSite_web项目的Source Packages
New
File/Folder...
选“Web”,File Type为Filter
Next

Class Name:EncodingFilter
Package:org.liupopo.simplewebsite.web.filter
Next
要选上“Add information to deployment descriptor (web)”, 这样NetBeans会自动在web.xml中配置好相应的Filter设置
Next
在这里我们可以设置Filter要用到参数,因为我想可以通过修改web.xml中的参数改变网站的编码,所以“New”,name为“Encode”value为“UTF-8”
Finish

看看NetBeans为我们做了什么
1.在web.xml增加了以下Filter的内容:
<filter>
<filter-name> EncodingFilter </filter-name>
<filter-class> org.liupopo.simplewebsite.web.filter.EncodingFilter </filter-class>
<init-param>
<param-name> Encode </param-name>
<param-value> UTF-8 </param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name> EncodingFilter </filter-name>
<url-pattern> /* </url-pattern>
</filter-mapping>
省了我们自己手动配置web.xml了。而且NetBeans对web.xml的编辑提供了可视化的操作界面,对web.xml中的各项设置进行了分类,非常方便我们的修改。
2.为我们生成了EncodingFilter这个类,刚打开的时候吓我一跳,一个Filter怎么这么多代码?原来是NetBeans为我们把一些常用的方法已经写好,我们只要在相应的位置加上我们的做具体事情的代码就可以了。NetBeans为我们加的doBeforeProcessing()和doAfterProcessing()两个方法是想我们在Filter之前和之后做些什么,生成的代码里已经做了日志处理,并且还有一大段被注释起来的示例代码,但