Introduction to Servlet

Servlet Overview

People seldom understand the intuition behind a technology before putting each bit together. To get a sense of how Servlet works, we will assume you are a client requesting for a specific resource from the server, e.g., a static web page such as index.html.

First, your request will be sent to a server and the server respond with the page you have requested – in this case, index.html [Simple right? 🙂 ].

 

Image result for client server image

 

However, it gets a bit tricky if you are requesting a dynamic content.  The process is not entirely straightforward since the server may not know about the resource at run-time. The server makes use of some helper application. These helper applications are also called WebContainer, e.g., Tomcat, Glassfish, etc. The Webcontainer contains servlet which is a java file that can process the request and return the resource.

So let’s code

We will be creating a simple application that adds two numbers together.

If you click on the Add button at this point, no action will be performed. Can you guess why? Exactly! You’ve not specified what the Add button should do or where it should submit to.

So we will add a form tag as shown below. Here we are saying that our request is a get request and it will be handled by Add servlet.

Great, if you run this application now, you should be getting an error. The reason for this error is because we have not created the Add servlet. To fix this, create a servlet and name it Add. Once you do that, try to let the class look like this

You should see the result of the addition after putting the two numbers and pressing the submit button.

@WebServlet is an annotation that binds our request to the servlet. To clarify further, whenever a user requests the Add page. For instance, if you click on the two numbers and check your browser, you will notice that the URL is localhost:8080/AddNumbers/Add?firstNumber=34&secondNumber=50, it will call this servlet.

A quick explanation of the Add servlet. Since we are making a get request. We will put our code in the doGet method().

Remember the parameter in our browser: localhost:8080/AddNumbers/Add?firstNumber=34&secondNumber=50. We can get these parameters by using request.getparameter(“the_name_of_the_parameter”). So we leverage this approach to get the two numbers.

After getting the number, we add them together and we use PrintWriter to print it on the browser. System.out.println() will print the result on the console and not the browser.

We could have used a post request if we don’t want the parameters to appear on the browser.

Thanks for reading 🙂

 

 

 

 

 

 

Share your thoughts