您的位置:首页 > Web前端 > JavaScript

JSP页面显示乱码解决方法

2010-09-13 11:47 507 查看

一、JSP页面显示乱码

下面的显示页面(display.jsp)就出现乱码:
<html>
<head>
<title>JSP的中文处理</title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
</head>

<body>
<%
out.print("JSP的中文处理");
%>
</body>
</html>
对不同的WEB服务器和不同的JDK版本,处理结果就不一样。原因:服务器使用的编码方式不同和浏览器
对不同的字符显示结果不同而导致的。解决办法:在JSP页面中指定编码方式(gb2312),即在页面的第一行加上:<%@ page contentType="text/html; charset=gb2312"%>,就可以消除乱码了。完整页面如下

<%@ page contentType="text/html; charset=gb2312"%>
<html>
<head>
<title>JSP的中文处理</title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
</head>
<body>
<%
out.print("JSP的中文处理");
%>
</body>
</html>

二、表单提交中文时出现乱码

下面是一个提交页面(submit.jsp),代码如下:
<html>
<head>
<title>JSP的中文处理</title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
</head>

<body>
<form name="form1" method="post" action="process.jsp">
<div align="center">
<input type="text" name="name">
<input type="submit" name="Submit" value="Submit">
</div>
</form>
</body>
</html>
下面是处理页面(process.jsp)代码:
<%@ page contentType="text/html; charset=gb2312"%>
<html>
<head>
<title>JSP的中文处理</title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
</head>
<body>
<%=request.getParameter("name")%>
</body>
</html>
如果submit.jsp提交英文字符能正确显示,如果提交中文时就会出现乱码。原因:浏览器默认使用UTF-8编码方式来发送请求,而UTF- 8和GB2312编码方式表示字符时不一样,这样就出现了不能识别字符。
解决办法:通过request.setCharacterEncoding ("gb2312")对请求进行统一编码,就实现了中文的正常显示。修改后的process.jsp代码如下:
<%@ page contentType="text/html; charset=gb2312"%>
<%
request.setCharacterEncoding("gb2312");
%>
<html>
<head>
<title>JSP的中文处理</title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
</head>
<body>
<%=request.getParameter("name")%>
</body>
</html>

三、数据库连接出现乱码

只要涉及中文的地方全部是乱码,解决办法:在数据库的数据库URL中加上
useUnicode=true&characterEncoding=GBK 就OK了。

四、数据库的显示乱码

在mysql4.1.0中,varchar类型,text类型就会出现中文乱码,对于varchar类型把它设为binary属性就可以解决中文问题,对于text类型就要用一个编码转换类来处理,实现如下:
public class Convert {
/** 把ISO-8859-1码转换成GB2312
*/
public static String ISOtoGB(String iso){
String gb;
try{
if(iso.equals("") || iso == null){
return "";
}
else{
iso = iso.trim();
gb = new String(iso.getBytes("ISO-8859-1"),"GB2312");
return gb;
}
}
catch(Exception e){
System.err.print("编码转换错误:"+e.getMessage());
return "";
}
}
}
把它编译成class,就可以调用Convert类的静态方法ISOtoGB()来转换编码。
总结:
1. 在jsp中<%@ page contentType="text/html; charset=A" %>如果指定了,那么在改jsp中所有构造的String(不是引用),如果沒有指定编码,那么这些String的编码是A的。从request的得到的String如果沒有指定request的编码的话,他是iso-8859-1的。从别的地方得到的String是使用原來初始的编码的,比如从数据库得到String,如果数据库的编码是B,那么该String的编码是B而不是A的,也不是系统默认的。 此时,如果要输出的String的编码不是A,那么,很可能显示乱码的,所以首先要将String正確转化为编码A的String,然后输出。
2. 在jsp中<%@ page contentType="text/html; charset=A" %>沒有指定,那么相当于指定了<%@ page contentType="text/html; charset=ISO-8859-1" %>

3. Servelte中如果执行了像 response.setContentType("text/html;charset=A");説明将response的字符输出流编码设置为A,所有要输出的String的编码要转化为A的,否則会得到乱码的。
Servelet中从request得到的String的编码和jsp中一样的,但是在servlet java文件中构造的String是使用的系统默认的编码的。在servelt中从外部得到的String 是使用原来的编码的,比如从编码为B的数据库得到的数据是编码为B的,不是A,也不是系统默认的编码。

五、Linux 下java中文环境设置

