ProblemYou want to use a servlet to add one or more parameters to a query string, then forward the request to its final destination. SolutionUse the HttpServletRequest API to get the existing query string. Then append any new parameters to the query string and use a javax.servlet.RequestDispatcher to forward the request. DiscussionThe servlet in Example 7-12 simply takes any existing query string and appends the parameters that it has to add to this String . Then it sends the now extended (or new) query string on its merry way with a call to RequestDispatcher.forward . Example 7-12. Adding a parameter to a query string with a servlet package com.jspservletcookbook; import javax.servlet.*; import javax.servlet.http.*; public class QueryModifier extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException { //returns null if the URL does not contain a query string String querystr = request.getQueryString( ); if (querystr != null){ querystr = querystr + "&inspector-name=Jen&inspector-email=Jenniferq@yahoo.com"; } else { querystr = "inspector-name=Jen&inspector-email=Jenniferq@yahoo.com";} RequestDispatcher dispatcher = request.getRequestDispatcher("/viewPost.jsp?"+querystr); dispatcher.forward(request,response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException { doGet(request,response); } }
See AlsoRecipe 7.1 on handling a POST request in a servlet; Recipe 7.5 on posting data from a servlet. |