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

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:

    • @HandlesTypes
    • @HttpConstraint
    • @HttpMethodConstraint
    • @MultipartConfig
    • @ServletSecurity
    • @WebFilter
    • @WebInitParam
    • @WebListener
    • @WebServlet

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.

Recommended Book: Head First Servlets and JSP [Kindle version]

 

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

 


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> 

 Recommended Book: Head First Servlets and JSP: Passing the Sun Certified Web Component Developer Exam

5. Compiling the servlet

Type the following command to compile the servlet class:

javac -cp TOMCAT_HOME\lib\servlet-api.jar" -d CLASS_DIR SRC_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 web application

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

Related Course: Servlets and JSPs: Creating Web Applications With Java

Recommended Book: Servlet & JSP: A Tutorial (A Tutorial series)

Submit to DeliciousSubmit to DiggSubmit to FacebookSubmit to Google BookmarksSubmit to StumbleuponSubmit to TechnoratiSubmit to TwitterSubmit to LinkedIn
Attachments:
Download this file (QuickServlet.zip)QuickServlet.zip[ ]5 kB
Download this file (QuickServletApp.war)QuickServletApp.war[Servlet annotation version]2 kB