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.

Followers

Pageviews Last 7 Days