现在的位置: 首页 > 综合 > 正文

JSP页面之间参数传递显示

2013年10月14日 ⁄ 综合 ⁄ 共 1572字 ⁄ 字号 评论关闭

 JSP的不同页面之间常常需要传递参数,如果参数的值全是数字和字母组成的,那么如果没有语法错误,一般都能正常显示.如果参数的值中含有汉字,既使没有语法错误,参数的值也可能无法正确显示,这往往都是page的pageEncoding属性和 contentType属性设置不当造成的.

现介绍我经常用的两种方法

      1、在<%@ %>中如下声明:
<%@ page 
        contentType = "text/html;charset = GB2312"

       .........
%>
这样用request获取参数的值时,汉字可以正常显示

如下例所示:

//SessionE1.jsp

<%@ page
 language="java"
 contentType = "text/html; charset = GB2312"
%>
<html>
 <head>
  <title>Session1.jsp</title>
 </head>
 <body>
  <form method = "post" action = "SessionE2.jsp">
   请输入姓名:<input type = "text" name = "userName">
   <input type = "submit" value = "提交">
  </form>
 </body>
</html>

//SessionE2.jsp

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

<html>
 <head>
  <title>SessionE2.jsp</title>
 </head>
 <body>
  <%! String name = ""; %>
  <p>
  <%
   name = request.getParameter("userName");
   %>
   </p>
   您的姓名是:<%= name %><br>
  
 </body>
</html>
  

      2、在<%@ %>中如下声明:
<%@ page 
        pageEncoding="GB2312"
       contentType = "text/html"

%>
这样request获取参数的值时,汉字不能正常显示,必须经过转换才能正常显示
如下例所示:

//SessionE1.jsp

<%@ page
 language="java"
 pageEncoding="GB2312"
 contentType = "text/html"
%>
<html>
 <head>
  <title>Session1.jsp</title>
 </head>
 <body>
  <form method = "post" action = "SessionE2.jsp">
   请输入姓名:<input type = "text" name = "userName">
   <input type = "submit" value = "提交">
  </form>
 </body>
</html>

//SessionE2.jsp

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

<html>
 <head>
  <title>SessionE2.jsp</title>
 </head>
 <body>
  <%! String name = ""; %>
  <p>
  <%
   name = request.getParameter("userName");
   name = new String(name.getBytes("ISO-8859-1"),"GBK");
   %>
   </p>
   您的姓名是:<%= name %><br>
  
 </body>
</html>
  
注:

    本文例子均在MyEclipse6.0下调试通过。

抱歉!评论已关闭.