【问题标题】:pagecontext request dispatcher servletspagecontext 请求调度程序 servlet
【发布时间】:2013-12-23 08:35:51
【问题描述】:

我正在尝试使用“RequestDispatcher”转发请求。我有 JSP pageContext 对象。 我尝试使用以下代码将我的请求转发到我的 servlet“MyServlet”。我在请求中设置了一些属性并转发了它。但我无法在我的 servlet 类中访问这些变量。

我的代码:

pageContext.getRequest().setAttribute("AValue","A");
pageContext.getRequest().setAttribute("BValue", "B");

ServletContext context= pageContext.getServletContext();
RequestDispatcher rd= context.getRequestDispatcher("/MyServlet");
rd.forward(pageContext.getRequest(),pageContext.getResponse());

帮帮我!! 提前致谢。

【问题讨论】:

  • 你能显示代码 MyServlet 中从请求中获取属性的代码是什么吗?上面写的代码和问题是在jsp里面吗?如果它在 jsp 中,为什么不简单地正确 request.setAttribute("AValue","A") 而不是 pageContext.getRequest().setAttribute("AValue","A");因为request是jsp中的一个隐式对象。
  • 感谢您的回复。我在我的一个服务器代码中使用此代码。从我的自定义标记库类中,我得到了这个 pageContext 对象并将其传递给我的服务器类。在我的服务器类中,基于某些条件,我将请求转发到各种 servlet。获取属性值的代码: String aValue = (String) request.getAttribute("AValue");

标签: jsp servlets request dispatcher pagecontext


【解决方案1】:

当从 JSP 页面动态包含或转发到 servlet 时,您可以使用 jsp:param 标记将数据传递给 servlet。

jsp:param 标记用于jsp:includejsp:forward 标记。

<jsp:include page="/servlet/MyServlet" flush="true" >
  <jsp:param name="AValue" value="A" />
  <jsp:param name="BValue" value="B" />
</jsp:include>

Here is source docs

十年来,确实非常不鼓励在 JSP 中使用 scriptlet &lt;% %&gt;
How to avoid Java Code in JSP-Files?

【讨论】:

  • 感谢您的回复。我没有直接从我的 JSP 转发我的请求。我需要通过 RequestDispatcher 转发我的请求。有没有其他办法?
  • 我试过下面的代码,pageContext.getRequest().setAttribute("check","checkValue"); RequestDispatcher rd = pageContext.getRequest().getRequestDispatcher("/MyServlet"); rd.forward(pageContext.getRequest(),pageContext.getResponse());在我的 servlet 类中, String v = (String) request.getAttribute("check"); System.out.println("校验值:" +v);它仍然在打印空值...知道吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-07
  • 2013-05-19
  • 1970-01-01
  • 2014-08-30
  • 1970-01-01
相关资源
最近更新 更多