Hello world servlet annotation example

This post shows you how to create a servlet annotation example using an example, servlet 3.0 has introduced an annotation based mapping instead of web.xml mapping. That makes web.xml optional in the latest servlet application.

If you do not have prior knowledge in servlet 2, don’t worry you can start learning servlet 3 directly web.xml knowledge is not needed.

Requirement

JDK 8 or greater version

Latest Eclipse EE for the web developer

Servlet 3. 1 jar or greater version

Tomcat 8.5 or greater version

Creating a first web application in servlet 3

Right click and create a new dynamic web project with web module version greater than 3.0.

Create a new HTML file – Right click on web content –> new –> HTML > give file name as index.html

index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

   Welcome to servlet 3.x hello world example
<br>
<br>

<a href="MyAction">Click here</a>

</body>
</html>

Now create a servlet — Right click on src–>new –>servlet –> give a file name as HelloServlet. remove all methods and constructor except doGet method for our hello world example

Provide your HTML action name in @WebServlet annotation.

HelloServlet.java

package com.candidjava;

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

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

@WebServlet("/MyAction")
public class HelloServlet extends HttpServlet
{
   protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
   {
      response.setContentType("text/html");

      PrintWriter pw=response.getWriter();
      pw.write("<h1> Welcome to Servlet <h1> <br>");
      pw.write("<h2> you have successfully received your response <h2> <br>");
   }
}

Add servlet jar

Add tomcat to the server environment

How to run

right click on index.html — Select RunAs–> run on server –> select tomcat and click finish

 

Output Screenshot

 Download

servlet-helloworld-3 zip

Servlet 3 hello world war

 

 

 

 

 

Leave a Reply

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