【发布时间】:2011-04-06 06:02:32
【问题描述】:
如何将变量从 servlet 传递到 jsp?
setAttribute 和 getAttribute 对我不起作用:-(
【问题讨论】:
如何将变量从 servlet 传递到 jsp?
setAttribute 和 getAttribute 对我不起作用:-(
【问题讨论】:
在以下情况下它将无法工作:
您将响应重定向到response.sendRedirect("page.jsp") 的新请求。新创建的请求对象当然将不再包含这些属性,并且它们将无法在重定向的 JSP 中访问。您需要转发而不是重定向。例如
request.setAttribute("name", "value");
request.getRequestDispatcher("page.jsp").forward(request, response);
您以错误的方式访问它或使用了错误的名称。假设您已使用名称 "name" 设置它,那么您应该可以在 forwarded JSP 页面中访问它,如下所示:
${name}
【讨论】:
${name} 而不是 <%out.println(${name});%>。
我发现的简单方法是,
在 servlet 中:
您可以设置该值并将其转发到 JSP,如下所示
req.setAttribute("myname",login);
req.getRequestDispatcher("welcome.jsp").forward(req, resp);
在 Welcome.jsp 中,您可以通过
获取值.<%String name = (String)request.getAttribute("myname"); %>
<%= name%>
(或)你可以直接调用
<%= request.getAttribute("myname") %>.
【讨论】:
使用
request.setAttribute("attributeName");
然后
getServletContext().getRequestDispatcher("/file.jsp").forward();
然后就可以在 JSP 中访问了。
附带说明 - 在您的 jsp 中避免使用 java 代码。使用 JSTL。
【讨论】:
getServletContext() 而不是request?
除了使用 属性 将信息从 servlet 传递到 JSP 页面之外,还可以传递 参数。只需重定向到指定相关 JSP 页面的 URL,并添加正常的参数通过 URL 传递机制即可完成。
一个例子。 servlet代码的相关部分:
protected void doGet( HttpServletRequest request, HttpServletResponse response )
throws ServletException, IOException
{
response.setContentType( "text/html" );
// processing the request not shown...
//
// here we decide to send the value "bar" in parameter
// "foo" to the JSP page example.jsp:
response.sendRedirect( "example.jsp?foo=bar" );
}
以及JSP页面的相关部分example.jsp:
<%
String fooParameter = request.getParameter( "foo" );
if ( fooParameter == null )
{
%>
<p>No parameter foo given to this page.</p>
<%
}
else
{
%>
<p>The value of parameter foo is <%= fooParameter.toString() %>.</p>
<%
}
%>
【讨论】:
您可以在将请求转发到 jsp 之前将所有值设置到响应对象中。或者您可以将您的值放入会话 bean 并在 jsp 中访问它。
【讨论】:
这是一个 servlet 代码,其中包含一个字符串变量 a。 a 的值来自带有表单的 html 页面。
然后将变量设置到请求对象中。然后使用forward 和requestdispatcher 方法将其传递给jsp。
String a=req.getParameter("username");
req.setAttribute("name", a);
RequestDispatcher rd=req.getRequestDispatcher("/login.jsp");
rd.forward(req, resp);
在jsp中按照下面程序中的这些步骤进行
<%String name=(String)request.getAttribute("name");
out.print("your name"+name);%>
【讨论】:
您还可以使用 RequestDispacher 并将数据与您想要的 jsp 页面一起传递。
request.setAttribute("MyData", data);
RequestDispatcher rd = request.getRequestDispatcher("page.jsp");
rd.forward(request, response);
【讨论】:
在doGet 上使用setAttribute 和getRequestDispatcher 时,请确保您正在使用为您的servlet 定义的urlPatterns(例如“/login”)访问您的页面。如果您使用“/login.jsp”执行此操作,您的doGet 将不会被调用,因此您的任何属性都将不可用。
【讨论】:
如果您使用 Action、Actionforward 方式来处理业务逻辑并显示下一页,请检查是否调用了重定向。正如许多其他人指出的那样,重定向不会保留您的原始请求,因为它基本上会迫使您向指定路径发出新请求。因此,如果您使用重定向而不是 requestdispatch,原始请求中设置的值将消失。
【讨论】: