Java EE 6. What's New in Servlet API 3.0



    With the release of Java EE 6, along with significant changes in JPA 2.0, the servlet 3.0 specification also underwent a number of improvements: simplified development and deployment procedures, configuration became more convenient, support for asynchronous requests appeared, and the security model improved. Next, I will try to highlight the main changes in the API.

    Servlet programming and deployment was simplified mainly by introducing annotations for declaring servlets (@WebServlet), filters (@WebFilter), listners (@WebListener), and security restrictions (@ServletSecurity). Thus, the deployment descriptor web.xml has become an optional element. I draw your attention to the fact that the components of the Servlet API themselves did not become POJO, no one has canceled the usual hierarchy of interfaces and classes. An annotation has also been added to support @MultipartConfig file downloads and to set @WebInitParam initialization parameters.

    Hello World Servlet Example
    package net.ismailov.tests;

    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    import java.io.PrintWriter;

    @WebServlet(name="hw", urlPatterns = "/hello_world")
    public class HelloWorld extends HttpServlet{

      public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        PrintWriter writer = response.getWriter();
        writer.println("

    Hello, World!

    ");
        
      }

    }


    The good news is the ability to dynamically register servlets:
    ServletRegistration.Dynamic dynamic =
    servletContext.addServlet(“DynamicTestServlet”, “net.ismailov.DynamicTestServlet”)
    dynamic.addMapping(“/dynamicServlet”);



    To support long-running operations, the option of asynchronous servlet operation has been added. To enable this feature, you must:
    //Либо декларативно указать поддержку асинхронного режима
    @WebServlet(asyncSupported=true)
    //Либо установить при динамической инициализации сервлета
    dynamic.setAsyncSupported(true);

    After this, response does not cease to exist at the end of the method. Must call
    AsyncContext ctx = ServletRequest.startAsync(req, res)

    Now the request and response instances will be saved, and, upon completion of the asynchronous method execution, can be used to output to the user one of the AsyncContext.dispatch methods (/ * various parameters * /)
      @WebServlet("/MyAsyncTestServlet" asyncSupported=true)
      public class TestServlet extends HttpServlet {
        public void doGet(HttpServletRequest req, HttpServletResponse res) {
          ...
          AsyncContext aCtx = request.startAsync(req, res);
          ScheduledThreadPoolExecutor executor = new ThreadPoolExecutor(10);
          executor.execute(new MyAsyncService(aCtx));
        }
      }

      public class MyAsyncService implements Runnable {
        private AsyncContext ctx;
        public MyAsyncService(AsyncContext ctx) {
          this.ctx = ctx;
        }
        public void run() {
          // Может быть вызвана долгая операция с последующим выводом
          ctx.dispatch("/result.jsp");
      }


    As already mentioned, with the new API it has become possible to set access restrictions, for example:

    @WebServlet(name="hw", urlPatterns = "/hello_world")
    @ServletSecurity(@HttpConstraint(rolesAllowed = {"admin"}))
    public class HelloWorld extends HttpServlet{

    Naturally, the task of assigning roles / users, as well as authentication, are vendor-specific. For example, glassfish issues a basic http auth form:



    It is also possible to impose restrictions on access methods:
    @ServletSecurity(httpMethodConstraints={ @HttpMethodConstraint("GET"),
      @HttpMethodConstraint(value="POST", rolesAllowed={"user_group_1"})})


    I tried to reflect the main innovations in api 3.0, it remains only to note that since December last year, a “reference implementation” of the Java EE6 specification: Glassfish 3.0 , in which you can experiment with the new API, is available.

    Also popular now: