簡體   English   中英

將值從servlet傳遞到jsp頁面

[英]passing value from servlet to jsp page

EditDeleteServlet-這是我列出所有學生的servlet。 這是代碼:

Student sbean = new Student();
            EditDeleteDAO sDAO = new EditDeleteDAO();

            String command = request.getParameter("command");
            PrintWriter out = response.getWriter();
            out.print(command);

            try{
                if(command.equals("Submit")) 
                {
                    String id=request.getParameter("id");
                    String studName=request.getParameter("studName");
                    String icNum=request.getParameter("icNum");
                    String matrixID=request.getParameter("matrixID");
                    String contactNum=request.getParameter("contactNum");
                    String email=request.getParameter("email");
                    String course=request.getParameter("course");
                    sbean.setId(Integer.parseInt(id));
                    sbean.setStudName(studName);
                    sbean.setICNum(icNum);
                    sbean.setMatrixID(Integer.parseInt(matrixID));
                    sbean.setContactNum(Integer.parseInt(contactNum));
                    sbean.setEmail(email);
                    sbean.setCourse(course);
                    EditDeleteDAO.insertDetails(sbean);
                    List<Student> list = sDAO.getAllDetails();
                    if(list!=null)
                    {
                        request.setAttribute("list",list);
                        RequestDispatcher rd = request.getRequestDispatcher("/studListing.jsp");
                        rd.forward(request, response);
                    }
                }

studListing.jsp-這是我的jsp頁面,我想在此處顯示數據

list = request.getAttribute(“ list”); %>

您已使用名為listkey添加到您的請求list

request.setAttribute("list",list);

因此您必須在JSP中使用此名稱來檢索它

還可以在您的JSP中使用EL而不是Java

<c:foreach items="${list}" var="student">
    ${student.studName}
<c:forEach>

您必須使用request.setAttribute()添加jsp頁面可以使用的鍵值對。 在您的代碼中:

request.setAttribute("list", list);

然后,您可以像這樣在jsp中檢索屬性:

<% List<Student> list = request.getAttribute("list"); %> // Note that the name of the attribute is "list"

但是,如果要遍歷列表,建議您使用EL:

<c:forEach items="${list}" var="listItem">
    <c:out value="${listItem.eid}"/>
</c:forEach>

本質上,JSP和Servlet共享相同的空間,實際上JSP在后端被編譯為Servlet,並且它們共享相同的HttpServletRequest和HttpServletResponse,因此您可以在request中設置Servlet中的值,並使用相同的request對象在JSP中獲取。

例如在Servlet內部,request.setAttribute(“ list”,list);

在JSP中,request.getAttribute(“ list”);

另外,您也可以使用會話對象在HttpSession中共享該對象。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM