O'Reilly logo

Java Servlet & JSP Cookbook by Bruce W. Perry

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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); ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required