日期:2014-05-18  浏览次数:20723 次

求解request.getAttribute()、急疯了!
对于request.getAttribute、request.setAttribute,的用法很困惑!
下面是一个简单的尝试,但是值的传递不能成功。

///*     test.jsp     *///

<%@   page   language= "java "   import= "java.util.* "   pageEncoding= "gbk "   %>
<html>
<head>  
<title>   Request.html </title>
</head>  
<body>
<form   action= "Request.jsp "   method= "post ">  
Name: <input   type= "text "   name= "Name "   size= "20 "   maxlength= "20 "> <br>  
<%
String   attr   =   new   String( "about   setAttribute. ");
request.setAttribute( "data ",   attr);
%>
<input   type= "submit "   value= "传送 ">  
</form>  
</body>  
</html>

///*   Request.jsp       *///

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

<html>  
<head>  
<title>   Request.jsp </title>
</head>  
<body>  
<h2> test </h2>  
getParameter( "Name "): <%=   request.getParameter( "Name ")   %> <br>
<br>
<%
String   data   =   (String)request.getAttribute( "data ");
%>
the   attribute: <%=data   %>
<br>
</body>  
</html>

///*输出结果*///

test
getParameter( "Name "):something

the   attribute:null  

为什么没法传输attr的值。请求高人解救
帮忙解答一下request.get/getAttribute的使用。万分感谢!




------解决方案--------------------
你request.setAttribute( "data ", attr);这样,只有当前请求才有效.
比如用forward(..)这样,在下一个页面,才可以访问...
而你这里用在对第二个页面的请求是一个新的请求.因为它是表单新提交的请求.
所以第二个页面访问不到属性 data,
你这样能用session.setAttribute()可以访问

------解决方案--------------------
唉...很多人刚开始都会这样失败的!!!!

首先你在URL里边输入test.jsp 的时候,服务器里边就会产生一个request,开始编译你的JSP文件,在这个过程,你在前面的某一处用了setAttribute();在后边你可以用request.getAttribute()取到.就像下边这样:
<%@ page language= "java " import= "java.util.* " pageEncoding= "gbk " %>
<html>
<head>
<title> Request.html </title>
</head>
<body>
<form action= "Request.jsp " method= "post ">
Name: <input type= "text " name= "Name " size= "20 " maxlength= "20 "> <br/>
<%
String attr = new String( "about setAttribute. ");

request.setAttribute( "data ", attr);========================> //前
%>
<input type= "submit " value= "传送 ">
</form>

<%

out.println(request.getAttribute( "data "));========================> 后


%>
</body>
</html>
最后服务完成了编译的工作,完成生成了HTML代码,并把它们返回给浏览器去执行,服务器上的那个request已经不存在,所有与它一起的数据都没有了.

返回给客户端后,我们就看到了一个表单,然后点击 "传送 ",再次访问服务上的Request.jsp,这时候又产生了一个新的request对像,但以前的那个数据已经不存在了,因为是不同的request了.所以你在Request.jsp里边再取它,那是当然取不到的了.setAttribute()是针对同