完美的中文乱码解决方案

1.jsp与页面参数之间的乱码
  页面参数的编码类型和系统默认的编码类型不一样:request.getCharacterEncoding("utf-8");
 jsp将变量输出到页面出现的乱码:response.setContentType("text/html;charset=utf-8")
 
 如果每个jsp页面都设置又太麻烦了 ,使用过滤器在web.xml中配置
 <filter>
<filter-name>filter</filter-name><!-- 过滤器的名称  可以随便命名 -->
<filter-class>filter.CodeFilter</filter-class><!-- 设置过滤器的类名(filter包下的CodeFilter类) -->
</filter>


<filter-mapping>
<filter-name>filter</filter-name><!-- 过滤器的名称与filter节点中的名称一致 -->
<url-pattern>/*</url-pattern><!-- 设置过滤器url为/* -->
</filter-mapping>

  filter包下的CodeFilter类为
  public class CodeFilter implements Filter {
 //销毁方法
public void destroy() {
// TODO Auto-generated method stub

}


public void doFilter(ServletRequest arg0, ServletResponse arg1,
FilterChain arg2) throws IOException, ServletException {
//把ServletRequest强转为HttpServletRequest
HttpServletRequest request=(HttpServletRequest)arg0;
HttpServletResponse response=(HttpServletResponse)arg1;
request.setCharacterEncoding("utf-8");//设置request的编码格式
response.setCharacterEncoding("utf-8");//设置response的编码格式
arg2.doFilter(request, response);

}
//初始方法
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub

}
}
以上两个步骤  就是配置过滤器的步骤

2.jsp与数据库之间的乱码
在驱动的url中指定 如mySql:jdbc:mysql://localhost:3306/WEBCLDB?useUnicode=true&characterEncoding=GBK


3.java与文件/流之间的乱码
读写字符文件建议使用基于字符的FileWriter和FileReader,省去字节和字符的转换
但是这两个类的构造函数默认使用系统的编码格式,如果文件内容和系统编码方式不同 就会出现乱码
这时候建议使用FileWriter和FileReader的父类:OutputStreamWriter/InputStreamReader,他们是也是基于字符的
但是可以在构造函数中指定编码类型:InputStreamReader(InputStream in,Charset sc) 和OutputStreamWriter(OutputStream out,Charset cs)
  
 4.用form表单post提交出现乱码:设置接收编码格式   request.getCharacterEncoding("utf-8");
 
  用form表单get提交出现乱码:将get采用url提交的iso8859-1编码转化为utf-8 
  String str=new String(request.getParameter("something").getBytes("iso-8859-1"),"utf-8");
  或者,修改Tomcat对get方式的汉字编码方式。修改Tomcat的配置文件 server.xml 找到Connector节点  改变URIEncoding 属性为GBK
  <Connector port="8080" maxThreads="150" minSpareThreads="25" maxSpareTreads="75"
  connectionTimeout="2000"  useBodyEncodingForURI="true" URIEncoding="gbk"/>
  以上总结各种乱码解决方案,希望对大家有所帮助
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值