在一个编码为utf-8的页面中,使用<jsp:include>或者<%@ include %>包含另一个.jsp/.html文件时,被包含后就会遇到乱码问题。解决的办法是,在每个被包含的页面开始加上下面一行<% page contentType="text/html;charset=utf-8" %>这个方法可以解决被包含页面是jsp页面时的中文乱码问题。当被包含页面是html文件时也需要将编码改成utf-8才可以。
今天在网上找到了另一种方便的做法,只需要改web.xml就可以了,示例代码如下:
<jsp-config>
<jsp-property-group>
<description>jsp encoding example</description>
<display-name>JSPConfiguration</display-name>
<url-pattern>*.jsp</url-pattern>
<el-ignored>true</el-ignored>
<page-encoding>utf-8</page-encoding>
<scripting-invalid>false</scripting-invalid>
<include-prelude></include-prelude>
<include-coda></include-coda>
</jsp-property-group>
<jsp-property-group>
<description>html encoding example</description>
<display-name>JSPConfiguration</display-name>
<url-pattern>*.html</url-pattern>
<el-ignored>true</el-ignored>
<page-encoding>utf-8</page-encoding>
<scripting-invalid>false</scripting-invalid>
<include-prelude></include-prelude>
<include-coda></include-coda>
</jsp-property-group>
</jsp-config>
说明:<jsp-config>里的定义,就是通知当前应用服务器,当前应用系统下,所有的 .jsp, .html 文件,若是没有定义contentType="text/html;charset=utf-8" 时,就会采用预设的 "utf-8" 字符集去处理,如此,就不需要在每个被包含的页面的第一行加上 contentType="text/html;charset=utf-8" 了。
1.<description>:设定的说明;
2.<display-name>:设定名称;
3.<url-pattern>:设定值所影响的范围,如:/CH2 或 /*.jsp;
4.<el-ignored>:若为true,表示不支持EL 语法;
5.<scripting-invalid>:若为true,表示不支持<% scripting %>语法;
6.<page-encoding>:设定JSP 网页的编码;
7.<include-prelude>:设置JSP 网页的抬头,扩展名为.jspf;
8.<include-coda>:设置JSP 网页的结尾,扩展名为.jspf。