【问题标题】:How to send parameters from a servlet如何从 servlet 发送参数
【发布时间】:2009-09-10 18:58:47
【问题描述】:

我正在尝试使用 RequestDispatcher 从 servlet 发送参数。

这是我的 servlet 代码:

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

 String station = request.getParameter("station");
 String insDate = request.getParameter("insDate");

 //test line
 String test = "/response2.jsp?myStation=5";

 RequestDispatcher rd;
 if (station.isEmpty()) {
     rd = getServletContext().getRequestDispatcher("/response1.jsp");

 } else {
     rd = getServletContext().getRequestDispatcher(test);
 }

 rd.forward(request, response);

} 

这是我的 jsp,带有读取值的代码 - 但是它显示为 null。

    <h1>response 2</h1>
    <p>
        <%=request.getAttribute("myStation")  %>
    </p>

感谢您的任何建议。 更环保

【问题讨论】:

  • RequestDispatcher 不用于读取参数。因此我编辑了你的帖子。

标签: java jsp servlets


【解决方案1】:

在您的 servlet 中按以下方式使用 request.setAttribute

request.setAttribute("myStation", value);

其中 value 恰好是您稍后要读取的对象。

稍后使用 request.getAttribute as 在不同的 servlet/jsp 中提取它

String value = (String)request.getAttribute("myStation")

<%= request.getAttribute("myStation")%>

请注意,get/setAttribute 的使用范围本质上是有限的——属性在请求之间被重置。如果您打算将值存储更长时间,则应使用会话或应用程序上下文,或者更好的数据库。

属性与参数不同,客户端从不设置属性。开发人员或多或少地使用属性将状态从一个 servlet/JSP 转移到另一个。所以你应该使用getParameter(没有setParameter)从请求中提取数据,如果需要使用setAttribute设置属性,使用RequestDispatcher在内部转发请求并使用getAttribute提取属性。

【讨论】:

  • 感谢广泛的 cmets。我真的很感激。传递的值具有页面范围,所以我认为您向我展示的方法就足够了。
【解决方案2】:

使用getParameter()。在应用程序内部设置和读取属性。

【讨论】:

    【解决方案3】:

    在您的代码中, 字符串测试 = "/response2.jsp?myStation=5";

    您正在添加 myStation=5 作为查询字符串。因为存储了查询字符串参数 作为请求对象中的请求参数。

    因此你可以使用 ,

    它工作正常。谢谢。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-24
      • 2018-08-20
      • 1970-01-01
      • 2015-11-25
      • 1970-01-01
      • 2015-05-22
      • 2013-08-13
      • 1970-01-01
      相关资源
      最近更新 更多