2007-01-30
解决中文乱码问题
关键字: JSP乱码出现的原因
java内核是unicode的。但Java总是根据操作系统的默认编码字符集来决定字符串的初始编码,而且Java系统的输入和输出的都是采取操作系统的默认编码,而数据库、文件、网络传输中的字节流……采用的编码更是各不相同。所以不可避免的就会出现烦人的乱码问题了。
解决办法
1、GB2312、GBK、Unicode(UTF8)?
从字符集的大小比较 GB2312 < GBK < UTF8,很显然,如果我们采用UTF8作为系统编码的话,是不会有错的。而且如果你要考虑国际化的话,UTF8似乎是你唯一的选择
2、开发和编译代码时指定字符集为GB2312
JBuilder和Eclipse都可以在项目属性中设置。
3、使用过滤器
java 代码
- public class EncodingFilter implements Filter{
- protected FilterConfig config = null;
- protected String encoding = null;
- public void init(FilterConfig filterConfig) {
- this.encoding = filterConfig.getInitParameter("encoding");
- this.filterConfig = filterConfig;
- }
- public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
- throws java.io.IOException, javax.servlet.ServletException{
- if (req.getCharacterEncoding() == null || !req.getCharacterEncoding().equals(encoding)){
- req.setCharacterEncoding(encoding);
- }
- chain.doFilter(req, res);
- }
- public void destroy() {
- this.encoding = null;
- this.filterConfig = null;
- }
- }
4.web.xml
在web.xml文件中需要描述一下过滤器:
xml 代码
- <filter>
- <filter-name>Set Character Encoding</filter-name>
- <filter-class>com.capinfo.filter.SetCharacterEncodingFilter</filter-class>
- <init-param>
- <param-name>encoding</param-name>
- <param-value>GB2312</param-value>
- </init-param>
- </filter>
- <filter-mapping>
- <filter-name>Set Character Encoding</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
5.在JSP页面中
注意:如果在url中传递带有中文的的数据
如:http://localhost:8088/Struts-demo/upload.do?filename=如何规划职业发展道路.pdf
那么在后台需要这么写才能得到不是乱码的"文件名".
String fileName = new String(request.getParameter("filename").getBytes("ISO-8859-1"), "GB2312");
response.addHeader("Content-Disposition", "attachment; filename=\"" + new String(fileName.getBytes("GB2312"), "ISO-8859-1") + "\"");
来取得url传递过来的fileName中文参数.
发表评论
- 浏览: 23391 次
- 性别:

- 来自: 辽宁

- 详细资料
搜索本博客
我的相册
2630137
共 2 张
共 2 张
最近加入圈子
最新评论
-
oracle数据还原与备份
谢谢楼主:)
-- by 凝血神抓 -
solaris9 网络配置
应该还有一个文件需要配置的,或者说需要配置一下IP才可以!你试下吧!
-- by dragonlin -
关键字: CCTV5 天下足球 ...
是的,就是这个理由.
-- by xuehongliang -
关键字: CCTV5 天下足球 ...
在电视上玩中国就没有正式发售的XBOX360..玩的游戏-实况既然还是没有汉化完 ...
-- by yanyanlong -
关键字: CCTV5 天下足球 ...
理由泥
-- by ddandyy






评论排行榜