乱码问题的由来:
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
加载中,请稍候......
前一篇: Cookie和session的区别以及安全性
后一篇: Request和Response、cookie介绍和区别
评论 重要提示:警惕虚假中奖信息
[发评论]
- 评论加载中,请稍候...
发评论
登录名:密码:找回密码 注册 记住登录状态
昵 称:
评论并转载此博文
发评论
以上网友发言只代表其个人观点,不代表新浪网的观点或立场。
< 前一篇 Cookie和session的区别以及安全性
后一篇 > Request和Response、cookie介绍和区别