我试图使用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);
}
Run Code Online (Sandbox Code Playgroud)
这是我的jsp,带有读取值的代码 - 但它显示为null.
<h1>response 2</h1>
<p>
<%=request.getAttribute("myStation") %>
</p>
Run Code Online (Sandbox Code Playgroud)
谢谢你的任何建议.更环保
Vin*_*lds 15
在您的servlet 中,以下列方式使用request.setAttribute
request.setAttribute("myStation", value);
Run Code Online (Sandbox Code Playgroud)
其中value恰好是您想要稍后阅读的对象.
稍后使用request.getAttribute as 在不同的servlet/jsp中提取它
String value = (String)request.getAttribute("myStation")
Run Code Online (Sandbox Code Playgroud)
要么
<%= request.getAttribute("myStation")%>
Run Code Online (Sandbox Code Playgroud)
请注意,get/setAttribute的使用范围本质上是有限的 - 属性在请求之间重置.如果您打算将值存储更长时间,则应使用会话或应用程序上下文,或者更好的数据库.
属性与参数不同,因为客户端从不设置属性.开发人员或多或少地使用属性将状态从一个servlet/JSP转移到另一个servlet/JSP.因此,您应该使用getParameter(没有setParameter)从请求中提取数据,如果需要使用setAttribute设置属性,使用RequestDispatcher在内部转发请求,并使用getAttribute提取属性.