Java Web (1) Servlet detailed explanation! !

1. What is a servlet?

    The process of processing a request and sending a response is done by a program called a servlet, and a servlet is something derived from implementing dynamic pages. The premise of understanding this is to understand something about the http protocol and know the B/S mode (browser/server).

    B/S: Browser/Server. The browser accesses the server through the URL, such as visiting Baidu, and entering www.baidu.com in the browser. At this time, the browser will display the home page of Baidu. So what are the steps in this specific process? This is to understand the http request and response

                  

    Request, response: You should know these two specific contents through the link given

 

Second, the relationship between tomcat and servlet

    Tomcat is a Web application server and a Servlet/JSP container. As a servlet container, Tomcat is responsible for processing client requests, sending requests to Servlets, and sending Servlet responses back to clients. Servlets are a kind of Servlet that runs in Java language. A component on a server. The most common use of servlets is to extend Java web server functionality, providing a very secure, portable, and easy-to-use alternative to CGI.

    It can be known from the request and response in the http protocol that the request sent by the browser is a request text, and what the browser receives should also be a response text. But in the above picture, I don't know how to change it. I only know that the request sent by the browser is the request, and we use the response when we respond back. I ignored the details, let's explore it now.

              

      ①: Tomcat receives and parses the http request text, and then encapsulates it into a request object of type HttpServletRequest. All HTTP header data can be queried by calling the corresponding method on the request object.

      ②: Tomcat will also encapsulate the information to be responded as a response object of type HttpServletResponse. By setting the response attribute, you can control the content to be output to the browser, and then hand the response to tomcat, and tomcat will turn it into the format of the response text send to browser

 

    The Java Servlet API is the interface between the servlet container (tomcat) and the servlet. It defines various methods of servlet, and also defines the object class that the servlet container transmits to the servlet, the most important of which are ServletRequest and ServletResponse. So when we write servlet, we need to implement the servlet interface and operate according to its specifications.

 

