[ Team LiB ] Previous Section Next Section

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, java.io.IOException {

    //returns null if the URL does not contain a query string
    String querystr = request.getQueryString( );

    if (querystr != null){

        querystr = querystr +

    } else {

        querystr = "inspector-name=Jen&inspector-email=Jenniferq@yahoo.com";}
        RequestDispatcher dispatcher =


public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, java.io.IOException {

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.

    [ Team LiB ] Previous Section Next Section