Over a million developers have joined DZone.

Savor the Servlet 3.0

A look at why the Sevrlet 3.0 specification is so useful to Java developers, using JBoss as an example.

· Java Zone

Microservices! They are everywhere, or at least, the term is. When should you use a microservice architecture? What factors should be considered when making that decision? Do the benefits outweigh the costs? Why is everyone so excited about them, anyway?  Brought to you in partnership with IBM.

We have been using Servlets and its versions for decades. The majority of production applications (legacy deployed applications) use Servlet 2.5. Nowadays, more Servlet 3 deployments are happening and people are migrating from Servlet 2.5 to the latest Servlet 3 specification to leverage the power of zero XML,annotation approach and much more.

Lets discuss Servlet 3.0 with an example. The Servlet 3.0 specification is available as JSR 315 in Java EE stack. Many application servlers like JBoss, Jetty, and of course Glassfish are supporting this Servlet specification. In my example, I will be using JBoss application server. You can use your preferred application server and do any required configuration changes for runing this example.

A brief on new specification feature of asynchronicity, although we can provide this feature by using Ajax. Having an inherent quality of server side means we won't be using any more Ajax altogether. Somebody should correct me if I am wrong. AsyncContext, AsyncListener, and AsyncEvent are newly added interfaces, having methods for asynchronicity and some new methods in ServletRequest interface.

It’s easy to define asynchronicity with annotations:

@WebServlet (urlPatterns= {"/MyAsyncServlet3"}, )

One of the motivations of asynchronous programming could be slow services that hold resources keep in background and make other call in process. 

With Servlet 3.0 Annotations, web.xml presence is optional. We can define Servlets, Filters, and Listeners using annotations.

@WebServlet (name="MyServlet3", urlPatterns= {"/MyServlet3"},
initParams= { @WebInitParam(name="param", value="value") })
 @WebFilter (filterName="myfilter", urlPatterns= {"/MyServlet3})
 @WebListener () 

Let's create a simple program to understand these annotations. We require Eclipse as IDE and an application server for this example.

  1. Create a dynamic project in Eclipse, here I've used the name blogsample.

  2. Create a Servlet MyServlet3 and MyAsynchServlet inside directory blog.sample. As Eclipse by default does not support Servlet 3.0, you have to take it as a dependency in your classpath:

    package blog.samples;
    import java.io.IOException;
    import java.io.PrintWriter;
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebInitParam;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    /**
    * This class represents an example of Servlet 3.0
    * Specification simple servlet with annotation
    *
    * @author shakil.akhtar
    *
    */
    @WebServlet(name="MyServlet3", urlPatterns={"/MyServlet3"},
    initParams={ @WebInitParam(name="fname", value="Shakil") })
    public class MyServlet3 extends HttpServlet{
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    PrintWriter out = response.getWriter(); 
    String fname = getServletConfig().getInitParameter("fname"); 
    out.println("Hello "+fname+"!"); 
    out.close();
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    doGet(request,response); 
    }
    }
    package blog.samples;
    import java.io.IOException;
    import java.util.Queue;
    import java.util.concurrent.ConcurrentLinkedQueue;
    import javax.servlet.AsyncContext;
    import javax.servlet.AsyncEvent;
    import javax.servlet.AsyncListener;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    /**
    * This is an example of asynchronous request
    *
    * @author shakil.akhtar
    *
    */
    @SuppressWarnings("serial")
    @WebServlet(urlPatterns = { "/MyAsyncServlet" }, asyncSupported = true)
    public class MyAsynchServlet extends HttpServlet {
    private static final Queue asycnReqQueue = new ConcurrentLinkedQueue();
    public void doGet(HttpServletRequest request, HttpServletResponse response) {
    final AsyncContext ctx = request.startAsync();
    ctx.setTimeout(30000);
    asycnReqQueue.add(ctx);
    //A listener that will listen Async request cycle
    ctx.addListener(new AsyncListener() {
    @Override
    public void onError(AsyncEvent asyncEvent) throws IOException {
    System.out.println("Inside onError");
    }
    public void onComplete(AsyncEvent asyncEvent) throws IOException {
    System.out.println("Inside onComplete");
    asycnReqQueue.remove(ctx);
    }
    public void onTimeout(AsyncEvent asyncEvent) throws IOException {
    System.out.println("Inside onTimeout");
    asycnReqQueue.remove(ctx);
    }
    @Override
    public void onStartAsync(AsyncEvent asyncEvent) throws IOException {
    System.out.println("Inside onStartAsync");
    }
    });
    asycnReqQueue.add(ctx);
    }
    public void doPost(HttpServletRequest request, HttpServletResponse response) {
    doGet(request, response);
    }
    } 
  3. Remove web.xml, as we are using annotations in our example.

  4. Export .war from Eclipse and name it blogsample.war.

  5. To run your example, you need a server supporting the Servlet 3.0 specification. I am using JBoss 7. You can download it from: http://www.jboss.org/jbossas/downloads/. Extract the zip somewhere and deploy blogsample.war into the $JBOSS_HOME\server\default\deploy directory. Now run JBoss and type http://localhost:8080/blogsample/MyServlet3 in the browser. You will see output as "Hello Shakil!". Now test an Async example with  http://localhost:8080/blogsample/MyAsyncServlet. Here is the output:

15:50:43,281 INFO  [STDOUT] Inside onTimeout
15:50:43,281 INFO  [STDOUT] Inside onComplete


In the above example, we saw how to create Servlets with annotations. There are many more in Servlet 3.0 specifications, like dynamic registrations of Servlets and filters, web framework plugins, built-in support for handling file uploads, and modularization of web.xml. You can find these specifications at http://java.sun.com/products/servlet/download.html.

Discover how the Watson team is further developing SDKs in Java, Node.js, Python, iOS, and Android to access these services and make programming easy. Brought to you in partnership with IBM.

Topics:
java ,j2ee ,servlet 3.0

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}