java 如何将对象从 servlet 传递到 JSP?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12143123/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I pass object from servlet to JSP?
提问by user1576197
Possible Duplicate:
How to pass an Object from the servlet to the calling JSP
可能的重复:
如何将对象从 servlet 传递到调用 JSP
How can I pass object from servlet to JSP?
如何将对象从 servlet 传递到 JSP?
I have used the following code in the servlet side
我在servlet端使用了以下代码
request.setAttribute("ID", "MyID");
request.setAttribute("Name", "MyName");
RequestDispatcher dispatcher = request.getRequestDispatcher("MangeNotifications.jsp");
if (dispatcher != null){
dispatcher.forward(request, response);
}
and this code in JSP side
和 JSP 端的这段代码
<td><%out.println(request.getAttribute("ID"));%> </td>
<td><%out.println(request.getAttribute("Name"));%> </td>
I get null results in the JSP Page
我在 JSP 页面中得到空结果
采纳答案by adatapost
I think servlet's service (doGet/doPost) method is not requested. In order to access requestattributes in JSPs, you mustrequest the servlet
via url-pattern
and that way you don't have to use session.
我认为 servlet 的服务 (doGet/doPost) 方法没有被请求。为了访问JSP 中的请求属性,您必须请求servlet
通过url-pattern
,这样您就不必使用会话。
SampleServlet.java
示例Servlet.java
@WebServlet(name = "SampleServlet", urlPatterns = {"/sample"})
public class SampleServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setAttribute("ID", "MyID");
request.setAttribute("Name", "MyName");
RequestDispatcher dispatcher = request
.getRequestDispatcher("/MangeNotifications.jsp");
if (dispatcher != null){
dispatcher.forward(request, response);
}
}
}
MangeNotifications.jsp (I presume that this file is located at root of web-context)
MangeNotifications.jsp(我假设这个文件位于 web-context 的根目录)
<br/>ID : ${ID} Or scriptlets <%-- <%=request.getAttribute("ID")%> --%>
<br/>ID : ${Name}
Now open the browser and set request url somersetting like this,
现在打开浏览器并像这样设置请求 url somersetting,
http://localhost:8084/your_context/sample
回答by kgautron
Put it in the session (session.setAttribute("foo", bar);
) or in the request; then it is accessible from the JSP through the name you gave it ("foo" in my example).
将其放入会话( session.setAttribute("foo", bar);
) 或请求中;然后它可以通过您给它的名称(在我的示例中为“foo”)从 JSP 访问。
EDIT :
Use simply <%= ID %>
and <%= Name %>
instead of <%out.println.....%>
. Note the =
at the beginning of the java tag, indicating to output the result of the expression.
编辑:简单地使用<%= ID %>
和<%= Name %>
代替<%out.println.....%>
。注意=
java标签开头的,表示要输出表达式的结果。