如何将Object从servlet传递给调用JSP

use*_*657 5 java jsp servlets

如何将Object从servlet传递给调用JSP.

我有一个JSP调用servlet.从这个servlet,我正在设置viewBean的属性.现在,我想在JSP页面上从Servlet获取此属性值集.

如何使用Servlet在JSP上提供此ViewBean对象.

Nan*_*ale 16

将对象放在会话中或请求在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
Run Code Online (Sandbox Code Playgroud)

你可以在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} 
Run Code Online (Sandbox Code Playgroud)

或者使用带有代码的scriptlet读取它:

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


KD.*_*KD. 0

像这样的东西应该有效

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

        RequestDispatcher rd = getServletContext().getRequestDispatcher(yourJSP);
        rd.forward(request, response);
Run Code Online (Sandbox Code Playgroud)