簡體   English   中英

如何將對象從servlet傳遞到調用的JSP

[英]How to pass an Object from the servlet to the calling JSP

如何將對象從servlet傳遞到調用的JSP。

我有一個JSP調用servlet。 從這個servlet,我正在設置viewBean的屬性。 現在,我想從JSP頁面上的Servlet獲取此屬性值的設置。

如何使該ViewBean對象在Servlet的JSP上可用。

將對象放入會話或servlet中的請求中,如:

String shared = "shared";
request.setAttribute("sharedId", shared); // add to request
request.getSession().setAttribute("sharedId", shared); // add to session
this.getServletConfig().getServletContext().setAttribute("sharedId", shared); // add to application context

您可以像這樣在jsp中閱讀:

<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<body>
<cut value= "${shared}"/>
<cut value= "${requestScope.shared}"/>
<cut value= "${requestScope.request.shared}"/>
${shared} 

或使用帶有代碼的scriptlet讀取它:

<%
 String shared = (String)request.getAttribute("sharedId");
 String shared1 = (String)request.getSession().getAttribute("sharedId");
 String shared2 = (String)this.getServletConfig().getServletContext().getAttribute("sharedId");
%>

好吧,首先,您需要設置值,以便可以從頁面訪問它,例如:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class MyServlet extends HttpServlet {
  public void doGet(HttpServletRequest request, HttpServletResponse response) {
    // Do some work.
    Person value = new Person("Matthew", "Abbott";

    request.setAttribute("person", person);

    // Forward to to the JSP file.
    request.getRequestDispatcher("showValue.jsp").forward(request, response);
  }
}

接下來,您可以使用表達式語言訪問值的屬性:

<!DOCTYPE html>
<html>
  <head>
    <title>${person.forename} ${person.surname}</title>
  </head>
  <body>
    <h1>Hello ${person.forename}!!!</h2>
  </body>
</html>

這樣的事情應該工作

request.setParameter("nameOfmyObjectParam",MyObject); //or request.setAttribute
String yourJSP = "/WEB-INF/pages/yourJSP.jsp";

        RequestDispatcher rd = getServletContext().getRequestDispatcher(yourJSP);
        rd.forward(request, response);

使用Servlet API,將Bean設置為Servlet中的request屬性-

request.setAttribute("viewBean", viewBean);

並使用EL在JSP中檢索(使用)它,如下所示-

${requestScope.viewBean}

在Servlet的session屬性中添加該ViewBean對象。 並在jsp中獲取該變量。

在servlet中

ViewBean viewbwanObject =新的ViewBean()session.setAttribyte(“ obj”,vi);

在jsp中。

<%

ViewBean v =(ViewBean)session.getAttribute(“ obj”)%>

暫無
暫無

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

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