Servlet without web.xml

One of the new features in Servlet 3.0 is the introduction of annotation to define a servlet, thus making web.xml optional. The following is a simple web app that only contains a servlet:

1. create project directory structure:

mkdir nowebxml
cd nowebxml/
mkdir -p src/test build/WEB-INF/classes
2. create TestServlet.java in src/test
cd src/test

package test;

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

import javax.ejb.EJB;
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(urlPatterns = "/TestServlet", loadOnStartup = 1)
public class TestServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);

protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter writer = response.getWriter();
writer.println("A servlet without web.xml: " + getServletName());
3. compile and package
javac -cp "$GLASSFISH_HOME/modules/*" -d ../../build/WEB-INF/classes/ TestServlet.java

cd ../../build/

jar cvf nowebxml.war WEB-INF/
4. deploy
cp nowebxml.war $GLASSFISH_HOME/domains/domain1/autodeploy/
5. run TestServlet
curl http://localhost:8080/nowebxml/TestServlet
A servlet without web.xml: test.TestServlet
GlassFish V3 is used for deploy and running the test web app, but this web app is portable and should work with any container that supports Servlet 3.0.

My javac command uses a wildcard in classpath values, which is only supported in Java SE 6 or later. Classpath wildcard is very convenient, especially in testing. In addition, Servlet 3.0 is part of Java EE 6, which itself requires Java SE 6.


servlet said...

Nice tutorial.
See http://www.jsptube.com/servlet-tutorials/servlet3/new-features.html

as well

Unknown said...

Great and Useful Article.

Online Java Training

Java Online Training India

Java Online Course

Java EE course

Java EE training

Best Recommended books for Spring framework

Java Interview Questions

Java Course in Chennai

Java Online Training India

Unknown said...

I enjoyed on reading your blog post. Very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article. Please visit my website, Friv 4000 Games is where all the free friv games.
Friv 4000