简体   繁体   English

转发到servlet并设置属性

[英]Forward to a servlet and set attribute

I'm working with servlets in java; 我正在使用Java中的servlet; I'm trying to forward from one servlet to another servlet. 我正在尝试从一个servlet转发到另一个servlet。 I also want to pass an attribute to that other servlet. 我还想将一个属性传递给其他servlet。

When i want to forward to a JSP, it works fine. 当我想转发到JSP时,它可以正常工作。 i do 我做

request.setAttribute("attrName", attribute)
request.getRequestDispatcher("forward.jsp").forward(request, response);

But When I do the same with a servlet: 但是,当我对servlet执行相同操作时:

request.setAttribute("attrName", attribute)
request.getRequestDispatcher("TheServlet").forward(request, response);

My server freaks out and I get the following error: 我的服务器吓坏了,出现以下错误:

javax.servlet.ServletRequestWrapper.isAsyncStarted(ServletRequestWrapper.java:395)

I know I can use the following line to redirect to a servlet: 我知道我可以使用以下行重定向到servlet:

response.sendRedirect("TheServlet");

But for some reason the set Attribute doesn't work when I redirect instead of forward. 但是由于某种原因,当我重定向而不是转发时,set Attribute无法正常工作。

redirect is a HTTP response sent to the browser requesting it to submit a new request to the specified URL. redirect是发送给浏览器的HTTP响应,请求其向指定的URL提交新请求。 Since it results in issuing an entirely new request previous request attributes you set wont be available in the new request. 由于它会导致发出全新请求,因此您设置的先前请求属性将在新请求中不可用。

In terms of forwarding to a servlet, did you check your web.xml configuration. 关于转发到servlet,您是否检查了web.xml配置。 Is it setup so that the forwarded servlet is seeing forwarded requests ? 是否进行了设置,以便转发的servlet看到转发的请求?

You could save the attribute to the session in the first servlet and access it from the second. 您可以将属性保存到第一个servlet中的会话中,然后从第二个servlet中访问它。 Use http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#getSession() 使用http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#getSession()

Also you could pass the attribute value in the URL query string in the redirect. 您也可以在重定向的URL查询字符串中传递属性值。 So your redirect URL would look like 'myRedirectUrl?attributeName=attributeValue' 因此您的重定向URL看起来像是“ myRedirectUrl?attributeName = attributeValue”

Also additionally try using 'include' method rather than 'forward'. 另外,请尝试使用“包含”方法而不是“前进”方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM