繁体   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