The normal approach to invoke other servlet would be to use RequestDispatcher#include()
.
request.getRequestDispatcher("/secondServletURL").include(request, response);
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.
response.sendRedirect(request.getContextPath() + "/secondServletURL?" + queryString);
You could create the query string as follows:
Map<String, String[]> params = new HashMap<String, String[]>(request.getParameterMap());
params.put("name1", new String[] {"value1"});
params.put("name2", new String[] {"value2"});
// ...
String queryString = toQueryString(params);
where toQueryString()
look like follows:
public static String toQueryString(Map<String, String[]> params) {
StringBuilder queryString = new StringBuilder();
for (Entry<String, String[]> param : params.entrySet()) {
for (String value : param.getValue()) {
if (queryString.length() > 0) {
queryString.append("&");
}
queryString
.append(URLEncoder.encode(param.getKey(), "UTF-8"))
.append("=")
.append(URLEncoder.encode(value, "UTF-8"));
}
}
return queryString.toString();
}
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:
SomeData data = new SomeData();
data.setSomeProperty1(request.getParameter("someProperty1"));
data.setSomeProperty2("some custom value");
data.setSomeProperty3("some other custom value");
SomeBusinessService service = new SomeBusinessService();
service.doSomeAction(data);
And servlet 2:
SomeData data = new SomeData();
data.setSomeProperty1(request.getParameter("someProperty1"));
data.setSomeProperty2(request.getParameter("someProperty2"));
data.setSomeProperty3(request.getParameter("someProperty3"));
SomeBusinessService service = new SomeBusinessService();
service.doSomeAction(data);
The SomeBusinessService
is usually to be an EJB.