Detailed Explanation of @ WebServlet in jsp Programming

  • 2021-12-05 06:59:31
  • OfStack

After writing the Servlet, the next step is to tell the Web container that there is a little information about the Servlet. In Servlet 3.0, annotations (Annotation) can be used to tell containers which Servlet will provide services and additional information. For example, in HelloServlet. java:


 @WebServlet( " /hello.view " )
  public class HelloServlet extends HttpServlet {
   As long as it is in Servlet Settings on @WebServlet Label, the container will automatically read the information in it. Above @WebServlet Tells the container that if the requested URL Yes " /hello.view ", then by HelloServlet Provides services for an instance of. You can use the @WebServlet Provide more information. 
  @WebServlet(
    name= " Hello " ,
    urlPatterns={ " /hello.view " },
    loadOnStartup=1
  )
  public class HelloServlet extends HttpServlet {

The @ WebServlet above tells the container that the name of HelloServlet, the Servlet, is Hello, which is specified by the name attribute, and if the client requests URL is/hello. view, it is handled by Servlet with the name Hello, which is specified by the urlPatterns attribute. When using annotations in Java EE related applications, remember that properties that are not set usually have default values. For example, if the name property of @ WebServlet is not set, the default value will be the full class name of Servlet.

When the application starts, virtually all Servlet instances are not created. The container instantiates the corresponding Servlet class, initializes it, and then processes the request when an Servlet service is required for the first time. This means that the client requesting the Servlet for the first time must wait for the Servlet class to be instantiated and the initial action must take before it can really get the request processed.

If you want the Servlet class to be loaded, instantiated, and initialized when the application starts, you can use the loadOnStartup setting. Setting a value greater than 0 (the default is-1) means that Servlet will be initialized after starting the application (instead of instantiating several Servlet). Numbers represent the initial order of Servlet, and containers must ensure that Servlet with smaller numbers is initialized first. In the case of annotation, if multiple Servlet use the same number when setting loadOnStartup, the container implementation manufacturer can decide which Servlet to load at its own discretion.

Thank you for reading, hope to help everyone, thank you for your support to this site!


Related articles: