一、bean封装
public class Person { private String name="张三"; private int age; private Date birthday; private Address addr; public Person() { super(); } public Person(String name) { super(); this.name = name; } public Address getAddr() { return addr; } public void setAddr(Address addr) { this.addr = addr; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
public class Address { private String city; public String getCity() { return city; } public void setCity(String city) { this.city = city; } }
二、el表达式显示(模拟数据库)
<body> <!-- 普通方式传递数据 --> <% String data="abcd"; request.setAttribute("data",data); %> ${data} <%-- pageContext.findAttribute("data") --%> </br> <!-- 数据从bean带过来 --> <% Person p=new Person(); p.setName("张三"); request.setAttribute("person",p); %> ${person.name} </br> <!-- 数据从复杂bean带过来 --> <% Person p1=new Person(); Address a=new Address(); a.setCity("上海"); p1.setAddr(a); request.setAttribute("p1",p1); %> ${p1.addr.city} </br> <!-- 产生多个数据 --> <% List list=new ArrayList(); list.add(new Person("aa")); list.add(new Person("bb")); list.add(new Person("cc")); request.setAttribute("list",list); %> ${list[1].name} </br> <% Map map=new HashMap(); map.put("aaa",new Person("a")); map.put("bbb",new Person("b")); map.put("ccc",new Person("c")); map.put("ddd",new Person("d")); request.setAttribute("map",map); %> ${map.aaa.name} </br> <!-- 获取当前web应用的名字 --> ${pageContext.request.contextPath } <a href="${pageContext.request.contextPath }/2.jsp">点击我</a> </body>
三、使用jstl+el完成集合迭代
在页面中使用JSTL标签需要完成的两个步骤:
1)导入jstl.jar和standard.jar这两个jar包
2)在JSP页面中使用<%@tablib url="" prefix="" %>元素导入标签库 (uri standard.jar -> meta-inf -> c.tlduri standard.jar -> meta-inf -> c.tld)
JSTL标签库中常用标签:
<c:foreach var="" items="">
<c:if test="">
<body> <% List list=new ArrayList(); list.add(new Person("aa")); list.add(new Person("bb")); list.add(new Person("cc")); request.setAttribute("list",list); %> <c:forEach var="person" items="${list}"> ${person.name }</br> </c:forEach> </br> <% Map map=new HashMap(); map.put("aaa",new Person("aaa")); map.put("bbb",new Person("bbb")); map.put("ccc",new Person("ccc")); map.put("ddd",new Person("ddd")); request.setAttribute("map",map); %> <c:forEach items="${map}" var="entry"> ${entry.key}:${entry.value.name} </br> </c:forEach> </br> <!-- 代表用户登陆了 --> <c:if test="${user!=null}"> 欢迎您:${user.username} </c:if> <c:if test="${user=null}"> 用户名:<input type="text"/> 密 码:<input type="password"/> </c:if> </body>
时间: 2024-11-05 10:20:08