JSP中使用request乱码问题的解决

2016-02-19 13:18 1 1 收藏

get新技能是需要付出行动的,即使看得再多也还是要动手试一试。今天图老师小编跟大家分享的是JSP中使用request乱码问题的解决,一起来学习了解下吧!

【 tulaoshi.com - Web开发 】

  JSP显示中文有乱码怎么办,用request得到的用户输入的中文怎么是乱码,把汉字写到数据库怎么是乱码,等等一些关于汉字乱码的问题。其实这个问题很简单,管它汉字不汉字,还是日文,还是其他的什么双字节的语言,我们一律把它当作UTF-8看待。

      (一)request中的双字节文字

      我们来实现在整个应用程序中使用UTF-8编码工作,之所以选择UTF-8不仅仅之于上述原因,我们知道java的就是基于在UTF-8之上的,所以我们选择UTF-8应该没错
首先把我们的.java, .jsp文件都用UTF-8编码来保存,如果以前的没有用UTF-8保存也无所谓,但是建议以后写的都用UTF-8来保存。

      并在.jsp里面写:

以下是引用片段:
%@page contentType="text/html; charset=UTF-8"%而不是%@page contentType="text/html; charset=UTF-8"%

      然后在web.xml添加下面一段:

以下是引用片段:
web-app
...
  filter
    filter-nameSet Character Encoding/filter-name
    filter-classcom.redv.projects.eduadmin.util.filters.SetCharacterEncodingFilter/filter-class
    init-param
      param-nameencoding/param-name
      param-valueUTF-8/param-value
    /init-param
  /filter
  filter-mapping
    filter-nameSet Character Encoding/filter-name
    url-pattern/*/url-pattern
  /filter-mapping
...
/web-app

      其中com.redv.projects.eduadmin.util.filters.SetCharacterEncodingFilter的代码如下:

package com.redv.projects.eduadmin.util.filters;
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;
import javax.servlet.UnavailableException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SetCharacterEncodingFilter
    implements Filter {

(本文来源于图老师网站,更多请访问https://www.tulaoshi.com/webkaifa/)

  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 {
    // 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);           //
Overrides the name of the character encoding used in the body of this request. This method must be called prior to reading request parameters or reading input using getReader().
      }
    }
    // Pass control on to the next filter
    chain.doFilter(request, response);
  }
  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);
  }
}

(本文来源于图老师网站,更多请访问https://www.tulaoshi.com/webkaifa/)

      这样,我们的request请求就是以UTT-8编码的,在JSP程序中就可以使用:request.getParameter("myKey")来直接得到UTF-8编码的字符串了,而不需要像这样:new String(request.getParameter("myKey").getBytes("ISO-8859-1"), "GBK")来解决那些乱码了。

     (二)数据库处理的双字节文字

      另外一个,就是写入数据库的问题,我们知道我们在使用mysql的时候可以改用这样的url来处理汉字编码问题:jdbc:mysql://localhost:3306/upas?useUnicode=true& characterEncoding=gb2312,那么对于那些我们无法像mysql这样解决的怎么办呢?难道我们每次都这样写吗:

import java.sql.*;
Class.forName("org.gjt.mm.mysql.Driver");
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
  con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "");
  pstmt = con.prepareStatement("SELECT f3, f4 FROM tbl1 WHERE f1 = ? AND f2 = ?");
  pstmt.setString(1, new String(f1.getBytes("GBK"), "ISO-8859-1");
  pstmt.setString(2, new String(f2.getBytes("GBK"), "ISO-8859-1");
  rs = pstmt.executeQuery();
  String f3, f4;
  while(rs.next()) {
    f3 = new String(rs.getString(1).getBytes("ISO-8859-1"), "GBK");
    f4 = new String(rs.getString(2).getBytes("ISO-8859-1"), "GBK");
  }
}
finally {
  //close resouces
  ...
}

      其实我们完全可以这样写:

import java.sql.*;
import com.redv.sql.encoding.*;
Class.forName("org.gjt.mm.mysql.Driver");
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
  con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "");
  //接管数据库连接实例
  boolean coding = true;
  EncodingConnection codingConnection = new EncodingConnection(con, coding, "ISO-8859-1", "GBK");
  //获得接管后的数据库连接实例,以后直接使用con已经是经过EncodingConnection重新包装过的实例
  con = codingConnection.getConnection();
  pstmt = con.prepareStatement("SELECT f3, f4 FROM tbl1 WHERE f1 = ? AND f2 = ?");
  pstmt.setString(1, f1);
  pstmt.setString(2, f2);
  rs = pstmt.executeQuery();
  String f3, f4;
  while(rs.next()) {
    f3 = rs.getString(1);
    f4 = rs.getString(2);
  }
}
finally {
  //close resouces
  ...
}

      看看,怎么样,我们只需要在获取数据库连接的地方稍微修改一下,甚至我们可以把它当作参数保存在 properties里面,改变coding的布尔值来设定是否使用自动编码转换。常常我们可以使用一个Database类来封装获取数据库连接的那段 getConnection,以便于我们可以从 javax.sql.DataSource中获取到数据库连接。这个时候我们仅仅需要修改我们的Database类即可,而不用去搜索所有使用了 rs.setString(), rs.getString()的地方去加入我们的编码转换代码了。

来源:https://www.tulaoshi.com/n/20160219/1603731.html

延伸阅读
标签: Java JAVA基础
  第二部分:关于JavaMail 文档的使用 下载的JavaMail API中带的文档是很有用的。你可以在JavaMail下的/docs/javadocs/index.html找到它。第二部分主要将分析邮件程序的组件。你可以通过阅读文档来获得更多这方面的信息。 组件发送邮件需要使用JavaMail,它使对邮件的操作变得简单易用。 属性对象 JavaMail需要创建一...
标签: Web开发
今天终于解决了AJAX的中文乱码问题,写篇文章来帮助一下有同样问题的朋友们。我的开发环境:XP, eclipse,使用GB18030编码。 当遇到这个问题时,到网上去查了好多文章,提到几种解决方案,如:全站UTF-8编码;请求头编码为中文;使用javascript中的escape函数。 使用GET方式提交数据的时候,中文问题很好解决,setrequestheader("Content-Type...
标签: Web开发
网上有很多解决这个问题的方法,试了一下都不好用,自己就对于这些方法测试了一下,然后逐个排除无用的设置,最后得到了最简单的方案。 js代码: 得到XmlHttpRequest的类 Code 1function HttpRequest() 2{ 3 //取得Request对象 4 this.Request=function(){ 5 try 6 { 7 if(window.XMLHttpRequest) request=new XMLHttpRequest(); 8 if(!reque...
标签: PHP
 从MySQL 4.1开始引入的多语言支持确实很棒,而且一些特性已经超过了其他的数据库系统。不过在测试过程中发现使用适用于MySQL 4.1之前的PHP语句操作MySQL数据库会造成乱码,即使是设置过了表字符集也是如此。 MySQL 4.1的字符集支持(Character Set Support)有两个方面:字符集(Character set)和排序方式(Collation)。对于字...

经验教程

392

收藏

90
微博分享 QQ分享 QQ空间 手机页面 收藏网站 回到头部