servlet

Java Servlet Url Parameters Example

Servlets are modules of the Java code that run in a server application to answer the client requests. They are not tied to a specific client-server protocol but are most commonly used with HTTP. The word “Servlet” is often used in the meaning of “HTTP Servlet” . In this tutorial, we will explain how to handle parameters of the Servlet HTTP Request.

1. Introduction

Servlet is a Java program which exists and executes in the J2EE servers and is used to receive the HTTP protocol request, process it and send back the response to the client. Servlets make use of the Java standard extension classes in the packages javax.servlet and javax.servlet.http. Since Servlets are written in the highly portable Java language and follow a standard framework, they provide a means to create the sophisticated server extensions in a server and the operating system in an independent way.

 
Typical uses for HTTP Servlets include:

  • Processing and/or storing the data submitted by an HTML form
  • Providing dynamic content i.e. returning the results of a database query to the client
  • Managing state information on top of the stateless HTTP i.e. for an online shopping cart system which manages the shopping carts for many concurrent customers and maps every request to the right customer

As Servlet technology uses the Java language, thus web applications made using Servlet are Secured, Scalable, and Robust.

1.1 Servlet Architecture & Lifecycle

A Servlet, in its most general form, is an instance of a class which implements the javax.servlet.Servlet interface. Most Servlets, however, extend one of the standard implementations of this interface, namely javax.servlet.GenericServlet and javax.servlet.http.HttpServlet. In this tutorial, we’ll be discussing only HTTP Servlets which extends the javax.servlet.http.HttpServlet class.

In order to initialize a Servlet, a server application loads the Servlet class and creates an instance by calling the no-args constructor. Then it calls the Servlet’s init(ServletConfig config) method. The Servlet should perform the one-time setup procedures in this method and store the ServletConfig object so that it can be retrieved later by calling the Servlet’s getServletConfig() method. This is handled by the GenericServlet. Servlets which extend the GenericServlet (or its subclass i.e. HttpServlet) should call the super.init(config) at the beginning of the init method to make use of this feature.

Signature of init() method

public void init(ServletConfig config) throws ServletException

The ServletConfig object contains the Servlet parameters and a reference to the Servlet’s ServletContext. The init method is guaranteed to be called only once during the Servlet’s lifecycle. It does not need to be thread-safe because the service() method will not be called until the call to the init() method returns.

When the Servlet is initialized, its service(HttpServletRequest req, HttpServletResponse resp) method is called for every request to the Servlet. The method is called concurrently (i.e. multiple threads may call this method at the same time) as it should be implemented in a thread-safe manner. The service() method will then call the doGet() or doPost() method based on the type of the HTTP request.

Signature of service() method

public void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException

When the Servlet needs to be unloaded (e.g. because a new version should be loaded or the server is shutting down), the destroy() method is called. There may still be threads that execute the service() method when the destroy() method is called, so destroy() method has to be thread-safe. All resources which were allocated in the init() method should be released in the destroy() method. This method is guaranteed to be called only once during the Servlet’s lifecycle.

Fig. 1: A Typical Servlet Lifecycle
Fig. 1: A Typical Servlet Lifecycle

1.2 Servlet Container

Servlet Container is a component which loads the Servlets and manages the Servlet life cycle and responds back with the dynamic content to the HTTP server. Servlet container is used by the HTTP server for processing the dynamic content and Tomcat is a perfect example for the Servlet Container.

Fig. 2: Servlet Container
Fig. 2: Servlet Container

The Servlet Container performs operations that are given below:

  • Life Cycle Management
  • Multithreaded Support
  • Object Pooling
  • Security etc.

1.3 Get vs. Post Request

There are many differences between the HTTP Get and Post request. Let’s see these differences:

