如何从servlet发送参数

我试图使用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。

  

response 2

谢谢你的任何建议。 更环保

在您的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传递到另一个servlet / JSP。 因此,您应该使用getParameter (没有setParameter)从请求中提取数据,如果需要使用setAttribute设置属性,使用RequestDispatcher在内部转发请求,并使用getAttribute提取属性。

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

在你的代码中,String test =“/ response.jsp?myStation = 5”;

您正在将myStation = 5添加为查询字符串。由于查询字符串参数在请求对象中存储为请求参数。

因此你可以使用,

它运作正常。谢谢。