Spring MVC — Sample Java servlet

According to Oracle docs, Servlet is a Java programming language class that is used to extend the capabilities of servers that host applications accessed by means of a request-response programming model. In this tutorial, I will explain how to respond to a request made by a user by using java servlets. I’ll be using Intellij IDEA as the IDE and Tomcat server as the web server.

Open Intellij IDEA and create a new project. Choose Maven as the project type.

Provide a suitable GroupId and an ArtifactId for the project.

Open pom.xml and enable the “Enable auto import” pop-up. It will automatically download any dependencies we add for the project.

Add a new folder called ‘webapp’ under main folder since we are developing a web project. Under webapp folder create another folder called ‘WEB-INF’.

Since we are creating a webapp, we need to tell the IDE that this is a web project. To configure that, we can change the packaging of the project into .war or .jar. In this case it should be .war.

To create the deployment descriptor which is the web.xml, right click on the project and go to Open Module Settings -> Web. Click on the + mark of the deployment descriptor tab and add the web.xml file. Make sure to give the correct path into WEB-INF folder.

This is the web.xml file created.

To get started with the servlet, create a package with the groupId we gave earlier. And then create a java class and provide a suitable name for it.

Add the http-servlet maven dependency into the pom.xml file.

Insert the following servelt.java file into to the java class you created under /servlets.

This servlet provides a response when a user requests something from URL mapping. It can be easily done by overriding the doGet() function of the HttpServlet class we extended. There are two main objects shown in the function.

  • HttpServletRequest req
  • HttpServletResponse resp

We are only interested with the resp object since we are creating a response to send. Whenever a user sends a GET request for this servlet, it will display the “Hello world!” message as the response.

Do the necessary changes in the web.xml file by inserting the below.

This defines the URL pattern in which the request is mapped. In our case, if the user type /home, it will respond with the Hello world message.

To add the tomcat server, go to Edit Configurations -> Tomcat Server -> Local.

You need to have Tomcat server downloaded in order to run this. As you can see, there is a warning at the bottom of the window. To correct that click on Fix button and add the spring-tutorial.war.exploded artifact. I chose the exploded option because if we change anything in the servlet it will automatically upload the change in the server.

Now you can run the server.

Go to localhost:8080/home and you will be able to see the response coming from the servlet.