首先,检查你的 /usr/share/fonts/ttf/gb 目录下是否装有中文字体 gbsn00lp.ttf 。如果没有,也可以用 Windows 字体目录下的 song.ttf 来代替。将字体文件拷贝到 Java 安装目录下的 jre/lib/fonts 下。第二,修改 Java 安装目录下的 jre/lib/fonts/fonts.dir 文件,将首行的 72 改为 73,然后添加下列内容:
gbsn00lp.ttf -Arphic Technology Co.-AR PL SungtiL GB-medium-r-normal--0-0-0-0-c-0-gb2312.1980-0
如果你用的是 song.ttf ,则应该将头部的 gbsn00lp.ttf 改为 song.ttf 。
第三,在 Java 安装目录下的 jre/lib 目录中,将字体配置文件 font.properties.zh.Turbo 复制为 font.properties.zh 。然后修改 font.properties.zh 。将文件中所有的:
-tlc-song-medium-r-normal--*-%d-*-*-c-*-gbk-0 替换为:
-Arphic Technology Co.-AR PL SungtiL GB-medium-r-normal--0-0-0-0-c-0-gb2312.1980-0
第四,用 JDK 自带的演示程序 SwingSet2 测试,如果看到中文菜单则说明设置成功。

六、Java Web配置过滤器进行字符编码

1. 在Web.xml中配置过滤器:
<!-- Example filter to set character encoding on each request -->
<filter>
<filter-name>Set Character Encoding</filter-name>
<filter-class> com.hthk.iisz.born.filter. SetCharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>GBK</param-value>
</init-param>
</filter>
<!-- Example filter mapping to apply the "Set Character Encoding" filter to *all* requests processed by this web application -->
<filter-mapping>
<filter-name>Set Character Encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
2. 编写过滤器
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0 *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.hthk.iisz.born.filter;

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;
/**
* <p>Example 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
* user's session.</p>
*
* @author Craig McClanahan
* @version $Revision: 466607 $ $Date: 2006-10-21 17:09:50 -0600 (Sat, 21 Oct 2006) $
*/
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);
}
}

七、Tomcat处理中文字符编码

首先JAVA(包括JSP)源文件中很可能包含有中文,而Java和JSP源文件的保存方式是居于字节流的,如果Java和JSP编译成class文件过程中,使用的编码方式与源文件的编码方式不一致,就会出现乱码。基于这种乱码,建议在Java文件中尽量不要写中文(注释部分不参与编译,写中文没关系),如果必须写的话,尽量手动带参数编译-ecoding GBK或-ecoding gb2312;对于JSP,在文件头加上<%@page contentType=”text/html;charset=GBK”%>或<%@page contentType=”text/html;charset=gb2312”%>基本上就能解决这类乱码问题.

Get提交方式的字符编码修改方法:
更改%TOMCAT_HOME%/conf/server.xml
<Connector port="8080" maxHttpHeaderSize="8192"
maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
enableLookups="false" redirectPort="8443" acceptCount="100"
connectionTimeout="20000" disableUploadTimeout="true" URIEncoding=’TUF-8’ useBodyEncodingForURI="true"./>
Post提交方式的媳妇编码修改方法:
更改%TOMCAT_HOME%/bin/ catalina.bat或catalina.sh
catalina.bat在第51行添加set CATALINA_OPTS=”-Dfile.encoding=UTF-8”
catalina.sh 在第52行添加export CATALINA_OPTS = "-Dfile.encoding=UTF-8"

八、总结

JAVA Unicode for TOMCAT
1. Edit file <TOMCAT>/conf/server.xml under tag <Connector> to add URIEncoding="UTF-8" useBodyEncodingForURI="true".
2. Edit file <TOMCAT>/bin/catalina.bat for Windows to add set CATALINA_OPTS = "-Dfile.encoding=UTF-8" or <TOMCAT>/bin/catalina.sh for Linux to add export CATALINA_OPTS = "-Dfile.encoding=UTF-8".
3. Set IDE (for example, NetBean, Eclipse and etc) file setting to UTF-8.
4. For all the JSPs, add these two lines:
a. <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
b. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
5. Create a filter as below:
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 EncodingFilter implements Filter {
private String encoding;
private FilterConfig filterConfig;
/**
* @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
*/
public void init(FilterConfig fc) throws ServletException {
this.filterConfig = fc;
this.encoding = filterConfig.getInitParameter("encoding");
}
/**
* @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
* javax.servlet.ServletResponse, javax.servlet.FilterChain)
*/
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
req.setCharacterEncoding(encoding);
chain.doFilter(req, resp);
}
/**
* @see javax.servlet.Filter#destroy()
*/
public void destroy() {
}
}
6. Edit file ../WEB-INF/web.xml to include filter:
<filter>
<filter-name>EncodingFilter</filter-name>
<filter-class>EncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>EncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: