简体   繁体   中英

Forward to a servlet and set attribute

I'm working with servlets in java; I'm trying to forward from one servlet to another servlet. I also want to pass an attribute to that other servlet.

When i want to forward to a JSP, it works fine. i do

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

But When I do the same with a 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:

response.sendRedirect("TheServlet");

But for some reason the set Attribute doesn't work when I redirect instead of forward.

redirect is a HTTP response sent to the browser requesting it to submit a new request to the specified 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. Is it setup so that the forwarded servlet is seeing forwarded requests ?

You could save the attribute to the session in the first servlet and access it from the second. Use 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. So your redirect URL would look like 'myRedirectUrl?attributeName=attributeValue'

Also additionally try using 'include' method rather than 'forward'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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