Create Servlet using Annotation – Servlet 3.0

Author posted by Jitendra on Posted on under category Categories Servlet and tagged as Tags with Leave a comment on Create Servlet using Annotation – Servlet 3.0

Create the Servlet without any deployment descriptor. Using Annotations

Before reading this article, i will suggest readers to go through the version table of J2EE.

One of the most appraised feature of Servlet 3.0 is the support of the annotations to create the Servlet. Before  this the Deployment Descriptor (web.xml) was used to create the servlet mapping , defining init parameters etc. All the settings can be now achieved without any entry in web.xml.

Prerequisite:

  1. JDK 5.0 and above.
  2. Tomcat 7
  3. Eclipse 3.6 – Helios (as of now, it only supports Tomcat 7)

We will start with creating the Servlet class :

package com.g2.servlet;

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

import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(
		name="TestServlet",
		urlPatterns={"/test","/testServlet"},
		initParams={
				@WebInitParam(name="db",value="Oracle"),
				@WebInitParam(name="jdk",value="6"),
				@WebInitParam(name="tomcat",value="7")
				}
			)
public class ServletUsingAnnotation extends HttpServlet{

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		PrintWriter pw = res.getWriter();

		res.setContentType("text/html");
		pw.write("Running Servlet using Annotation..");
		pw.write("<br />");
		pw.write("-- Init parameters --");
		pw.write("<br />");
		pw.write("db : "+this.getInitParameter("db"));
		pw.write("<br />");
		pw.write("jdk : "+this.getInitParameter("jdk"));
		pw.write("<br />");
		pw.write("tomcat : "+this.getInitParameter("tomcat"));
	}
}

As you can see in above code, we have used annotation “@WebServlet” to declare this class as servlet. to pass the init parameter to servlet, we have used “@WebInitParam“. Before Servlet 2.5 we were not able to specify multiple url for the same servlet. As you can see in above code, we have given two URLs for the same servlet.

Create “index.jsp” page :

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Creating servlet using Annotation</title>
</head>
<body>
<a href="../test">Servlet using Annotation</a>
</body>
</html>

After clicking on hyperlink on page “index.jsp” Servlet will open with following output.

Running Servlet using Annotation..
— Init parameters —
db : Oracle
jdk : 6
tomcat : 7

Related posts