java中文处理大全

本文围绕Java编程中的编码处理展开。介绍了处理http请求数据编码的方法,如设置httpservletrequest对象字符编码、使用filter过滤等;阐述了数据库编码处理,包括连接和操作数据时的编码转换;还提及xml配置文件编码设置及响应结果编码设置,如在servlet、jsp、html中的设置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、处理http请求数据编码

(1)在处理请求前,先设置httpservletrequest对象的字符编码,我们大多使用 request.setCharacterEncoding("gb2312") 方法,或者使用servletfilter过滤设置来处理中文表单的提交。需要注意的是,这个方法的使用一定需要在 request.getParameter前使用。否则对你所需要的结果会有不同的影响。

(2)对用户输入的请求数据进行编码:

strOut = new String(strIn.getBytes("8859_1"), "GB2312");

在Apusic 0.9.5版中实现了Java Servlets 2.3规范草案,其中在ServletRequest接口中新增了一个方法setCharacterEncoding(String enc),可以补上在HTTP请求中缺少的charset信息,而上面这一烦琐的转换过程就在Servlet引擎中自动完成了,而且Servlet引擎还对转换过程做了优化,提高了运行效率。
下面给出一个简单的例子,大家可以做一下比较。

// 传统方式
<%@ page contentType="text/html; charset=gb2312" %>
<html>
<body>
<form method=post action=test.jsp>
<input type=text name=your_name>
</form>
<%= new String(request.getParameter("your_name").getBytes("8859_1"), "GB2312") %>
</body>
</html>
或  写个类

<%@ page contentType=“text/html;charset=gb2312”%>
<%!
public String getStr(String str){
try{String temp_p=str;
byte[] temp_t=temp_p.getBytes(“ISO8859-1”);
String temp=new String(temp_t);
return temp;
}
catch(Exception e){ }
return “NULL”;
}
%>
<%--http://www.cndes.com测试--%>
<% String keyword=“创联网络技术中心欢迎您的到来”;
String keyword1=request.getParameter(“keyword1”);
keyword1=getStr(keyword1);
out.print(keyword);
out.print(keyword1);
%>

// 新的方式
<%@ page contentType="text/html; charset=gb2312" %>
<% request.setCharacterEncoding("GB2312"); %>
<html>
<body>
<form method=post action=test.jsp>
<input type=text name=your_name>
</form>
<%= request.getParameter("your_name") %>
</body>
</html>  

(3)filter过滤设置来处理中文表单的提交

1)首先编写filter类:

package myFilter;


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

public class ChangeCharsetFilter implements Filter {


    protected String encoding = null;/////要制定的编码,在web.xml中配置

    protected FilterConfig filterConfig = null;

