Java 的乱码解决方法 统一编码UTF-8

一、介绍两个类
URLEncoder//编码
URLDecoder//解码

看看下面的测试输出,你就明白是做什么的了

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

public class main {

 public static void main(String[] args) throws UnsupportedEncodingException{
  System.out.println("UTF-8");
  String a = URLEncoder.encode("中文测试", "UTF-8");//编码
  System.out.println(a);
  System.out.println(URLDecoder.decode(a,"UTF-8"));//还原
  //下面同理
  System.out.println("/nGBK(百度就是用这种)");
  a = URLEncoder.encode("中文测试", "GBK");
  System.out.println(a);
  System.out.println(URLDecoder.decode(a,"GBK"));
 }
}

[输出]
UTF-8
%E4%B8%AD%E6%96%87%E6%B5%8B%E8%AF%95
中文测试
GBK(百度就是用这种)
%D6%D0%CE%C4%B2%E2%CA%D4
中文测试


看了上面的输出就明白百度地址栏那一串是什么了。假如你做了下面一系列设置,那么在服务器端你接收到Get方法的中文参数将被转换成类型%D6%D0%CE%C4%B2%E2%CA%D4 你就需要用到上面的两个工具类, 如果你像我在下面设置,你在上面的调用的第二个参数也得是UTF-8; 使用post就不需要解码,直接读取就行了。


二、配置tomcat (这一步我没有做,但没发现问题,我用的是Tomcat 5.08经典版本)
打开tomcat的server.xml文件,找到区块,加入如下一行:
URIEncoding="UTF-8"
完整的应如下:
<Connector port="8080" maxThreads="150" minSpareThreads="25" maxSpareThreads="75" enableLookups="false" redirectPort="8443" acceptCount="100" debug="0" connectionTimeout="20000" disableUploadTimeout="true" URIEncoding="UTF-8"/>

 

三、增加连接数据库的参数
mysql 数据库建表时设置编码为utf8(写法不同不是UTF-8),

连接数据库:
 // 连接参数,这里设置连接使用的编码
 public static final String DB_URL = "jdbc:mysql://localhost:3306/?useUnicode=true&characterEncoding=utf8";

 

四、使用过滤器设置编码 
1、
// 简单的就用下面这个,这里使用的是硬编码也就是在代码中写死了用那种编码我这里用utf-8,也可以把编码设置用写到web.xml中的Filter设置中
package com.max;

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;

/**
* Example filter that sets the character encoding to be used in parsing the
* incoming request
*/
public class SetCharacterEncodingFilter implements Filter {

    /**
     * Take this filter out of service.
     */
    public void destroy() {
    }
    /**
     * Select and set (if specified) the character encoding to be used to
     * interpret request parameters for this request.
     */
    public void doFilter(ServletRequest request, ServletResponse response,
    FilterChain chain)throws IOException, ServletException {

    request.setCharacterEncoding("UTF-8");

    // 传递控制到下一个过滤器
    chain.doFilter(request, response);
    }

    public void init(FilterConfig filterConfig) throws ServletException {
    }
}


web.xml配置文件中增加
    <filter>
  <filter-name>Set Character Encoding</filter-name>
  <filter-class>com.max.SetCharacterEncodingFilter</filter-class>
 </filter>
 <filter-mapping>
  <filter-name>Set Character Encoding</filter-name>
  <url-pattern>/*</url-pattern>
 </filter-mapping>

 

2、
//下面这个是将编码设置放到web.xml中的

filter类的内容:

/*
 * ====================================================================
 *
 *              JavaWebStudio 开源项目
 *              
 *               Struts_db v0.1
 *
 * ====================================================================
 */
package com.strutsLogin.util;

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 {

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

  // Pass control on to the next filter
  chain.doFilter(request, response);

 }

 /**
  * Place this filter into service.
  *
  * @param filterConfig
  *            The filter configuration object
  */
 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 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);

 }

}// EOC

然后我们在web.xml中加一些配置,就可以了,配置如下:

<filter>
    <filter-name>Set Character Encoding</filter-name>
    <filter-class>javawebstudio.struts_db.SetCharacterEncodingFilter</filter-class>
    <init-param>
        <param-name>encoding</param-name>
        <param-value>UTF-8</param-value>
    </init-param>
    <init-param>
        <param-name>ignore</param-name>
        <param-value>true</param-value>
    </init-param>
</filter>

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

放在web.xml的合适位置。一般在最后,<jsp-config>标签之前(如果有的话)

 

五、在JSP页面中设置编码

<%@ page language="java" pageEncoding="UTF-8"%>

 

六、使用i18n
使ApplicationResources.properties支持中文
建立一个ApplicationResources_ISO.properties文件,把应用程序用的message都写进去,然后在dos下执行这个命令,
native2ascii -encoding gb2312 ApplicationResources_ISO.properties ApplicationResources.properties
native2ascii          [参数]  [输入文件]                          [输出文件]

native2ascii这个工具是jdk自带的一个东东,所以如果path都设定正确就可以直接运行了,你可以在$java_home$/bin下找到他。
转换后的中文类似于这个样子
中文格式下 :user_name_label=用户名:
ascii格式下 :user_name_label=/u7528/u6237/u540D/uFF1A

Netbean 有个方便的编辑多国语言的工具,但不是直接写,而是在弹出窗口中编辑,确定插入后自动转换成ascii如上面那种.
Eclipse 有个一样功能的插件jinto在下面的地址中下载
http://www.guh-software.de/jinto.html

在Jsp页面使用 "user_name_label" 来引用 "用户名:",而且能够简单方便实现多语言支持。

通常将编码同一成UTF-8是很有好处的,如果想使用其他编码如GBK,这上面用到UTF-8全改为GBK

 
  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值