getAttribute表示从request范围取得设置的属性,所以必须通过setAttribute设置属性,此操作的对象类型为Obeject。
getParameter表示接收页面所提交的参数,如:表单提交的参数,URL重写(就是xxx?id=1中,id传的参数),因此这
个没有setParameter方法,而且接收参数的返回值类型为String类型。
HttpServletRequest类既有getAttribute()方法,也有getParameter()方法,这两个方法的区别如下:
(1)HttpServletRequest类有setAttribute()方法,没有setParameter()方法
(2)当两个WEB组件之间为链接关系时,被链接的组件通过getParameter()方法来获得请求参数,例:
假定login.jsp和success.jsp之间为链接关系,login.jsp有如下代码:
<from name = "hello" method="post" action="success.jsp">
请输入用户名:<input type="text" name="username">
<input type="submit" name="Submit" value="提交"></from>
在success.jsp中通过request.getParameter("username")方法来获得请求参数username:
<% String username=request.getParameter("username");%>
(3)当;两个web组件之间为转发关系时,转发目标组件通过getAttribute()方法和转发源组件共享request范围内的数据。假定login.jsp和hello.jsp之间为转发关系。login.jsp希望向hello.jsp传递当前的用户名字,如何传递这个数据呢?先在login.jsp中调用setAttribute()方法:
<%String username=request.getParameter("username");
request.setAttribute("username",username);
%>
<jsp:forword page="hello.jsp"/>
在hello.jsp中通过getAttribute()方法获取用户名字:
<% String username = (String) request.getAttribute("usrname");%>
Hello:<%=username%>
从更深的层次考虑,request.getParameter()方法传递的数据,会从web客户端传递到web服务器端,代表HTTP请求
数据,request.getParameter()方法返回String类型的数据。
request.setAttribute()和getAttribute()方法传递的数据只会在web容器的内部,在具有转发关系的web组件之间共享。
这两个方法能够设置Object类型的共享数据。
request.getParamter()方法取得是通过容器的实现来取得类似post,get方式传入的数据;
request.setAttribute()和getAttribute()只是容器内部流转,仅仅是请求处理阶段。
getAttribute是返回对象,getParameter返回字符串。
request.getAttribute()方法返回request范围内存在的对象,而request.getParameter()方法是获取http提交过来的数据。