        public void destroy() {

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

    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
 throws IOException, ServletException {

            if (request.getCharacterEncoding() == null){
            String encoding = getEncoding();////得到指定的编码名字
            if (encoding != null)
                request.setCharacterEncoding(encoding);////设置request的编码
        }

         chain.doFilter(request, response);///有机会执行下一个filter

    }

    public void init(FilterConfig filterConfig) throws ServletException {

          this.filterConfig = filterConfig;
        this.encoding = filterConfig.getInitParameter("encoding");///得到在web.xml中配置的编码
  
    }


    protected String getEncoding() {

        return (this.encoding);///得到指定的编码

    }


}


2。编辑web.xml文件

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app
 PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>

<filter>
        <filter-name>SetCharacterEncoding</filter-name>
        <filter-class>myFilter.ChangeCharsetFilter </filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>GB2312</param-value>//////指定编码为GB2312
        </init-param>
     </filter>
    <filter-mapping>
        <filter-name>SetCharacterEncoding</filter-name>
        <url-pattern>/*</url-pattern>////////对于所有的request改变其编码
    </filter-mapping>

</web-app>
///

3。

写一个a.jsp

<%@ page contentType="text/html; charset=GB2312" %>
<html>
<head></head>
<body>
<%
String name=request.getParameter("name");///本来这里得到字符是iso-8859-1编码的,不能直接

在Console中输出的,但是现在改变了request的编码方式,此时的name的编码是GB2312,所以能正确在Console中显示的。

System.out.println(name);

%>
<form action="a.jsp" method="post">
<input type="text" name="name">
<input type="submit">
</form>
<%=name%>
</body>
</html>

完!


2。编辑web.xml文件

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app
 PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>

<filter>
        <filter-name>SetCharacterEncoding</filter-name>
        <filter-class>myFilter.ChangeCharsetFilter </filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>GB2312</param-value>//////指定编码为GB2312
        </init-param>
     </filter>
    <filter-mapping>
        <filter-name>SetCharacterEncoding</filter-name>
        <url-pattern>/*</url-pattern>////////对于所有的request改变其编码
    </filter-mapping>

</web-app>
///

3。

写一个a.jsp

<%@ page contentType="text/html; charset=GB2312" %>
<html>
<head></head>
<body>
<%
String name=request.getParameter("name");///本来这里得到字符是iso-8859-1编码的,不能直接

在Console中输出的,但是现在改变了request的编码方式,此时的name的编码是GB2312,所以能正确在Console中显示的。

System.out.println(name);

%>
<form action="a.jsp" method="post">
<input type="text" name="name">
<input type="submit">
</form>
<%=name%>
</body>
</html>

完!


2。编辑web.xml文件

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app
 PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>

<filter>
        <filter-name>SetCharacterEncoding</filter-name>
        <filter-class>myFilter.ChangeCharsetFilter </filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>GB2312</param-value>//////指定编码为GB2312
        </init-param>
     </filter>
    <filter-mapping>
        <filter-name>SetCharacterEncoding</filter-name>
        <url-pattern>/*</url-pattern>////////对于所有的request改变其编码
    </filter-mapping>

</web-app>
///

3。

写一个a.jsp

<%@ page contentType="text/html; charset=GB2312" %>
<html>
<head></head>
<body>
<%
String name=request.getParameter("name");///本来这里得到字符是iso-8859-1编码的,不能直接

在Console中输出的,但是现在改变了request的编码方式,此时的name的编码是GB2312,所以能正确在Console中显示的。

System.out.println(name);

%>
<form action="a.jsp" method="post">
<input type="text" name="name">
<input type="submit">
</form>
<%=name%>
</body>
</html>

完!


2、处理数据库编码

(1)连接数据库时处理:

用 useUnicode=true&characterEncoding=gb2312 连接数据库?
小弟不才,,看不懂这句是什么意思!!能不能说详细一点,,谢谢..


try{
Class.forName("org.gjt.mm.mysql.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/database?user=root&password=pwd&useUnicode=true&characterEncoding=gb2312");
}catch(Exception e){
System.err.println(e.getMessage());
}

只有这样而已。如果你想换编码,只需改一下gb2312这个就行了。

(2)操作数据时取

一,取中文
用JDBC执行SELECT语句从SERVER取数据(中文)后,将数据
用APPEND方法加到TEXT AREA(TA),不能正确显示。但加到
LIST中时,则大部分汉字可正确显示。

处理:将数据按“ISO-8859-1”格式转为字节数组,再按系统
缺省编码格式(default character encoding)转为STRING,即可在TA和LIST中正确显示。
程序段如下:

dbstr2 = results.getString(1);
//*********************************************************************
// After read result from Database server, Convert the result string.

dbbyte1 = dbstr2.getBytes("iso-8859-1");
dbstr1 = new String(dbbyte1);
//*********************************************************************

二,写中文到DB
处理方式与以上相逆,先将SQL语句按DEFAULT CHARACTER ENCODING
转为字节数组,再按ISO-8859-1转为STRING,然后送执行,
则中文信息可正确写入DB。

sqlstmt = tf_input.getText();

//*****************************************************************************
// Before send statement to Database server, Convert sql statement.

dbbyte1 = sqlstmt.getBytes();
sqlstmt = new String(dbbyte1,"iso-8859-1");
//*****************************************************************************

_stmt = _con.createStatement();
_stmt.executeUpdate(sqlstmt);
。。。。。。

3、处理xml配置文件编码

如果XML文件中包含中文,可以将XML文件字符编码设为“GB2312”。比如:aaa.xml文件如下

<?xml version='1.0' encoding="GB2312"?>

<database>

    <user oid="12" email="aaa@163.com"  password="aaa" firstname="好好好" lastname="哈"/>

    <product oid="110" name="CD束身听"  image="multimedia/aaa.gif" description="可播放多种格式"/>

</database>

4/处理响应结果的编码

(1)在servlet中

response.setContentType("text/html;charset=GB2312");

(2)在jsp中

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

(3)在html中

<head>

<meta http-equiv="Content-Type" CONTENT="text/html; charset=gb2312">

</head>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值