Say I submit a simple page (that has no parameters, no forms, etc, and I can’t add anything to this page), I end-up in the first servlet. Now I determine it’s time to do the stuff in the second servlet. The second servlet expects a bunch of parameters and form fields populated, so first I’d need to set those up in the first servlet, then figure out how to get those things to the second servlet. When I tried to add something to the parameter map, it errored-out with “no modifications are allowed to a locked parameter map” (which is the way JSP is supposed to work). I was thinking maybe I should instantiate up another request object, but I’m not sure how to do that (and keep myself out of hot water). If, in the first servlet, I ever am able to construct a request object with all “the right stuff”, then I’d need to run that second servlet with that request, and let it take me to whatever page the second servlet redirects me to. I think that one would just be a response.sendRedirect();
How do I get additional parameters and things defined in the first servlet so when I do the sendRedirect, the second servlet has everything it needs?
The normal approach to invoke other servlet would be to use
RequestDispatcher#include().If you’d like to add extra request parameters and you would like to end up with them in the (bookmarkable!) URL of redirected page, then you have to populate a query string based on those parameters yourself before redirecting.
You could create the query string as follows:
where
toQueryString()look like follows:However, as that servlet seems to be running in the same container and you’d like to reuse the second servlet’s logic without exposing the additional parameters into public, then likely a much better way is to refactor the business code of that tight coupled second servlet into another, separate and reuseable class which you finally just import and call in your both servlets. You can then pass the data to that class using a reuseable Javabean object.
For example, servlet 1:
And servlet 2:
The
SomeBusinessServiceis usually to be an EJB.