Get Query String from Servlet Request

The getQueryString() method is defined in the HttpServletRequest interface, which is used to retrieve the query string of the HTTP request. A query string is the string on the URL to the right of the path to the servlet. Using this a programmer can know the data which is sent from the client(when a form is submitted) 

What is a Query String?

A Query String is a String which is appeneded to the URL containing the form fields and data which is entered by the user. It will start with a ‘?’ and the fields are seperated by ‘&’


Here we can see that there are two Form fields firstName and lastName appended as query string as values and two fields are seperated by &.

Lets now see the complete example to have a better understanding.


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">
        <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
        <title>Query String Example</title>
        <form method="GET" action="./QueryStringExample">
             First Name : <input type="text" name="firstName"/></br>
             Last Name  : <input type="text" name="lastName"/></br>
            <input type="submit"></br>

package com.javainterviewpoint;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class QueryStringExample extends HttpServlet
    public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException 
        PrintWriter out = res.getWriter();   
        String queryString = req.getQueryString(); 
        out.println("Query String passed is  : " + queryString);   

We will be calling getQueryString() method of the request to get the query string.


<?xml version="1.0" encoding="UTF-8"?>
     <web-app xmlns:xsi="" xmlns="" xmlns:web="" xsi:schemaLocation="" id="WebApp_ID" version="2.5">

Run the Form.jsp page



After filling the FirstName and LastName, click on the submit button to get the queryString.


Leave a Reply

Your email address will not be published. Required fields are marked *