Monday, December 19, 2016

Create Java Servlet Using @annotation

Web applications are configured by means of web.xml. That means you have to configure web components like WebServlet, WebListener, WebFilter, WebInitParam etc in deployment descriptor i.e. web.xml.

From Servlet 3.0, Web components can be deployed by using annotations. This will be easier for quick development. But if both web.xml and annotation present for a component, then the deployment descriptor (web.xml) configurations will be executed because it'll override the annotation declaration.

The @WebServlet annotation is used to declare a servlet. The annotated class must extend the javax.servlet.http.HttpServlet class.

Min. App. Servers requirements: Tomcat7, GlassFish, WebLogic Server, JBoss

Syntax

@WebServlet(
    attribute1=value1,
    attribute2=value2,
    ...
)
public class TheServlet extends javax.servlet.http.HttpServlet {
    // servlet code...
}
 

Attributes of @WebServlet

Name
Type
Required
Description
value
or
urlPatterns
String[]
Required
Specify one or more URL patterns of the servlet. Either of attribute can be used, but not both.
name
String
Optional
Name of the servlet
displayName
String
Optional
Display name of the servlet
description
String
Optional
Description of the servlet
asyncSupported
boolean
Optional
Specify whether the servlet supports asynchronous operation mode. Default is false.
initParams
WebInitParam[]
Optional
Specify one or more initialization parameters of the servlet. Each parameter is specified by @WebInitParam annotation type.
loadOnStartup
int
Optional
Specify load-on-startup order of the servlet.
smallIcon
String
Optional
Specify name of the small icon of the servlet.
largeIcon
String
Optional
Specify name of the large icon of the servlet.
NOTE: the attributes displayName, description, smallIcon and largeIcon are primarily used by tools, IDEs or servlet containers, they do not affect operation of the servlet.
 

Examples

A servlet is annotated with only the URL pattern:

@WebServlet("/myServlet")
public class MyServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.getWriter().println("Hello");
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       
        super.service(req, resp);
       
    }
}
Here the servlet MyServlet is mapped to the URL pattern /myServlet. When accessing this servlet by Get method [accessing by only the URL], it will return a “Hello” message.

A servlet is annotated with multiple URL patterns:

@WebServlet(urlPatterns={"/sendFile", "/uploadFile"})
 
public class UploadServlet extends HttpServlet{
 
   @Override
     protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException,   IOException {
        PrintWriter writer = resp.getWriter();
        writer.print("<html>");

        writer.print("<body>");
        writer.print("<h1>Sample HTML Respose</h1>");
        writer.print("
</body>");
        writer.print("
</html>");
    }

   @Override

   protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.service(req, resp);
    }
  
}
Here the servlet UploadServlet is mapped to the two URL pattern /sendFile and /uploadFile. When accessing this servlet by Get method [accessing by only the URL], it will return HTML output.

Declare a servlet with additional information:


@WebServlet(
        name="MyOwnServlet",
        description="This is my annotated servlet",
        urlPatterns="/MyOwnServlet"
        )

public class OwnServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.service(req, resp);
    }
    
}
Here the servlet OwnServlet is mapped to  URL pattern /MyOwnSerlet. When accessing this servlet by Get method [accessing by only the URL], it will return BLANK page.

Declare a servlet with some init parameters:


@WebServlet(urlPatterns="/paramTest",
        initParams={
                        @WebInitParam(name="dir",value="d:/test"),
                        @WebInitParam(name="types", value="pdf,doc,docx")
                    }
        )

public class InitParamTestServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String dir = getInitParameter("dir");
        String types = getInitParameter("types");
      
        PrintWriter writer = resp.getWriter();
        writer.write(dir);
        writer.write(types);
    }
  
}
Here the servlet InitParamTestServlet is mapped to  URL pattern /paramTest. When accessing this servlet by Get method [accessing by only the URL], it will print the values of initialization parameters.

Declare a servlet with asynchronous operation mode and load-on-startup order:


@WebServlet(
            urlPatterns="/taskController",
            loadOnStartup=1,
            asyncSupported= true
        )

public class BackgroundProcess extends HttpServlet{

    @Override
    public void init() throws ServletException {
        System.out.println("Background Process started.....");
    }
  
}
The servlet BackgroundProcess is mapped to  URL pattern /taskController. Here loadOnStartup=1 means that the servlet is initialized by the container when it starts up or when the application is deployed. Value 1 means that the priority level of the servlet is 1 [most] for the application server or container. The app server or container calls the init() method of the servlet when the server being started or the application being deployed.

You can starts multiple servlet of a web application by the server using this annotation with a specific order. If the value of this annotation  is same for multiple servlets, then the container will decide the initialization orders of them[ i.e. sometimes initialized by order of names].

We also specify the servlet supports asynchronous mode by using asyncSupported= true.
 




No comments:

Post a Comment