Welcome

首页 / 网页编程 / JSP / JSP页面乱码的5种解决方法

JSP页面乱码的5种解决方法2014-10-27JSP编程中网页显示出现乱码的情况,基本可以归为5类:

1. JSP页面显示乱码。

2. Servlet接收Form/Request传递的参数时显示为乱码

3. JSP接收Form/Request传递的参数时显示为乱码

4. 用<jsp:forward page="catalog2.html"></jsp:forward>时页面显示乱码

5. 数据库存取的时候产生乱码。

下面给出全部解决方法:

步骤/方法

1. JSP页面显示乱码。

第一种为在页面的开头加上:

<%@ page language="java" contentType="text/html; charset=GBK" pageEncoding="GBK"%>

注:有时候如果不再页面开头加上这句,则页面中无法保存中文字符,并提示:中文字符在不能被iso-8859-1字符集mapped,这是由于默认情况下,JSP是用iso-8859-1来编码的,可以在Window->Preferences->General->Content Type选项下,在右边的窗口选择Text->Jsp,然后在下面的Default Encoding由默认的iso-8859-1改为GBK,然后点击update即可解决。

本栏目更多精彩内容:http://www.bianceng.cn/webkf/JSP/

然而这种方式会带来一些问题:由于这一句在其他文件include该文件的时候不能被继承,所以include它的文件也需要在文件开头加上这句话,此时如果用的是pageEncoding="gbk"则会出现问题。类似于org.apache.jasper.JasperException: /top.jsp(1,1) Page directive: illegal to have multiple occurrences of contentType with different values (old: text/html;charset=GBK, new: text/html;charset=gbk).

类似地,如果两个文件一个用的是gbk,一个用的是gb2312也会出现问题。

另一种更好的解决方式为:

在项目的web.xml中添加以下片段:

<jsp-config>

<jsp-property-group>

<description>

Special property group for JSP Configuration JSP example.

</description>

<display-name>JSPConfiguration</display-name>

<url-pattern>*.jsp</url-pattern>

<el-ignored>true</el-ignored>

<page-encoding>GBK</page-encoding>

<scripting-invalid>false</scripting-invalid>

<include-prelude></include-prelude>

<include-coda></include-coda>

</jsp-property-group>

<jsp-property-group>

<description>

Special property group for JSP Configuration JSP example.

</description>

<display-name>JSPConfiguration</display-name>

<url-pattern>*.html</url-pattern>

<el-ignored>true</el-ignored>

<page-encoding>GBK</page-encoding>

<scripting-invalid>false</scripting-invalid>

<include-prelude></include-prelude>

<include-coda></include-coda>

</jsp-property-group>

</jsp-config>

2