J2EE – Servlet Annotation

Previously, we configure our HelloWorld servlet by hooking up with url “/helloworld” in the web.xml. There is another way of configuring this and it is called the servlet annotation and specifically we are going to use @WebServlet.

Let’s start coding

Back in the HelloWorldServlet.java, before the class name, we simply put @WebServlet(“/helloworld”), that is with the url pattern within the parenthesis. Let’s remove the <servlet> and <servlet-mapping> tag inside the web.xml and restart the applciation. When the application has restarted, you should be able see the same result.

package com.davidcheah.webapplication.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

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

public class HelloServlet extends HttpServlet {
	public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
		PrintWriter out = response.getWriter();
		out.println("<html><body><h1>Hello World</h1>");
		out.println("<p>The time is " + new Date() + "</p>");

Source Code


About the author

Founder of tattweicheah.com. Loves music, sport and most importantly software development.

Leave a Reply

Your email address will not be published. Required fields are marked *