`
keller
  • 浏览: 48943 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

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>

分享到:
评论

相关推荐

    Jsp和Servlet中文乱码问题

    本文将深入探讨JSP和Servlet中文乱码问题的根源、解决方案以及预防策略。 ### JSP和Servlet中的中文乱码问题根源 中文乱码问题通常源于字符编码不一致或配置错误。在Web应用中,数据流经多个环节,包括客户端...

    解决jsp+servlet开发中的中文乱码问题

    ### 解决JSP+Servlet开发中的中文乱码问题 #### 概述 在基于JSP(Java Server Pages)和Servlet技术的Java Web应用开发过程中,中文乱码问题一直是困扰开发者的一大难题。由于Java Web应用程序涉及多个组件之间的...

    jsp传参 servlet接收中文乱码问题的解决方法.docx

    jsp 传参 servlet 接收中文乱码问题的解决方法 jsp 传参 servlet 接收中文乱码问题是一个经常遇到的问题,特别是在使用 Hibernate+Servlet 框架时。当我们在 jsp 页面传参到 servlet 时,中文字符经常会出现乱码...

    JSPServlet 中的汉字编码问题

    本文主要针对JSP (Java Server Pages) 和 Servlet 中汉字编码问题的解决方法进行详细阐述。 #### 二、字符编码基础知识 1. **字符集**: 指的是用于存储和传输字符的一套规则,包括字符的编码方式。例如ASCII码、GB...

    Jsp_Servlet_中文API档

    主要围绕JSP与Servlet的基本概念、工作原理以及在Web应用开发中的作用等方面展开。 ### JSP与Servlet概述 #### JSP(JavaServer Pages) - **定义**:JSP是一种基于Java技术的服务器端网页开发技术,它允许在HTML...

    ajax+jsp+servlet 中文解决方法

    在这个"ajax+jsp+servlet 中文解决方法"的示例中,开发者遇到了在使用Ajax进行数据交互时中文乱码的问题。中文乱码通常是由字符编码不一致导致的,特别是在跨平台或跨浏览器通信时。以下是一些关于如何解决这个问题...

    servlet与jsp中文乱码处理

    通过以上方法,基本可以解决servlet和jsp在接收和显示中文时的乱码问题。但在实际开发中,可能还需要根据具体环境和需求进行调整。了解这些知识点,对于Java Web开发者来说是非常必要的,能够提高项目的稳定性和用户...

    JSP Servlet 中的汉字编码问题

    JSP Servlet 中的汉字编码各种问题解决方法

    JSP\Servlet中文API文档

    ### JSP\Servlet中文API文档解析 #### 一、Servlet接口概述 在Java Web开发中,Servlet技术扮演着至关重要的角色,它允许开发者创建可扩展的、基于组件的应用程序,这些应用程序可以处理HTTP请求并生成动态响应。`...

    JSP-Servlet中的汉字编码问题-JSP教程

    本文将围绕“JSP-Servlet中的汉字编码问题”这一主题展开讨论,通过对相关知识点的深入剖析,帮助读者理解JSP/Servlet环境中汉字编码可能出现的问题及解决方案。 #### 二、基础知识回顾 1. **字符编码**:字符编码...

    jsp+servlet+mysql乱码解决的这天

    该方案的解决方法可以解决jsp+servlet+mysql开发中常见的中文乱码问题,确保中文字符的正确显示。 jsp+servlet+mysql乱码解决方案的实现步骤如下: 首先,在jsp页面中设置编码格式为utf-8,以确保页面中的中文字符...

    JSP_Servlet 中的汉字编码问题.pdf

    #### 四、JSP/Servlet中的汉字编码问题及解决方法 1. **常见问题分析**: - 在JSP/Servlet应用中,汉字编码问题主要体现在以下几个方面: - **表单提交**:用户通过表单提交的数据可能因为客户端和服务器端编码不...

    Servlet及jsp解决中文乱码问题

    本文将详细介绍如何在Servlet与JSP中彻底解决中文乱码问题,并给出具体的解决方案。 #### 二、中文乱码的原因分析 中文乱码主要由以下几个原因引起: 1. **服务器端编码设置不正确**:如果服务器端的字符集设置与...

    超强过滤器彻底解决JSP-SERVLET中文参数GET-POST传递的问题(转)

    总结,"超强过滤器"是解决JSP-Servlet之间中文参数GET-POST传递问题的有效手段,通过统一设定请求的字符编码,确保在整个Web应用中中文数据能够正确无误地传输和处理。对于大型项目,这样的全局解决方案可以大大提升...

    jsp和servlet请求与响应

    本文详细介绍了JSP和Servlet中关于请求与响应的关键知识点,包括JSP内置对象的作用、请求与响应对象的使用方法、中文乱码问题及其解决办法、转发与重定向的区别以及Servlet的基本创建和配置流程。希望这些内容能够...

    jsp+servlet实现增删改查

    为了解决中文乱码问题,项目可能使用了过滤器(Filter)。在HTTP请求和响应过程中,过滤器可以拦截并处理字符编码,确保中文字符正确显示。例如,设置请求和响应的编码格式为UTF-8,避免中文乱码的出现。 分页功能...

    JSP-Servlet学习笔记第2版.pdf

    11. 实际开发中遇到的问题及其解决方案:例如,处理请求中文乱码问题、在开发中如何分层以及代码的组织和管理。 以上就是学习JSP和Servlet需要掌握的核心知识点。这些知识可以指导开发人员构建动态的Web应用,并...

    jsp/servlet阶段测试

    Filter的用途包括:查询请求并做出相应的行动、修改请求头和内容、修改响应头和内容、解决界面中文乱码的问题等。 4. Listener的类型:Listener是Servlet规范中的一种组件,用于监听Servlet容器的事件。常见的...

    jsp和servlet操作mysql中文乱码问题的解决办法.docx

    在 JSP 和 Servlet 操作 MySQL 过程中,中文乱码问题是一个常见的问题,而解决这个问题需要从多方面入手,包括 JSP 页面、Servlet 编程和 Filter 配置等。本文将详细介绍解决 JSP 和 Servlet 操作 MySQL 中文乱码...

    servlet中文乱码问题

    通过修改Tomcat配置文件中的`URIEncoding`属性以及在Servlet中通过`response.setContentType()`和`request.setCharacterEncoding()`方法来设置字符编码,可以有效解决中文乱码问题。此外,还可以通过字符集转换的...

Global site tag (gtag.js) - Google Analytics