首页 > 编程 > JSP > 正文

JSP动态网站开发程序中的关于中文问题的解决方法

2024-09-05 00:19:43
字体:
来源:转载
供稿:网友
注册会员,创建你的web开发资料库,

  这段时间经常看到有人问到中怎么中文总是?号。原因其实很简单,因为大家大多用的是tomcat服务器,而tomcat服务器的默认编码为 iso-8859-1(西欧字符)。就是因为iso-8859-1(西欧字符)编码造成了我们经常看到?号。

  方法一:最简单也是用的最多的方法。

  <%@ page language="java" pageencoding="gbk" %>

  或者<%@ page contenttype="text/html;charset=gbk";>这里可以用gb2312或者gbk,只是gbk比gb2312支持跟多的字符。

  这个方法用于jsp页面中的中文显示。

  方法二:使用过滤器。

  过滤器使用主要针对表单提交,插入数据库的数据都是?号。这也是应为tomcat不按request所指定的编码进行编码,还是自作主张的采用默认编码方式iso-8859-1编码。

  编写一个setcharacterencodingfilter类。

import java.io.ioexception;

import javax.servlet.filter;
import javax.servlet.filterchain;
import javax.servlet.filterconfig;
import javax.servlet.servletexception;
import javax.servlet.servletrequest;
import javax.servlet.servletresponse;

public class setcharacterencodingfilter implements filter {
 protected string encoding = null;
 protected filterconfig filterconfig = null;
 protected boolean ignore = true;

 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;
 }

 public void dofilter(servletrequest request, servletresponse response, filterchain chain) throws ioexception, servletexception {
 // todo 自动生成方法存根
 if (ignore (request.getcharacterencoding() == null)) {
  string encoding = selectencoding(request);
  if (encoding != null)
   request.setcharacterencoding(encoding);
 }
 chain.dofilter(request, response);
}

public void destroy() {
 // todo 自动生成方法存根
 this.encoding = null;
 this.filterconfig = null;
}

protected string selectencoding(servletrequest request) {
 return (this.encoding);
}
}

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表