• The use of servlet


    Servlet is a java code run in the server such as Tomcat.

    How to create a servlet?

      1.Create a class extends HttpServlet (or implements the Servlet interface or extends the GenericServlet)

      2.Override the doPost and doGet (if implements the Servlet interface , you should override all the methods : init() service() getServletConfig() getServletInfo() destroy())

      3.Configure the Servlet in the web.xml.

    The structure of Servlet:

      javax.servlet.Servlet interface

        ----->  javax.servlet.Genericservlet abstract class

          ------> javax.servlet.http.HttpServlet

            ------> the class extends or implements xxx you defined by yourself

    The life-cricle of servlet:

      1.create the servlet and call the init() to initialize the servlet.

      2.process the request via service().

      3.destroy the servlet via destroy() and the garbage collect the servlet.

    When we create the serlet , the first access to the servlet will create the object of servlet constructor , then call the init() method . But the init() will be called once.

    Importantly , there will start a thread to call the service() . Because the web apps are multi-thread application.

    When we access to the server, there will open a new thread to call the service.

    The servlet object usually created once and it stays at the memory for a long time.

    When the server stop or the servlet object was destroyed the destroy() method will be called.

    Notice:

      if you create the member variables in servlet , may lead to the secure problems.

      So, we should avoid to create member variables in servlet. If must, we should synchronize it.

    About doGet() and doPost():

      According to the url, we can find the servlet from the web.xml to call the service(). The service() in HttpServlet is extended from GenericServlet and includes doGet() and doPost().

      Tell from the method name, the service could tell which method to use. And here involves a design pattern: Template method model.

    The load-on-startup of servlet:

      We can see that the servlet constructor is constructed when we access the url. So how to construct and instantiate the servlet when the server starts up ?

      We can add the tag <load-on-startup> in <servlet> tag of web.xml:

                                  <servlet>

                                    <load-on-startup>2</load-on-startup>     -----> it meas the priority, the value could set from 1 to 10, but 1 has been                                                          used in server, so we often use 2.

                                  </servlet>

      Why should we start the servlet with the Server?

        Could load some resourece in advance and create the database or data for the web application.So the performance will impove in some degree.

    Details about url-pattern:

      1.Could one servlet map to several path?

        Yes! For example:

            <servlet-mapping> 

              <servlet-name>LifeServlet</servlet-name>

              <url-pattern>/life</url-pattern>

            </servlet-mapping>

            <servlet-mapping> 

              <servlet-name>LifeServlet</servlet-name>

              <url-pattern>/life1</url-pattern>

            </servlet-mapping>

        The ****/life and ****/life1 equals.

      2.How to write the url-pattern?

        1.The full name whcih starts with "/"

        2.Use the wildcard:

          2.1 match the directory: start with "/" and end with "*"

          2.2 match the extensibel name: can't start with "/" and end with "*.xxx" usually "*.action". 

             classical mistake:  /*.do

    The path of servlet:

        1. Absolute path:

          1.1 with protocol:

            <a href="http:localhost:8080/day7_2/demo1">demoServlet</a>

            This way is not often used, if used, usually access to other project not this web project.

          1.2 without protpcol

            <a href="/day7_2/demo1 ">demoServlet</a>

            Write "/" in the browser, the "/" equals the root path of the server. "/" means "http://localhost:8080", and we can add the project's name and the resource name.

            From the following, "day7_2" is the project's name and the "demo1" is the resource's name.

            This way is widely used in appliaction development, it can accees to the inner project resource. This is widely used!!!   /project's name/resource's name

        2.Relative path:

          2.1 

            http://localhost:8080/day7_2/demo1      -----> servlet path 

            http://localhost:8080/day7_2/admin.html    -----> html path

            The relative path could be set: <a href="./demo1">demoServlet1</a> 

            The "." represents the "http://localhost:8080/day7_2".

            Also this path could be simplified as <a href="demo1">demoServlet1</a>

        Create a folder called "jsps" in the WebRoot directory, put the admin.html in it, when we access the admin.html, the absolute path will be ok,

        while the relative path will encounter error. How to solve it?

            set the path: <a href="../demo1">demoServlet1</a>

        Conclusion: we recommend the absolute path without protocol in application developing:

          how to write: /project's name/ the value of <url-pattern> in servlet.

    The init() of Servlet interface:

      1:We know that the init(ServletConfig config) in Servlet interface has parameter, and its parameter type is ServletConfig, but its overrided init() doesn't have parameter, why?

        Reason: the GenericServlet has overrided the init(ServletConifg config) -----> init(), and we don't need to override it anymore, What we override located in GenericServlet rather than

        in the Servlet interface.

      2:What is the ServletConfig? And what's the function of ServletConfig?

        In the GenericServlet has the following funcntion:

          public void init(ServletConfig config) throws ServletException{

            this.config = config;

            this.init();

          }

        ServletConfig: the servlet configuration object used by a servlet container to pass information to a servlet during the initialization.

        We can get the configuring data in the web.xml file by ServletConfig.When we access to the servlet, the server will instantiate the servlet object and create the ServletConfig object.

        Pass the ServletConfig to the servlet via init() method.

    How to get the ServletConfig?

      The servlet we defined extends the GenericServlet class and there is a method called getServletConfig(), so the defined class also has this method:

        ServletConfig config = this.getServletConfig();

        // we can get the information in web.xml:

        String name = config.getServletName();

    ServletContext:  

      The ServletContext represents a web application. Each servlet has its own ServletConfig, and in one web application, the web application has its own ServletContext.

      It means every web application has its own ServletContext. Every ServletContext can be shared by all servlets in the web application.

      Common methods of ServletConfig:

        1. get the servlet's name:

          public String getServletName();

        2. get the value of init-param in web.xml. And the init-param should be defined in the servlet tag.

          public String getInitParameter(String tagName);

        3. get the Enumeration of all the init-param's names in the web.xml

          public Enumeration getInitParameterNames();

    When to create the ServletContext?

      When the server starts up, the container will create a ServletContext object for the web application, which represents the web application.

    How to get the ServletContext?

      //1. get the ServletConfig first

      ServletConfig config = this.getServletConfig();

      //2. get the ServletContext via ServletConfig

      ServletContext context1 = config.getServletContext();

      But in fact we often get the ServletContext via the following method:

      ServletContext context2 = this.getServletContext();

    There is one note: the ServletConfig and the ServletContext are both created by the server not by us.

     What's the function of ServleContext?

      1.get the initialization parameter of the web application:

        String getInitParameter(String name):

          Returns a String containing the value of the named context-wide initialization parameter, or null if the parameter does not exist. 

        Enumeration getInitParameterNames():

          Returns the names of the context's initialization parameters as an Enumeration of String objects, or an empty Enumeration if the context has no initialization parameters. 

        Press "F2" at the <web-app> in web.xml, we can see the introduction of this tag. There is a tag called <context-param> it just is the context's parameter.

        From the description of this help document, we can find that the element can be put at a arbitrary oder.

        The ServletContext's configure is aimed to the whole application, while the ServletConfig is aimed at the Servlet.

        The whole appliacation shares the same ServletContext, every Servlet communicate with each other via the ServletContext, so the SerlvetContext also called domain object.  

      2.share the information in the servlet

        The ServletContext is a domain object, and the data in servlet is shared via ServletContext:

        

      3.get the path(resource)[important]

        In the web development, if you want to get the resource, you must get the absolute disk path.[*****]

        3.1How to get the absolute disk path?

          String getRealPath(String path);

          context.getRealPath("/file's path");

      Distinguish the different file path:

      

     

         3.2 URL getResource(String path): get a URL object, it can get a path String via getPath(), which is our path of web project

          String pojectPath = context.getResource("/").getPath();

        3.3 InputStream getResourceAsStream(String path): get an inputstream of specific resource

        other: there is a method to get the class file in classes directory:

          Class.getResource("/").getPath();// this method could get the class file's absolute disk path

      4.other function:

        4.1 get the MIME type:

          String getMimeType(String file): will use it when we download file.

    Default Servlet: if there is no command to match the url-pattern the server will use this servlet to handle it. The default servlet's url-pattern is "/".

         

        

            

        

  • 相关阅读:
    SDN大作业
    第06组 Beta版本演示
    SqlServer 将多行字段合并成单行
    C# MD5加密字符串
    Request.IsAjaxRequest()总是返回false
    Mybatis 语句包含单引号的写法
    idea每次启动maven项目都貌似读不到配置
    idea下springboot项目配置文件application.properties不生效的问题
    Ubuntu 设置时区
    SpringBoot 使用MyBatis
  • 原文地址:https://www.cnblogs.com/ppcoder/p/7189484.html
Copyright © 2020-2023  润新知