3. Write Servlet

    In the front, we already know what a servlet is, why do we need a servlet? (In order to achieve dynamic web pages instead of displaying static web pages, you can check the specific situation in Baidu), the relationship between tomcat and servlet? And other issues. Now to manually write a servlet.

    3.1. Manually write servlet.

      1. Create a MyServlet to inherit HttpServlet, rewrite the doGet and doPost methods, that is, to see whether the request is get or post, and then use different processing methods to process the request,

            

      2. Configure MyServlet in web.xml, why do you need to configure it? Let the request sent by the browser know which servlet to reach, that is, let tomcat find the corresponding servlet for the encapsulated request to use.

            Configure four things.

                

            After configuration, how does the browser find the corresponding servlet through the information we configured.

                

            Follow the steps. First, the browser finds the url-pattern in web.xml through http://localhost:8080/test01/MyServlet. This is the first step. After matching the url-pattern, it will find the servlet of the second step. Name MyServlet, know the name, you can find the third step through servlet-name, and when the third step is reached, you can know the location of the servlet. Then go to it to find the corresponding processing method to deal with.

       3. Experiment to verify that the above configuration is successful.

               

            

    3.2. Use the wizard to create a new MyServlet

        This is relatively simple, web.xml does not need us to configure manually, the tool directly helps us configure it automatically

            1. Right-click the project, and there is an option to create a new servlet directly in the new option.

            2. Configure the information in the MyServlet class

                

          3. Configure the servlet information in web.xml

                  

        4. Look at the code and web.xml in the MyServlet01 class. The configuration is the same as the manual configuration, but it is generated by using a graphical interface to make it easier for us to create servlets.

 

    3.3, explain the principle of creating servlet in detail

        1. What is the life cycle of a servlet?

        2. Why does the created servlet inherit from httpServlet instead of directly implementing the Servlet interface?

        3. In the life cycle of servlet, it can be seen that the service method is executed. Why do we only need to write the doGet and doPost methods?

        We should all know this series of questions, instead of simply knowing how to configure and use servlets? The above questions will be answered one by one.

        1. What is the life cycle of a servlet?

          When the server starts (configure load-on-startup=1 in web.xml, the default is 0) or when the servlet is requested for the first time, a servlet object will be initialized, that is, the initialization method init(ServletConfig conf) will be executed.

          The servlet object handles all client requests and executes it in the service(ServletRequest req, ServletResponse res) method

          Finally, when the server is shut down, the servlet object will be destroyed and the destroy() method will be executed.

              

        2. Why does the created servlet inherit from httpServlet instead of directly implementing the Servlet interface?

        3. In the life cycle of servlet, it can be seen that the service method is executed. Why do we only need to write the doGet and doPost methods?

          View the source code, the inheritance structure of httpServlet.

             httpServlet inherits GenericServlet. Those who understand should know immediately, what is the role of GenericServlet (generic Servlet)? The general idea is to implement the method of the Servlet interface and simplify the steps of writing servlet. Details are as follows

                

             The inheritance structure of GenericServlet implements the Servlet interface and the ServletConfig interface,

                    

             Servlet interface content

                  

                As you can see from here, the three key methods of the Servlet life cycle, init, service, destroy. There are two other methods, a getServletConfig() method to get the ServletConfig object, the ServletConfig object can get some information about the Servlet, ServletName, ServletContext, InitParameter, InitParameterNames, you can know by looking at the ServletConfig interface

             ServletConfig interface content

                 

                The ServletContext object is the servlet context object, which has many functions. After obtaining the ServletContext object, you can obtain most of the information we need, such as obtaining the path of the servlet, and other methods.

               At this point, you know the content and function of the Servlet interface. To sum up, the three life cycle operation methods can obtain ServletConfig, and ServletContext can be obtained through ServletConfig. After GenericServlet implements the Servlet interface, it means that we can directly inherit GenericServlet, and we can use the methods in the Servlet interface we introduced above. We can get ServletConfig and ServletContext, but that is too troublesome. The ServletContext cannot be obtained directly, so GenericServlet implements the ServletConfig interface in addition to the Servlet interface, so that the ServletContext can be obtained directly.

              Detailed explanation of the content of the GenericServlet class

                     

                Looking at the picture above, the red boxes are the methods implemented by the Servlet and ServletConfig interfaces. There are 9 methods, which is normal, but we can find that there are two init methods, one with parameters ServletConfig, and one with or without The method of reference, why is it designed this way? Here we need to know what is done in it, let's see what these two methods do respectively?

                init(ServletConfig config)

                      

                init()

                      

                A member variable config

                      

                getServletConfig()

                      

                To explain through these methods, first look at the init (ServletConfig config) method, because only init (ServletConfig config) has a ServletConfig object, in order to facilitate the direct use of the ServletConfig object in other places, not just limited to init (ServletConfig config) method, so create a private member variable config, assign it to config in the init(ServletConfig config) method, and then get the ServletConfig object through the getServletConfig() method, which is understandable, but in In init (ServletConfig config), line 158, an init() method is also called, and this init() method is empty, what is not read, why is this? The reason for this is to prevent one thing. When we need to do something else in the init method, the way we think of is to inherit GenericServlet and rewrite the init(ServletConfig config) method. This dependency will destroy the original GenericServlet class. The code written in init (ServletConfig config), that is, the member variable config in the GenericServlet class will always be null and cannot be assigned, because it is rewritten, it will not be executed in the init (ServletConfig config) method in GenericServlet. code. To assign a value, you must call the parent class's init(ServletConfig config) method in the overridden init(ServletConfig config) method, which is super. init(ServletConfig config), in this way, it is very inconvenient, and I am afraid that sometimes I will forget to write this code, so add an init() method to the GenericServlet class, and you need to initialize other data in the init method later. You only need to rewrite the init() method without overwriting the init(ServletConfig config) method. This design is much better, and you don't need to care about the content of init(ServletConfig config). There are no other problems.

                service(ServletRequest req, ServletResponse res)

                      

                   An abstract method, indicating that the content is not implemented in the GenericServlet class, then what we think is that there must be a layer above it, that is, there is a subclass that inherits it and implements this method, if we write our own Servlet Inheriting GenericServlet, you need to write the service method yourself. Isn't that exhausting, and we can see that the parameters in the service method are still ServletRequest and ServletResponse. It's not linked to http-related objects, so let's look below.

           Detailed HttpServlet class

               Inheriting the GenericServlet class, through our speculation above, the main function of this class must be to implement various details and designs of the service method. And you can know from the class name that the class is linked to http.

                     

                Pay attention to the service(HttpServletRequest req, HttpServletResponse resp) method and the service(ServletRequest req, ServletResponse res) method.

                  service(ServletRequest req, ServletResponse res)方法

                        

                    One thing to do in this method is to force the two objects of ServletRequest and ServletResponse into HttpServletRequest and HttpServletResponse objects. Why can it turn like this?

                      First of all, you need to know what type of req and res are. By printing System.out.println(req), you can know that the actual type of req is the source code in org.apache.catalina.connector.RequestFacade Tomcat.

                        

                          

                    As can be seen from the figure, the inheritance structure of req: RequestFacade, httpServletRequest, ServletRequest, we know that req itself is ServletRequest, then from the perspective of inheritance structure, it can also be regarded as HttpServletRequest, or ServletRequest, so the forced conversion to HttpServletRequest is Yes, if you don't understand, let me give an example, ArrayList, List, Object, Object obj = new ArrayList(); List list = new ArrayList(); An ArrayList object can be regarded as a List object, or it can be regarded as an Object Object, can obj be called a List object now? The answer is yes, because obj is an ArrayList object. Since it is an ArrayList object, it can be regarded as a List object. In the same way, RequestFacade corresponds to ArrayList, httpServletRequest corresponds to List, and ServletRequest corresponds to Object.

                    After converting to httpServletRequest and HttpServletResponse objects, call the service(HttpServletRequest req, HttpServletResponse resp) method.

                service(HttpServletRequest req, HttpServletResponse resp)

                    This method is to determine what the request method is from the browser. Each processing method is different. We commonly use get, post, and there may be a lot of content in our processing method. Therefore, in this method, we will The other 5 request methods such as get and post are extracted and turned into a single method. Then when we need to write a servlet, we can directly rewrite the doGet or doPost method instead of rewriting the service method, which is more targeted. So here we go back to the situation when we wrote the servlet above, inheriting httpServlet, and as long as we rewrite two methods, one doGet and one doPost, in fact, the service method will call one of these two methods (see the request method). So that answers the question 3 we asked at the beginning.  

                     

