如何从servlet传递对象到调用JSP页面

5
如何从servlet传递对象到调用的JSP页面。
我有一个JSP调用一个servlet。从这个servlet中,我正在设置一个viewBean的属性。 现在,我想从Servlet上获取在JSP页面上设置的属性值。
如何从servlet将ViewBean对象提供给JSP使用。

请查看http://stackoverflow.com/a/12033142/142822。 - KV Prajapati
5个回答

17

将对象放置在servlet的session或request中,例如:

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} 

或者使用带有以下代码的脚本方式:

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

我对使用Java servlet进行Web开发还比较新。然而,我想引起第二个代码块的注意。我确信这里有一个错误。你不能直接调用在Java servlet中定义的变量,例如'shared'。这是因为servlet依赖反射来查找它们关联的变量/值。再次强调,我的分析可能有误,但我认为这样做不会起作用。 - Matthew

4
首先,你需要设置值,以便从页面中访问它,例如:
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>

0
将ViewBean对象添加到servlet的会话属性中。并在jsp中获取该变量。
在servlet中:
ViewBean viewbwanObject = new ViewBean(); session.setAttribute("obj", vi);
在jsp中:
<%

ViewBean v = (ViewBean) session.getAttribute("obj")

视图Bean v =(ViewBean)session.getAttribute(“obj”)


0

类似这样的代码应该可以运行

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

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

0

使用Servlet API将bean设置为请求属性,方法如下 -

request.setAttribute("viewBean", viewBean);

然后使用EL在JSP中检索(使用)它,如下所示 -

${requestScope.viewBean}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接