用於解決Action中request.setAttribute("list",list)
由於我用的是struts框架,就拿整個項目介紹:
1.首先把jstl的兩個常用包jstl.jar、standard.jar加載到環境中
2.Action代碼:(整個過程不需要了解,這兒方法就是返回一個封裝Students對象的list,然後request.setAttribute("list",list)起來)
public ActionForward selectStudent(ActionMapping mapping,ActionForm form,
HttpServletRequest request,HttpServletResponse response) {
StudentForm studentForm = (StudentForm) form;
DBConnection dbconn = new DBConnection();
Connection conn = dbconn.getConnection();
StudentServiceFactory serviceFactory = new StudentServiceFactory();
List list = serviceFactory.getStudentService().selectStudent(conn);
request.setAttribute("list",list);
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
return mapping.findForward("show");
}
3.show.jsp頁面:
<%@ page language="java" pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="c" %>//這三句很重要
<%@ taglib uri="http://jakarta.apache.org/struts/tags-bean" prefix="bean"%>
<%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'show.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
查詢結果如下: <br>
<table>
<tr>
<td>ID</td>
<td>姓名</td>
</tr>
<c:forEach items="${list}" var="student">// items為list的一個迭代器,list為Action中傳遞過來的list,student為Student類對象
<tr>
<td>${student.id }</td>//輸出student的id屬性
<td>${student.name }</td>//輸出student的name屬性
</tr>
</c:forEach>
<logic:iterate id="li" name="list" type="vo.Student">//id為自定義的名字,name為Action中傳過來的list,type為實體類,包括完整路徑,這裡是vo.Student
<tr>
<td><bean:write name="li" property="id"/></td>//name為邏輯名,和logic:iterate id="li"中的id對應,property為實體類中真正的屬性
<td><bean:write name="li" property="name"/></td>
<td><a href="student.do?method=deleteStudent&id=<bean:write name="li" property="id"/>">刪除</a></td>
</tr>
</logic:iterate>
</table>
<a href="student.jsp">返回</a>
</body>
</html>
在JSP頁面引入Struts標簽庫的時候有所不同:
struts1.3的為:
<%@ taglib uri="http://jakarta.apache.org/struts/tags-bean" prefix="bean"%>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-html" prefix="html"%>
<%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>或者<%@ taglib uri="http://struts.apache.org/tags-logic" prefix="logic" %>