servlet

Java Servlet onclick 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 and show you how to call a Servlet method on a button click.

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

Now, open up the Eclipse Ide and let’s see how to call a Servlet method on a button click.

2. Java Servlet onclick Example

2.1 Creating JSP Views

Servlet supports many types of views for different presentation technologies. These include – JSP, HTML, XML etc. So let us write a simple view in JavaServletOnClick/src/main/webapp/. To make the form works with Java servlet, we need to specify the following attributes for the <form> tag:

  • method="post": To send the form data as an HTTP POST request to the server. Generally, form submission should be done in HTTP POST method
  • action="Servlet Url": Specifies the relative URL of the servlet which is responsible for handling the data posted from this form

Add the following code to it in order to call a Servlet from a JavaScript function:

index.jsp

<!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=UTF-8">
	    <title>Servlet onClick Example</title>
	    <style type="text/css">
	        .paddingBtm {
	            padding-bottom: 12px;
	        }
	    </style>
	    <script type="text/javascript">
	        function callServlet() {
	            document.forms[0].action = "Welcome";
	            document.forms[0].submit();
	        }
	    </script>
	</head>
	<body>
	    <center>
	        <h2>Servlet onClick Example</h2>
	        <form id="loginFormId" name="loginForm" method="post">
	            <div id="usernameDiv" class="paddingBtm">
	                <span id="user">Username: </span><input type="text" name="username" />
	            </div>
	            <div id="loginBtn">
	                <input id="btn" type="submit" value="Login" onclick="callServlet();" />
	            </div>
	        </form>
	    </center>
	</body>
</html>

3. Run the Application

As we are ready for all the changes, let us compile the project and deploy the application on the Tomcat7 server. Open your favorite browser and hit the following URL. The output page will be displayed.

http://localhost:8085/JavaServletOnClick/

Fig. 1 - onClick Example Application Output
Fig. 1 – Application Output

Enter the username and submit the form. Developers will see that the upon the button click the form will be submitted to the Servlet and the below log will be seen on the console.

Parameter Received From The JavaScript onClick Example. Submitted Name Is?= jcg

4. Conclusion

In this section, developers learned how to call a Servlet on a button click. Developers can download the sample application as an Eclipse project in the Downloads section. I hope this article served you with whatever developers were looking for.

5. Download the Eclipse Project

This was an example of Servlet Application Login.

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

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.

5 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Jarrod Roberson
Jarrod Roberson
6 years ago

download link is broken!

abhishek Kumar
abhishek Kumar
6 years ago

you should explain javaScript part of index.jsp file. Specially document.forms[0].action = “Welcome”;
.

Ankur
Ankur
4 years ago

What if client has js disabled in browser.

Back to top button