杞人忧天上掉下个林妹妹

穿越旷野的妹妹啊,慢些走;请不要用你的沉默告诉我,你不回头!

导航

乱吗解决方法[收集]

在 XSL 中引入外部 CSS/JS/VBS 时, 如果 被引入的文件内含有中文, 则会变为乱码的解决方法!
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB2312" />
<title></title>
<script src=“xxx.js“ language=“javascript“ charset=“GB2312“></script>
</head>

 

1.Jsp文件页面显示乱码,这种情况比较好处理,在页面的Page指令加上如下一项就OK了:

<%@ page contentType="text/html; charset=gb2312"%>

2.Jsp页面采用表单提交时,提交的数据中含有中文,这时我们获取表单数据后,展示到其它页面时也会出现乱码,解决方案是在提交处理的Servlet里接收数据时,先加上如下一行代码:

request.setCharacterEncoding("gb2312");

这是其中的一种作法,当页面较少时还好,如果页面较多,我每添加新的页面就要加上这句话,所以可以采用过滤器来解决,具体解决步骤如下:

 

首先写一个过滤器类,代码如下:

package demo;

import javax.servlet.*;
import java.io.IOException;

public class SetCharacterEncodingFilter implements Filter {

 protected String encoding = null;             //编码方式

 protected FilterConfig filterConfig = null;   //过滤器配置信息

 protected boolean ignore = true;              //是否忽略过滤


 public void destroy() {
  this.encoding = null;
  this.filterConfig = null;
 }


 public void doFilter(ServletRequest request, ServletResponse response,
   FilterChain chain) throws IOException, ServletException {
  if (ignore || (request.getCharacterEncoding() == null)) {

   String encoding = selectEncoding(request);
   if (encoding != null) {
    request.setCharacterEncoding(encoding);
   }
  }
  chain.doFilter(request, response);
 }

 /**
  * 过滤器初始化方法,从配置文件读取编码方式和是否忽略信息
  * @author 
  * @param  FilterConfig     filterConfig       过滤器配置信息,存放在web.xml中
  * @return
  * @exception
  */
 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 if (value.equalsIgnoreCase("yes"))
   this.ignore = true;
  else
   this.ignore = false;
 }

 
 protected String selectEncoding(ServletRequest request) {
  return (this.encoding);
 }
}

然后在web.xml文件中添加如下代码:

 <filter>
  <filter-name>Set Character Encoding</filter-name>
  <filter-class>com.tcs.common.SetCharacterEncodingFilter</filter-class>
  <init-param>
   <param-name>encoding</param-name>
   <param-value>UTF-8</param-value>
  </init-param>
 </filter>

 <filter-mapping>
  <filter-name>Set Character Encoding</filter-name>
  <url-pattern>/*</url-pattern>
 </filter-mapping>

这样所有的请求都将交由这个过滤器处理下,这样无论我们添加多少个页面都可以放心了,不用总考虑要加那么一句代码了.

3.在存取数据库时发生乱码现象,这种现象比较郁闷,处理起来相对复杂一点.

首先要在数据存入数据库时,进行如下编码的转换:如我们要把含有中文的字符串存入数据库,首先:

    String s=request.getParameter("author"); 

    String author=new String(s.getBytes("ISO8859_1"),"gb2312");

在从数据库取出展示到页面时,也要经过如下转换:

      String  s=rs.getString("author");

      String author=new String(s.getBytes("GB2312"),"ISO8859_1");

posted on 2006-10-08 17:25  杞人  阅读(288)  评论(0编辑  收藏  举报