分享

jsp与servlet中的中文问题解决

 smoking_boy 2005-08-10
JSP与Servlet中的中文问题解决


中文编码采用GBK或者gb2312,前者支持的字符集合要大。
具体是:
(1)Jsp页面中设定:<%@ page contentType="text/html; charset=GBK" %>
(2)Servlet中,在response.getWriter()调用之前,执行response.setContentType(”text/html; charset=GBK")
(3)如果在Servlet中没有设定,自行编写toGBK函数,在取得参数时候进行转换,代码如下:
 /**
    * 做编码的转换,转换成GBK。
    * @param str  需要做转换的字符串
    * @return  String   返回转换后的字符串
    */
    public static String toGBK(String str) {
        String temp = str;
        try {
            if (temp == null) {
                temp = "";
            }
            if (temp.equals("null")) {
                temp = "";
            }
            byte[] b = temp.getBytes("ISO8859-1"); //按字节将串拆分
            str = new String(b, "GBK"); //按GBK编码方式将字节组合
        } catch (UnsupportedEncodingException uee) {
        }
        return str;
    }
    (4)编写一个Servlet Filter,在每次响应之前进行编码的转换。这样可以避免在每个Servlet中进行上述的(2)(3)操作。Filter示例如下:
 package kellerdu.util;
    mport javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import net.sf.hibernate.*;


/**
 * <p>Filter that sets the character encoding to be used in parsing the
 * incoming request, either unconditionally or only if the client did not
 * specify a character encoding.  Configuration of this filter is based on
 * the following initialization parameters:</p>
 * <ul>
 * <li><strong>encoding</strong> - The character encoding to be configured
 *     for this request, either conditionally or unconditionally based on
 *     the <code>ignore</code> initialization parameter.  This parameter
 *     is required, so there is no default.</li>
 * <li><strong>ignore</strong> - If set to true, any character encoding
 *     specified by the client is ignored, and the value returned by the
 *     <code>selectEncoding()</code> method is set.  If set to false,
 *     <code>selectEncoding()</code> is called <strong>only</strong> if the
 *     client has not already specified an encoding.  By default, this
 *     parameter is set to "true".</li>
 * </ul>
 *
 * <p>Although this filter can be used unchanged, it is also easy to
 * subclass it and make the <code>selectEncoding()</code> method more
 * intelligent about what encoding to choose, based on characteristics of
 * the incoming request (such as the values of the <code>Accept-Language</code>
 * and <code>User-Agent</code> headers, or a value stashed in the current
 * users session.</p>
 */

public class SetEncodingServlet extends HttpServlet implements Filter {
    // ----------------------------------------------------- Instance Variables


    /**
     * The default character encoding to set for requests that pass through
     * this filter.
     */
    protected String encoding = null;

    /**
     * The filter configuration object we are associated with.  If this value
     * is null, this filter instance is not currently configured.
     */
    protected FilterConfig filterConfig = null;

    /**
     * Should a character encoding specified by the client be ignored?
     */
    protected boolean ignore = true;

    // --------------------------------------------------------- Public Methods


    /**
     * Take this filter out of service.
     */
    public void destroy() {

        this.encoding = null;
        this.filterConfig = null;

    }

    /**
     * Select and set (if specified) the character encoding to be used to
     * interpret request parameters for this request.
     *
     * @param request The servlet request we are processing
     * @param result The servlet response we are creating
     * @param chain The filter chain we are processing
     *
     * @exception IOException if an input/output error occurs
     * @exception ServletException if a servlet error occurs
     */
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException,
        ServletException {
        // Conditionally select and set the character encoding to be used
        if (ignore || (request.getCharacterEncoding() == null)) {
            String encoding = selectEncoding(request);
            if (encoding != null) {
                request.setCharacterEncoding(encoding);
            }
        }
        /**
         * 用户认证
         */
        try {
           HttpServletRequest req = (HttpServletRequest) request;
           TblSysUser user = (TblSysUser) req.getSession().getAttribute(
               LoginOper.USER);
           if (user == null && req.getServletPath().indexOf("login") == -1) {//没有登录
              req.getRequestDispatcher("/login.jsp").forward(request,response);
              //chain.doFilter(request, response);
           } else {
               chain.doFilter(request, response);
        //每次响应之后关闭Heibernate Session
              HibernateUtil.closeSession();
           }
       } catch (ServletException ex) {
       } catch (IOException ex) {
       } catch (HibernateException ex) {
       }
    }

    /**
     * Place this filter into service.
     *
     * @param filterConfig The filter configuration object
     */
    public void init(FilterConfig filterConfig) throws ServletException {
        //System.out.println("SetEncodingServlet inits");
        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;
        }
        try {
            com.yingrui.voip.HibernateUtil.closeSession();
        } catch (HibernateException ex) {
            System.out.println("Hibernate Init Exception!");
        }

    }

    // ------------------------------------------------------ Protected Methods


    /**
     * Select an appropriate character encoding to be used, based on the
     * characteristics of the current request and/or filter initialization
     * parameters.  If no character encoding should be set, return
     * <code>null</code>.
     * <p>
     * The default implementation unconditionally returns the value configured
     * by the <strong>encoding</strong> initialization parameter for this
     * filter.
     *
     * @param request The servlet request we are processing
     */
    protected String selectEncoding(ServletRequest request) {
        return (this.encoding);

    }

}

相应的web.xml配置如下(这里采用Struts):
  <filter>
    <filter-name>setencodingservlet</filter-name>
    <filter-class>kellerdu.util.SetEncodingServlet</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>GBK</param-value>
    </init-param>
    <init-param>
      <param-name>ignore</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>setencodingservlet</filter-name>
    <url-pattern>*.jsp</url-pattern>
  </filter-mapping>
  <filter-mapping>
    <filter-name>setencodingservlet</filter-name>
    <url-pattern>*.do</url-pattern>
  </filter-mapping>


    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多