Search This Blog

Wednesday, May 9, 2012

Differences in Creating a Servlet in versions 2.5 and 3.0 Of the Servlet Spec.

Differences in Servlet Definitions between v2.5 and v3.0

The following 2 examples show the difference between how a Servlet Java Class and associated web.xml deployment descriptor was changed in the upgrade from version 2.5 to version 3.0 of the Servlet Specification. I found this a simple and interesting look at the way the definition of a Servlet in code has now been simplified through the use of annotations from JSR 175.

2.5 Version of Servlet Definition 

Java Class Of Servlet in 2.5

public class MyServlet extends HttpServlet {
    public void doGet (HttpServletRequest req, HttpServletResponse res) {
        ....
    }
}

Deployment descriptor in 2.5 (web.xml)

<web-app>
    <servlet>
        <servlet-name>MyServlet</servlet-name>
        <servlet-class>samples.MyServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>MyServlet</servlet-name>
        <url-pattern>/MyApp</url-pattern>
    </servlet-mapping>
    ...
</web-app>

3.0 Version of Servlet Definition 

Here is the much simplified version written to the Servlet 3.0 API. As MyServlet is annotated as a servlet using the @Servlet annotation, it gets initialized during the start-up of the web container. Note that the deployment descriptor is optional in this case.

Java Class Of Servlet in 3.0

@Servlet(urlMappings={"/MyApp"})
public class MyServlet {
    @GET
    public void handleGet(HttpServletRequest req, HttpServletResponse res) {
        ....
    }
}

Deployment descriptor in 3.0 (web.xml) - Optional


8 comments: