In this Java tutorial, I will help you develop a Java servlet from scratch using the @WebServlet annotation and how to deploy, run and test the servlet on Tomcat server.

This tutorial is similar to Java servlet quick start guide for beginner (XML), except that the servlet configuration and mapping is done through annotations instead of in web.xml file. No XML stuff is used.

Table of content:

    1. Quick introduction to servlet annotations
    2. Creating directory structure
    3. Writing the annotated servlet class
    4. Writing the JSP page
    5. Compiling the servlet
    6. Creating WAR file
    7. Deploying and testing the web application

  

1. Quick introduction to servlet annotations

The Servlet API 3.0 introduces a new package called javax.servlet.annotation which provides annotation types which can be used for annotating a servlet class. The annotations can replace equivalent XML configuration in the web deployment descriptor file (web.xml) such as servlet declaration and servlet mapping. Servlet containers will process the annotated classes at deployment time.

The annotation types introduced in Servlet 3.0 are:

The annotation @WebServlet is used for declaring a servlet class (the class still must extend from the HttpServlet class) and configuring mapping for it. Here are some examples of using the @WebServlet annotation:

    • The simplest way to declare a servlet:
      @WebServlet("/Submit")
      public class QuickServlet extends HttpServlet {
      	// servlet code here...
      }

      Here the servlet QuickServlet is mapped to the URL pattern: /Submit.

       

    • Declare a servlet with additional information:
      @WebServlet(
      	name = "AnnotatedServlet",
      	description = "A sample annotated servlet",
      	urlPatterns = {"/QuickServlet"}
      )
      public class QuickServlet extends HttpServlet {
      	// servlet code here...
      }

      Here the servlet is declared with additional information such as name and description.

    • Declare a servlet with multiple URL patterns:
      @WebServlet(
      	urlPatterns = {"/foo", "/bar", "/cool"}
      )
      public class QuickServlet extends HttpServlet {
      	// servlet code here...
      }

      Here the servlet is mapped with three different URL patterns: /foo, /bar and /cool.

       

Now let’s build a simple Java web application which has a servlet configured by using the @WebServlet annotation. Assuming you have JDK 1.7 and Tomcat 7.0 installed on your computer. Of course you can use newer versions.

 

2. Creating directory structure

Since we don’t use any IDE, create the following directory structure:

directory structure

And suppose the current working directory is the QuickServletdirectory.


3. Writing the annotated servlet class

Create the servlet class called QuickServlet.java under src\net\code\java\servlet directory. Paste the following code:

package net.codejava.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.annotation.WebServlet;

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

@WebServlet(
	name = "AnnotatedServlet",
	description = "A sample annotated servlet",
	urlPatterns = {"/QuickServlet"}
)
public class QuickServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException {

		PrintWriter writer = response.getWriter();
		writer.println("<html>Hello, I am a Java servlet!</html>");
		writer.flush();
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		String paramWidth = request.getParameter("width");
		int width = Integer.parseInt(paramWidth);

		String paramHeight = request.getParameter("height");
		int height = Integer.parseInt(paramHeight);

		long area = width * height;

		PrintWriter writer = response.getWriter();
		writer.println("<html>Area of the rectangle is: " + area + "</html>");
		writer.flush();

	}
} 

 

4. Writing the JSP page

Under WebContent directory, create a JSP file called index.jsp with the following code:

<html>
<head>
	<title>Quick Servlet Demo</title>
</head>
<body>
	<a href="/QuickServlet">Click here to send GET request</a> 
	
	<br/><br/>
	
	<form action="QuickServlet" method="post">
		Width: <input type="text" size="5" name="width"/> 
		&nbsp;&nbsp;
		Height <input type="text" size="5" name="height"/>
		&nbsp;&nbsp;
		<input type="submit" value="Calculate" />
	</form>
</body>
</html> 

 

5. Compiling the servlet

Type the following command to compile the servlet class:

javac -cp TOMCAT_HOME\lib\servlet-api.jar" -d CLASS_DIRSRC_DIR\QuickServlet.java

Replace:

    • TOMCAT_HOME=C:\Program Files\Apache Software Foundation\Tomcat 7.0.
    • CLASS_DIR = WebContent\WEB-INF\classes
    • SRC_DIR = src\net\codejava\servlet


6. Creating WAR file

Type the following command to package the WebContent directory as a WAR file (Note that there is a dot at the end):

jar cfv deploy\QuickServletApp.war -C WebContent .

Note that there is no web.xml file because we have used the @WebServlet annotation to declare and map the servlet.


7. Deploying and testing the Java servlet

Refer to the tutorial: Java servlet quick start guide for beginner (XML) for deploying and testing the application.

 

Other Java Servlet Tutorials:


About the Author:

is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.

Attachments:
Download this file (QuickServlet.zip)QuickServlet.zip[ ]5 kB
Download this file (QuickServletApp.war)QuickServletApp.war[Servlet annotation version]2 kB

Add comment

   


Comments 

#3avoicu2020-09-11 11:17
Hi! The link on step 7 is to this page, not to the XML example.
Quote
#2umar2020-01-31 11:05
nice tut i like it , what you bhenchod
Quote
#1Mahesh Dinkar Doipho2017-07-31 08:14
Maddy Email Id. Please send me text as early as possible.
Quote