request.setAttribute傳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>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章