Recipe 7.7 Using a Servlet to Add a Parameter to a Query String


You want to use a servlet to add one or more parameters to a query string, then forward the request to its final destination.


Use 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.


The 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, {  //returns null if the URL does not contain a query string     String querystr = request.getQueryString( );     if (querystr != null){         querystr = querystr +          "&inspector-name=Jen&";     } else {         querystr = "inspector-name=Jen&";}                  RequestDispatcher dispatcher =            request.getRequestDispatcher("/viewPost.jsp?"+querystr);         dispatcher.forward(request,response);  } public void doPost(HttpServletRequest request, HttpServletResponse response)     throws ServletException, {            doGet(request,response);            }     } 

The HttpServletRequest.getQueryString( ) method returns the query string without the opening "?", as in:


If you want to get the request URL right up to the query string but not include the "?", use HttpServletRequest.getRequestURL( ) , which returns a java.lang.StringBuffer type.

See Also

Recipe 7.1 on handling a POST request in a servlet; Recipe 7.5 on posting data from a servlet.

Java Servlet & JSP Cookbook
Java Servlet & JSP Cookbook
ISBN: 0596005725
EAN: 2147483647
Year: 2004
Pages: 326 © 2008-2017.
If you may any questions please contact us: