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 ‘&’
http://localhost:8080/ServletsTutorial/QueryStringExample?firstName=Java&lastName=InterviewPoint
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.
Form.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Query String Example</title> </head> <body> <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> </form> </body> </html>
QueryStringExample.java
package com.javainterviewpoint; import java.io.IOException; import java.io.PrintWriter; 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 { res.setContentType("text/html"); PrintWriter out = res.getWriter(); String queryString = req.getQueryString(); out.println("Query String passed is : " + queryString); out.close(); } }
We will be calling getQueryString() method of the request to get the query string.
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>ServletsTutorial</display-name> <servlet> <servlet-name>QueryStringExample</servlet-name> <servlet-class>com.javainterviewpoint.QueryStringExample</servlet-class> </servlet> <servlet-mapping> <servlet-name>QueryStringExample</servlet-name> <url-pattern>/QueryStringExample</url-pattern> </servlet-mapping> </web-app>
Run the Form.jsp page
After filling the FirstName and LastName, click on the submit button to get the queryString.
Leave a Reply