如何将对象从servlet传递到JSP? [英] How can I pass object from servlet to JSP?

查看:115
本文介绍了如何将对象从servlet传递到JSP?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
如何从Servlet传递对象到调用的JSP

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端使用了以下代码

I have used the following code in the servlet side

request.setAttribute("ID", "MyID");
request.setAttribute("Name", "MyName");
RequestDispatcher dispatcher = request.getRequestDispatcher("MangeNotifications.jsp");  
if (dispatcher != null){  
dispatcher.forward(request, response);  
}

和此代码在JSP端

    <td><%out.println(request.getAttribute("ID"));%> </td>
    <td><%out.println(request.getAttribute("Name"));%> </td>

我在JSP页面中得到空结果

I get null results in the JSP Page

推荐答案

我认为不需要servlet的服务(doGet/doPost)方法.为了访问JSP中的 request 属性,您必须通过url-pattern请求servlet,这样就不必使用会话.

I think servlet's service (doGet/doPost) method is not requested. In order to access request attributes in JSPs, you must request the servlet via url-pattern and that way you don't have to use session.

SampleServlet.java

SampleServlet.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(我认为该文件位于Web上下文的根目录中)

MangeNotifications.jsp (I presume that this file is located at root of web-context)

<br/>ID : ${ID}     Or scriptlets  <%-- <%=request.getAttribute("ID")%>  --%> 
<br/>ID : ${Name}

现在打开浏览器并像这样设置请求网址,

Now open the browser and set request url somersetting like this,

http://localhost:8084/your_context/sample

这篇关于如何将对象从servlet传递到JSP?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