FeatureGETPOST
Sending of dataClient data is appended to URL and sentClient data is sent separately
Storing in the Browser HistoryAs data is appended, the client data is stored in the browser historyAs data is sent separately, the client data is not stored in the browser history
BookmarkThe URL with client data can be bookmarked. Thereby, later without filling the HTML form, the same data can be sent to serverNot possible to bookmark
Encoding or enctypeapplication/x-www-form-urlencodedapplication/x-www-form-urlencoded or multipart/form-data. For binary data, multipart encoding type is used
Limitation of data sentLimited to 2048 characters (browser dependent)Unlimited data
Hacking easinessEasy to hack the data as the data is stored in the browser historyDifficult to hack as the data is sent separately in an HTML form
Type of data sentOnly ASCII data can be sentAny type of data can be sent including the binary data
Data secrecyData is not secret as other people can see the data in the browser historyData is secret as not stored in the browser history
When to be usedPrefer when data sent is not secret. Do not use for passwords etc.Prefer for critical and sensitive data like passwords etc.
CacheCan be caughtCannot be caught
DefaultIf not mentioned, GET is assumed as defaultShould be mentioned explicitly
PerformanceRelatively faster as data is appended to URLA separate message body is to be created

Do remember, if client data includes only the ASCII characters i.e. no secrecy and the data is limited to 2 KB length, then prefer GET, else POST.

1.4 Servlet Advantages

There are many advantages of Servlet over CGI (Common Gateway Interface). The Servlet Web Container creates threads for handling the multiple requests to the Servlet. Threads have a lot of benefits over the processes such as they share a common memory area, lightweight, cost of communication between the threads are low. The basic benefits of Servlet are as follows:

  • Less response time because each request runs in a separate thread
  • Servlets are scalable
  • Servlets are robust and object-oriented
  • Servlets are platform-independent
  • Servlets are secure and offer portability

Fig. 3: Benefits of using Servlets
Fig. 3: Benefits of using Servlets

Now, open up the Eclipse IDE and let’s see how to retrieve the Url parameters in a Servlet!

2. Java Servlet Url Parameters Example

Here is a step-by-step guide for implementing the servlet framework in Java.

2.1 Tools Used

We are using Eclipse Kepler SR2, JDK 8 and Maven. Having said that, we have tested the code against JDK 1.7 and it works well.

2.2 Project Structure

Firstly, let’s review the final project structure, in case you are confused about where you should create the corresponding files or folder later!

Fig. 4: Servlet Url Parameters Application Project Structure
Fig. 4: Application Project Structure

2.3 Project Creation

This section will demonstrate on how to create a Java-based Maven project with Eclipse. In Eclipse IDE, go to File -> New -> Maven Project.

Fig. 5: Create Maven Project
Fig. 5: Create Maven Project

In the New Maven Project window, it will ask you to select project location. By default, ‘Use default workspace location’ will be selected. Just click on next button to proceed.

Fig. 6: Project Details
Fig. 6: Project Details

Select the Maven Web App Archetype from the list of options and click next.

Fig. 7: Archetype Selection
Fig. 7: Archetype Selection

It will ask you to ‘Enter the group and the artifact id for the project’. We will input the details as shown in the below image. The version number will be by default: 0.0.1-SNAPSHOT.

Fig. 8: Archetype Parameters
Fig. 8: Archetype Parameters

Click on Finish and the creation of a maven project is completed. If you observe, it has downloaded the maven dependencies and a pom.xml file will be created. It will have the following code:

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>JavaServletUrlParameters</groupId>
	<artifactId>JavaServletUrlParameters</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
</project>

We can start adding the dependencies that developers want like Servlets, Junit etc. Let’s start building the application!

3. Application Building

Below are the steps involved in developing this application.

3.1 Maven Dependencies

Here, we specify the dependencies for the Servlet API. The rest dependencies will be automatically resolved by the Maven framework and the updated file will have the following code:

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>JavaServletUrlParameters</groupId>
	<artifactId>JavaServletUrlParameters</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>JavaServletUrlParameters Maven Webapp</name>
	<url>http://maven.apache.org</url>
	<dependencies>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>3.1.0</version>
		</dependency>
	</dependencies>
	<build>
		<finalName>${project.artifactId}</finalName>
	</build>
