基于request.getAttribute与request.getParameter的区别详解
2016-06-23 18:33
447 查看
HttpServletRequest类既有getAttribute()方法,也有getParameter()方法,这两个方法有以下区别:
1、HttpServletRequest类有setAttribute()方法,而没有setParameter()方法;
2、当两个Web组件之间为链接关系时,被链接的组件通过getParameter()方法来获得请求参数;
例如,假定welcome.jsp和authenticate.jsp之间为链接关系,welcome.jsp中有以下代码:
代码如下:
<a href="authenticate.jsp?username=qianyunlai.com">authenticate.jsp </a>
//或者:
<form name="form1" method="post" action="authenticate.jsp">
请输入用户姓名:<input type="text" name="username">
<input type="submit" name="Submit" value="提交">
</form>
在authenticate.jsp中通过request.getParameter(“username”)方法来获得请求参数username:
<% String username=request.getParameter("username"); %>
3、当两个Web组件之间为转发关系时,转发目标组件通过getAttribute()方法来和转发源组件共享request范围内的数据。
假定authenticate.jsp和hello.jsp之间为转发关系。authenticate.jsp希望向hello.jsp传递当前的用户名字,如何传递这一数据呢?先在authenticate.jsp中调用setAttribute()方法:
代码如下:
<%
String username=request.getParameter("username");
request.setAttribute("username",username);
%>
<jsp:forward page="hello.jsp" />
在hello.jsp中通过getAttribute()方法获得用户名字:
代码如下:
<% String username=(String)request.getAttribute("username"); %>
Hello: <%=username %>
4、request.getAttribute 返回的是Object,request.getParameter 返回的是String。
1、HttpServletRequest类有setAttribute()方法,而没有setParameter()方法;
2、当两个Web组件之间为链接关系时,被链接的组件通过getParameter()方法来获得请求参数;
例如,假定welcome.jsp和authenticate.jsp之间为链接关系,welcome.jsp中有以下代码:
代码如下:
<a href="authenticate.jsp?username=qianyunlai.com">authenticate.jsp </a>
//或者:
<form name="form1" method="post" action="authenticate.jsp">
请输入用户姓名:<input type="text" name="username">
<input type="submit" name="Submit" value="提交">
</form>
在authenticate.jsp中通过request.getParameter(“username”)方法来获得请求参数username:
<% String username=request.getParameter("username"); %>
3、当两个Web组件之间为转发关系时,转发目标组件通过getAttribute()方法来和转发源组件共享request范围内的数据。
假定authenticate.jsp和hello.jsp之间为转发关系。authenticate.jsp希望向hello.jsp传递当前的用户名字,如何传递这一数据呢?先在authenticate.jsp中调用setAttribute()方法:
代码如下:
<%
String username=request.getParameter("username");
request.setAttribute("username",username);
%>
<jsp:forward page="hello.jsp" />
在hello.jsp中通过getAttribute()方法获得用户名字:
代码如下:
<% String username=(String)request.getAttribute("username"); %>
Hello: <%=username %>
4、request.getAttribute 返回的是Object,request.getParameter 返回的是String。
相关文章推荐
- Android高阶UI之一个实用的多条件筛选菜单
- 大三学生暑假到传智播客培训UI设计,不料竟被坑
- 传智播客UI设计结束了我脑袋别在裤腰带上的生活
- shareSDK自定义分享界面UI
- DNS测试工具querperf
- log4j:ERROR setFile(null,true) call failed.
- iOS动态改变UITableView的tableViewHeader的高度
- 循环结构中break和continue的替代方法(Repetition without break and continue statement)
- ORM issue
- NGUI战斗飘字及界面优化
- 2.7、Android Studio使用翻译编辑器本地化UI
- 2.7、Android Studio使用翻译编辑器本地化UI
- UILongPressGestureRecognizer长按手势
- Count Numbers with Unique Digits
- niagara编译错误:using type arguments to access generic types requires the use of "-source 1.5"
- 给UICollectionViewCell绑定手势 long press举例
- button,input,html 对应的value,innerText,innerHTML 关系
- NGUI OnChange Event
- easyui_动态添加隐藏toolbar按钮
- easyui numberbox不可编辑