学习本文章前需知getRequestDispatcher的使用
前言
一、setAttribute是什么?
二、使用步骤示例
1.建ArrayList和HashMap
2. 使用setAttribute将al和hm对象绑定并传出
3.目标jsp取值
4.示例输出
三.全部代码
总结
前言
作为个人学习记录,有误和不清楚地方可评论指正,互相学习共同进步!谢谢!
提示:以下是本篇文章正文内容
一、setAttribute是什么?
setAttribute(String name, Object o)他是传递参数的一种方式,特别是对一些特殊数据,属于页面之间的传值,从a.jsp到b.jsp一次传递,之后这个request就会失去他的作用范围,再传就要重新设一个request.setAttribute()。
二、使用步骤示例
1.建ArrayList和HashMap
ArrayList al=new ArrayList();al.add("zs");al.add("ls");al.add("ww");HashMap hm=new HashMap();hm.put("zs", 21);hm.put("ls", 18);hm.put("ww", 18);
2. 使用setAttribute将al和hm对象绑定并传出
request.setAttribute("name", al);
request.setAttribute("nameyear", hm);
3.目标jsp取值
ArrayList a=(ArrayList)request.getAttribute("name");//取值放到了a和h中
HashMap h=(HashMap)request.getAttribute("nameyear");
4.示例输出
ArrayList a=(ArrayList)request.getAttribute("name");HashMap h=(HashMap)request.getAttribute("nameyear");out.print("for循环输出ArrayList:"+"
");for(int i=0;i");}out.print("迭代器输出ArrayList:"+"
");Iterator it1=a.iterator();while(it1.hasNext()){out.print(it1.next()+"
");}out.print("foreach输出ArrayList:"+"
");for (Object i : h.keySet()) {out.print( i + " 的年龄是:" + h.get(i)+"
");}out.print("迭代器输出HashMap:"+"
");Set st=h.keySet();Iterator it2=st.iterator();while(it2.hasNext()){String s=(String)it2.next();out.print(s + " 的年龄是:" + h.get(s)+"
");}
三.全部代码
传出代码:
<%@page language="java" contentType="text/html; charset=utf-8"pageEncoding="utf-8" import="java.util.*"%>
Insert title here
<%ArrayList al=new ArrayList();al.add("zs");al.add("ls");al.add("ww");HashMap hm=new HashMap();hm.put("zs", 21);hm.put("ls", 18);hm.put("ww", 18);request.setAttribute("name", al);request.setAttribute("nameyear", hm);RequestDispatcher rd=request.getRequestDispatcher("neizhiduixiang.jsp");rd.forward(request,response);
%>
传入代码(foreach和迭代器遍历输出):
<%@ page language="java" contentType="text/html; charset=utf-8"pageEncoding="utf-8" import="java.util.*"%>
Insert title here
<%ArrayList a=(ArrayList)request.getAttribute("name");HashMap h=(HashMap)request.getAttribute("nameyear");out.print("for循环输出ArrayList:"+"
");for(int i=0;i");}out.print("迭代器输出ArrayList:"+"
");Iterator it1=a.iterator();while(it1.hasNext()){out.print(it1.next()+"
");}out.print("foreach输出ArrayList:"+"
");for (Object i : h.keySet()) {out.print( i + " 的年龄是:" + h.get(i)+"
");}out.print("迭代器输出HashMap:"+"
");Set st=h.keySet();//ArrayList和HashMap传入类型为Object类Iterator it2=st.iterator();while(it2.hasNext()){String s=(String)it2.next();out.print(s + " 的年龄是:" + h.get(s)+"
");}
%>
总结
setAttribute和getAttribute是页面传值的一种方法