</project>

3.2 Java Class Creation

Let’s create the required Java files. Right-click on src/main/java folder, New -> Package.

Fig. 9: Java Package Creation
Fig. 9: Java Package Creation

A new pop window will open where we will enter the package name as: com.jcg.servlet.

Fig. 10: Java Package Name (com.jcg.servlet)
Fig. 10: Java Package Name (com.jcg.servlet)

Once the package is created in the application, we will need to create the controller class. Right-click on the newly created package: New -> Class.

Fig. 11: Java Class Creation
Fig. 11: Java Class Creation

A new pop window will open and enter the file name as: ServletUrlParameterExample. The Servlet Controller class will be created inside the package: com.jcg.servlet.

Fig. 12: Java Class (ServletUrlParameterExample.java)
Fig. 12: Java Class (ServletUrlParameterExample.java)

3.2.1 Implementation of Servlet Controller Class

In an HTTP GET request, the request parameters are taken from the query string (i.e. the data following the question mark in the URL). For example, the URL http://hostname.com?p1=v1&p2=v2 contains the two request parameters i.e. p1 and p2. Let’s see the simple code snippet that follows this implementation.

ServletUrlParameterExample.java

package com.jcg.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/getParameters")
public class ServletUrlParameterExample extends HttpServlet {

	private static final long serialVersionUID = 1L;

	// This Method Is Called By The Servlet Container To Process A 'GET' Request.
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		handleRequest(req, resp);
	}

	public void handleRequest(HttpServletRequest req, HttpServletResponse resp) throws IOException {

		resp.setContentType("text/html");

		// Get Parameters From The Request
		String param1 = req.getParameter("param1");
		String param2 = req.getParameter("param2");
		String[] paramArray = req.getParameterValues("paramArray");

		if(param1 == null || param2 == null || paramArray == null) {
			// The Request Parameters Were Not Present In The Query String. Do Something Or Exception Handling !!
		} else if ("".equals(param1) || "".equals(param2) || "".equals(paramArray)) {
			// The Request Parameters Were Present In The Query String But Has No Value. Do Something Or  Exception Handling !!
		} else {
			System.out.println("Parameter1?= " + param1 + ", Parameter2?= " + param2 + ", Array Parameters?= " + Arrays.toString(paramArray));

			// Print The Response
			PrintWriter out = resp.getWriter();
			out.write("<html><body><div id='serlvetResponse'>");
			out.write("<h2>Servlet HTTP Request Parameters Example</h2>");
			out.write("<p>param1: " + param1 + "</p>");
			out.write("<p>param2: " + param2 + "</p>");
			out.write("<p>paramArray: " + Arrays.toString(paramArray) + "</p>");
			out.write("</div></body></html>");
			out.close();
		}
	}
}

4. Run the Application

As we are ready with all the changes, let us compile the project and deploy the application on the Tomcat7 server. To deploy the application on Tomat7, right-click on the project and navigate to Run as -> Run on Server.

Fig. 13: How to Deploy Application on Tomcat
Fig. 13: How to Deploy Application on Tomcat

Tomcat will deploy the application in its web-apps folder and shall start its execution to deploy the project so that we can go ahead and test it on the browser.

5. Project Demo

Open your favorite browser and hit the following URL. The output page will be displayed.

http://localhost:8085/JavaServletUrlParameters/

Server name (localhost) and port (8085) may vary as per your tomcat configuration. Developers can debug the example and see what happens after every step. Enjoy!

Fig. 14: Application Output
Fig. 14: Application Output

That’s all for this post. Happy Learning!!

6. Conclusion

In this section, developers learned how to retrieve the request parameters in a Servlet. Developers can download the sample application as an Eclipse project in the Downloads section. I hope this article has served you whatever you were looking for as a developer.

7. Download the Eclipse Project

This was an example of Servlet Url Parameters.

Download
You can download the full source code of this example here: JavaServletUrlParameters

Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button