乱码的解决

乱码问题的由来:
    1.浏览器发送以本机平台字符编码的中文数据(GB2312).例如中文字符 "中"->(0xd6d0);
    2.如果在web容器中接受数据时没有指定编码,web容器使用默认编码ISO-8859-1得到数据,由于0xd6d0在ISO-8859-1中找不到对应字符,所以显示乱码.
    
    以post在接受数据之前使用:
    
    request.setCharacterEncoding("GB2312");   
    
    让程序以GB2312编码解析数据
    如果是以get方式通过请求参数获取的数据,此方法就无效了,必须在得到参数后进行转码

    String name =request.getParameter("name"); 
    //对参数转码
    user.setName(new String(name.getBytes("ISO-8859-1"),"GB2312"));

    字符内容输出到浏览器时也应该指定编码方式
    
    response.setContentType("text/html; charset="+"GB2312");

    在web程序中如果调用response.sendRedirect()方法重定向到中文页面时,需要以如下方式调用
    response.sendRedirect(

实例:通过滤器解决中文问题
    1.编写过滤器
[java] view plain copy
public class UnifiedCoding implements Filter {  
    private String encoding=null;  
    private FilterConfig filterConfig = null;  
    //是否忽略编码  
    private boolean ignore=true;  
    @Override  
    public void destroy() {  
        this.encoding = null;  
        this.ignore = true;  
    }  
    public void doFilter(ServletRequest req, ServletResponse resp,  
            FilterChain chain) throws IOException, ServletException {  
        if(ignore || req.getCharacterEncoding()==null){  
            String encoding = this.encoding;  
            if(encoding!=null){  
                req.setCharacterEncoding(encoding);  
            }  
        }  
        resp.setContentType("text/html;charset="+encoding);  
        chain.doFilter(req, resp);  
    }  
    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{  
            this.ignore = false;  
        }     
    }  
}  

    2.编写测试页面
[java] view plain copy

0

阅读 评论 收藏 转载 喜欢 打印 举报
已投稿到:
加载中,请稍候......
  • 评论加载中,请稍候...
发评论

登录名:密码:找回密码 注册 记住登录状态

昵   称:

评论并转载此博文sg_trans.gif

发评论

以上网友发言只代表其个人观点,不代表新浪网的观点或立场。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值