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


Problem

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

Solution

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.

Discussion

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, 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);            }     } 

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

 first=Bruce&last=Perry&zipcode=01922 

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

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net