How to Create Servlet Without web.xml | @WebServlet Annotation in Servlet 3

By Arvind Rai, January 12, 2015
Java EE 6 has introduced @WebServlet annotation in servlet 3. Using this annotation we can use servlet without web.xml. @WebServlet provides different elements to configure URL pattern and load-on-startup etc. Servlet container identifies a class as servlet if annotated by @WebServlet Annotation. Here in this page we will create a sample servlet using @WebServlet Annotation.

@WebServlet Annotation

The classes annotated by @WebServlet are considered as Servlet by servlet container. There are optional elements which can be used with @WebServlet.

asyncSupported: If true, servlet supports asynchronous operation.
description: We can provide the description of servlet using this element.
displayName: This is the display name of the servlet.
initParams: Initialization parameter can be provided using this element.
loadOnStartup: This defines the order of the servlet for load-on-startup.
name: Using this element, we provide the name of the servlet.
urlPatterns: URL pattern to access the servlet.

Now find the sample example for annotation based servlet without web.xml
HelloWorldServlet
package com.concretepage;
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(urlPatterns = "/HelloWorldServlet", loadOnStartup = 1)
public class HelloWorldServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException{
	     doGet(request,response);
	}
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException{
	     response.setContentType("text/html");
	     PrintWriter out = response.getWriter();
	     out.println("Hello World!");
	}
} 

Gradle to Resolve Dependency

Find the gradle to resolve the dependency.
build.gradle
 apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'war'
archivesBaseName = 'ServletDemo'
version = '1' 
repositories {
    mavenCentral()
}
dependencies {
    compile 'javax.servlet:javax.servlet-api:3.1.0'
}  

Demo Project structure in Eclipse

Find the demo project structure in eclipse.
How to Create Servlet Without web.xml | @WebServlet Annotation  in Servlet 3

Output

Open command prompt and go to project root directory. Use command as below
gradle eclipse: to setup classpath in eclipse.
gradle clean build : to build the war file.
Use the URL as http://localhost:8080/ServletDemo-1/HelloWorldServlet
to access the servlet.
How to Create Servlet Without web.xml | @WebServlet Annotation  in Servlet 3

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us