Fourth, several key objects. ServletConfig, ServletContext, request, response

       Explain four categories, ServletConfig object, ServletContext object, request object, response object

    ServletConfig object

        Access: getServletConfig(); 

        Function: As mentioned above, you can get four things,

              

            getServletName(); //Get the name of the servlet, which is the servlet-name we configured in web.xml

            getServletContext(); //Get the ServletContext object, the function of which is explained below

            getInitParameter(String); //Get the value of the parameter initialized in the servlet. Note here the distinction from global initialization parameters. This gets only the initialization parameters under the servlet

                

             getInitParameterNames(); //Get the names of all initialization parameters in the Servlet, that is, the key value. You can find the value of each initialization parameter through the key value. Note that the return type is an enumeration

                

                

                

           Note: In the source code process we analyzed above, we know that we can directly use its methods without first obtaining ServletConfig, and then obtaining its various parameters, such as the ServletConfig().getServletName() we used above; It can be written directly as getServletName(); instead of getting ServletConfig(); first, the reason is that in GenericServlet, we have already obtained these data for us, we just need to take it directly.

 

      ServletContext object

           Access method: getServletContext(); 、getServletConfig().getServletContext(); //The difference between these two access methods is the same as the above explanation. The first one is to take it directly. In GenericServlet, we have already used getServletConfig(). getServletContext(); got the ServletContext. We only need to get it directly. The second one is equivalent to getting it by ourselves, and the two readings are the same.

           Function: tomcat creates a ServletContext instance for each web project, tomcat creates it at startup, destroys it when the server shuts down, shares data in a web project, manages web project resources, configures public information for the entire web, etc. In layman's terms, Just a web project, there is a ServletContext instance, and each servlet can access it.

              1. Shared data in web projects, getAttribute(String name), setAttribute(String name, Object obj), removeAttribute(String name)

                  setAttribute(String name, Object obj) stores content within the scope of the web project so that all servlets in the web project can access it

                  getAttribute(String name) Get the content by the specified name

                  removeAttribute(String name) removes content by specified name   

                   

                     

                    

              2. The initialization parameter of the entire web project // This is the global initialization parameter, and the initialization value can be obtained in each Servlet

                  getInitPatameter(String name) //Get the initialization value by specifying the name

                  getInitParameterNames() //Get the enumeration type

                   web.xml configures the initialization of the entire web project

                      

                      

                      

              3. Obtain web project resources

                  3.1 Get the path of the specified resource under the web project: getServletContext().getRealPath("/WEB-INF/web.xml")

                    

                    

                  3.2 Get the content of the specified resource under the web project, and return the byte input stream. InputStream getResourceAsStream(java.lang.String path)

                    Prerequisite knowledge: An understanding of streams is required. If you don't know, you can go to see the article on IO stream summary

                    

                    A screenshot of the output

                    

 

               4. getResourcePaths(java.lang.String path) All content under the specified path.

                    

                    

                    

                5 There are many other methods. These are the only ones that are used temporarily. If you need to use them in the future, you can check the source code and API.

      request object

          We know that request is an object that encapsulates the request text, so all the content in the request text, request header, request body, and request line can be obtained through request.

                

            1. Obtaining the content of the request line.

              

              

                

            2 Obtaining the request header

                Just pick anything from Baidu, and then check the request headers, including the following, for a little understanding.

                

                String getHeader(java.lang.String name) Get the specified header content String[]

                  

                  

                long getDateHeader(java.lang.String name) Get the specified header content Date

                int getIntHeader(java.lang.String name) Get the specified header content int

                Enumeration getHeaders(java.lang.String name) Get all the content of the specified name

            3 Acquisition of request body -- acquisition of request parameters

               There are two types, one get request and one post request

               get request parameters: http://localhost:8080/test01/MyServlet?username=jack&password=1234

               post请求参数: <form method="post"><input type="text" name="username">

                String request.getParameter(String) Get the specified name, a request parameter value.

                String[] request.getParameterValues(String) Get the specified name, all request parameter values. For example: checkbox, select, etc.

                Map<String , String[]> request.getParameterMap() to get all request parameters  

    

            4 Request forwarding

                request.getRequestDispatcher(String path).forward(request,response); //path: the page to jump to after forwarding, whether it starts with "/" or not, it starts with the root of the web project, because this is request forwarding, request Forwarding is only limited to use under the same web project, so it always starts from the root of the web project.

                web project root:

                    Development: G:\Workspaces\test01\WebRoot\..

                    Runtime: D:\java\tomcat\apache-tomcat-7.0.53\webapps\test01\..

                 web site root:

                    Runtime: D:\java\tomcat\apache-tomcat-7.0.53\webapps\..

                It can be seen from this that the web project root starts from the web project name, so when we request forwarding, we only need to write the path to be accessed after the project name.

                Features: The url in the browser will not change, that is, the browser does not know what the server does, the server helps us jump to the page, and the forwarded page can continue to use the original request, because it is the original request, Therefore, the attributes in the request field can continue to be obtained.

                

      response object

          

        A commonly used method: response.setHeader(java.lang.String name, java.lang.String value) Set the specified header, which is generally used.

             For example: set to automatically refresh every 3 seconds,

              response.setHeader("Refresh",3);

              

              

              In this way, you can see the number of seconds of the current time, and you will find that the page will be automatically refreshed every three seconds.

        The most important one is redirection, and some other operations are encapsulated in the response object, focusing on redirection

          Redirect (page jump)

            Method 1: Manual solution

                response.setStatus(302); //Status code 302 means redirection

                response.setHeader("location","http://www.baidu.com");

            Method 2: Use the packaged ones, through response.sendRedirect("http://www.baidu.com");

          Features: The page that the server tells the browser to jump to is the page that the browser actively jumps to. The browser knows, and the url in the browser's address bar will change. It is the browser that re-initiates a request to another page, so The request is re-initiated, which is different from request forwarding.

            Note: response.sendRedirect(path); //

            The first: response.sendRedirect("/test01/MyServlet01"); //The beginning of "/" is used, indicating that it starts from the root of the web site, so you need to write test01/MyServlet01

            The second: response.sendRedirect("MyServlet01"); //Do not use "/" at the beginning, indicating that it starts from the root of the web project, then there is no need to write test01.

            Redirection does not have any limitations. It can redirect any path in the web project, or access the path in other web projects, and it is distinguished by "/" here. If it starts with "/", it means that I want to Restart the positioning, do not visit the web project just now, write the project name by yourself, if you do not start with "/", then you know that you are accessing the servlet under the web project just now, you can omit the project name. That's how to differentiate.

 

 

V. Summary

      This chapter is long, but clears up a lot of knowledge points

          1. What is a servlet? If writing a servlet?

          2. I analyzed some of the source code of the servlet and learned some of the cleverly designed things. For example, the life cycle of the servlet was originally written, but under its design, we only focus on the doGet and doPost methods. Why is this possible? Woolen cloth? It can be found in the source code.

          3, servlet life cycle, web.xml configuration

          4. Detailed explanation of ServletConfig object, ServletContext object, request object and response object in servlet. Including some of the commonly used methods.

          5. The next article will explain the solution to the Chinese garbled problem of request and response

            

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325816682&siteId=291194637