Objective
In fact, javaweb knowledge has long been learned, but because now in the big data development, so the knowledge of the web has been forgotten. Ready to start slowly the knowledge of the Web 1.1 points of memory, learn a little bit of no relationship, afraid to use the words, nothing.
I. Servlet Overview 1.1, Servlet Introduction
The Servlet runs the Java applet on the server side , and Sun provides a set of specifications (interfaces)to handle the client requests and respond to the dynamic resources of the browser . the essence of the servlet, however, is Java code , which dynamically outputs content to the client through the Java API.
A servlet is one of the three components of the Java Web (Servlet,filter,listener), which is a dynamic resource, and a program that runs on a WEB server or application server acts as a processing request, and the server gives the request to the servlet for processing. In a servlet, you typically need:
Accept request data, process requests, complete responses
For example, the client makes a logon request, or outputs a registration request, and these requests should have a servlet to complete the processing. Each servlet must implement the Javax.servle.Servlet interface.
Summarize:
The process of processing requests and sending responses is done by a program called a servlet , and the servlet is intended to solve the problem of implementing dynamic pages. The premise of understanding this is to know something about the HTTP protocol and know the B/s mode (browser/server).
b/S: Browser/server. Browser through the URL to access the server, such as access to Baidu, in the browser input www.baidu.com, this time the browser will display the homepage of Baidu.
Supplement 1:
Servlet specification (Sun Company has developed a component specification for extending Web server Functionality ): contains three technical points (three major components)
Servlet Technology
Filter Technology---Filters
Listener Technology---Listener
1) extended Web server capabilities
The Web server (Tomcat, Weblogic, IIS, Apache) does not handle the power of a dynamic resource request (that is, the request needs to be computed), only the request for a static resource (if the browser requests an HTML page,
The Web server checks to see if the requested HTML page exists and is returned. If you want your Web server to handle requests for dynamic resources, you need to use CGI programs, components, and containers.
2) components (software modules that can be deployed separately, components must conform to the appropriate specifications.) )
The advantage is that it can speed up software development and improve the maintainability of software. Containers: Provides a running environment for components and manages the lifecycle of components. Components do not rely entirely on specific containers, as long as they conform to the appropriate specifications.
Supplement 2:
The difference between a servlet and a common Java class: a customer cannot directlyways to create a Servlet object and invoke a servlet, you can call the Servlet method indirectly only by making an HTTP request to the Web server. 1.2. How to implement a servlet
Implementing the Javax.servlet.Servlet Interface
Inheriting the Javax.servlet.GenericServlet class
Inheriting the Javax.servlet.http.HttpServlet class
Typically, the HttpServlet class is inherited to complete the servlet.
1.3. servlet and Thread safety issues
One type of servlet has only one instance object, it is possible that a servlet can handle multiple requests at the same time, the thread is unsafe, but the servlet is efficient.
Solution:
Do not create a member in the servlet, create a local variable variable!
You can create stateless members!
You can create a stateful member, but the state must be bit read-only!
Public classServlet extends HttpServlet {//Stateless member /*Public class User {public void Hello () {System.out.println ("Hello"); } }*/ //creates a stateful member, but the state must be bit read-only /*Public class User {private String name = "Zhangsan"; Public String GetName () {return name; } }*/ PrivateUser User =NewUser (); protected voidDoPost (httpservletrequest request, httpservletresponse response) throws Servletexception, IOException {System . out. println ("doPost () ..."); } protected voiddoget (httpservletrequest request, httpservletresponse response) throws Servletexception, IOException {System. out. println ("doget () ..."); }}
Sample CodeIi. the connection between Tomcat and servlet
Tomcat is a Web application server and is a servlet/jsp container . Tomcat acts as a servlet container that handles client requests, sends requests to the servlet, and sends the Servlet's response back to the customer . and servlets are a kind of running in support components on the Java language Server :
The most common use of servlets is to extend the Java Web Server functionality to provide a very secure, portable, and easy-to-use CGI alternative.
From the request and response in the HTTP protocol, it is known that the request made by the browser is a request text, and the browser should receive a response text.
But in the above diagram, do not know how to change, only know that the browser sent over the request is requested, we respond back to the use of response. Ignoring the details, let's explore it now.
1) Tomcat receives and parses the HTTP request text and encapsulates it into a request object of type HttpServletRequest , and all HTTP header data reads can be queried by the request object by invoking the corresponding method.
2) Tomcat also responds with information encapsulated as a HttpServletResponse type of response object , and by setting the response property you can control what you want to output to the browser. The response is then handed to Tomcat,tomcat and sent to the browser in the format of the response text.
The Java servlet API is the interface between the servlet container (Tomcat) and the servlet , which defines the various methods of Serlvet and defines the object classes that the Servlet container transmits to the servlet. The most important of these is servletrequest and servletresponse.
So when we write a servlet, we need to implement the Servlet interface and act on its specifications.
Third, write a simple Servlet3.1, manually write a servlet
1) Create a servlet_demo_0010 inheritance httpservlet, overriding the Doget and Dopost methods, which is to see whether the request is a GET or post, and then handle the request in a different way.
2) Configuring servlet_demo_0010 in Web. XML, why do I need to configure it? Let the browser make a request to know which servlet to reach, that is, let Tomcat put the encapsulated request to find the corresponding servlet to use.
Analysis:
Follow the steps to first browser via http://localhost:4040/Web_Servlet/ Servlettest to find the Url-pattern in Web. XML, this is the first step, after matching to Url-pattern, you will find the second step servlet name Myservlet, know the name,
You can find the third step through Servlet-name, and in the third step, you will be able to know the location of the servlet. The corresponding processing method is then found in the process.
3) Testing
Description the configuration was successful! (output get because the HTTP request is a GET request by default)
3.2. Create a servlet using the Eclipse Wizard
This is relatively simple, web. XML does not need to be configured manually, the tool directly for us to automatically configure the
1) Right-click the project with the option to create a new servlet directly in the new option
2) Configure the information in the servlet_demo_0020 class
3) Configuring servlet information in Web. xml
4) Look at the code in the Servlet_demo_0020 class and Web. XML, where the configuration is the same as the manual configuration, but with a graphical interface that makes it easier for us to create servlets.
Iv. servlet life cycle 4.1, life cycle methods and characteristics
void init (ServletConfig servletconfig): The initialization method that executes immediately after the Servlet object is created, only once;
void Service (ServletRequest servletrequest, Servletresponse servletresponse): Each processing request is called in this method, it will be called multiple times;
void Destroy (): Called before the servlet is destroyed and is responsible for releasing the resources used by the Servlet object;
Characteristics:
Singleton, a class has only one object, and of course there may be more than one servlet class
Thread is unsafe, so it's efficient.
The Servlet class is written by itself, but the object is created by the server, and the corresponding method is called by the server
4.2. servlet Life cycle
A Servlet object is initialized when the server is started (configuration load-on-startup=1 in Web. XML, default is 0), or when the servlet is first requested, that is, the initialization method init (ServletConfig conf) is executed
The Servlet object handles all client requests and executes in the service (ServletRequest req,servletresponse res) method
The Servlet object is destroyed when the last server is closed, and the Destroy () method is executed.
Graphic:
Detailed Description:
Summary (interview will ask):
1) When the servlet is created
This object is created the first time the servlet is accessed by default (call the Init () method)
2) When the servlet is destroyed
The server shuts down the servlet and destroys it (calls the Destroy () method)
3) methods that must be performed for each access
public void Service (ServletRequest arg0, Servletresponse arg1)
V. servlet principle 5.1, servlet execution process
In the address bar of the browser, enter: Http://ip:port/appNames/servlet
1) Connect to this server via browser and Ip:port.
2) The browser generates a request packet (path Appnames/servlet) to send the request to the server .
3) The server receives the request packet, analyzes the request resource path to do the precise location, through the request appname finds the WebApps file below the appname to do the match, matches on needs to obtain the servlet (mapping) in the web.
4) The server creates two objects:
The first object: The Request object, which implements the HttpServletRequest interface, and the server parses the data from the request packet and stores it in the object. The advantage of this is that there is no need to understand the HTTP protocol, just read the request.
The second object, the response object, implements the HttpServletResponse interface, in which the results of the servlet processing can be stored on the object, and the server generates a response packet based on the object's data.
5) When executing the servlet () method, the servlet can obtain the requested data through request, or it can store the processing results on the response. The server then directly forms a tacit understanding with the response object, generating a response packet to the browser.
6) The browser resolves the response packet returned by the server, generating the result of the response.
Procedure for servlet access: HTTP request---->web.xml--------> Url-pattern----->servlet-name----->servlet-class-----> Quickstratservlet (corresponding class file) 5.2, servlet configuration
1) Basic configuration Web. xml file
<!--the configuration of the servlet classes--
< configuration of the virtual path of the servlet!--
Where Url-pattern is configured:
1) Exact match: The resource accessed is exactly the same as the configured resource to access the
An absolute address can only be mapped to 1 addresses
Format:/directory/directory/file name. extension
<url-pattern>/quickStartServlet</url-pattern>
2) directory matching: Format:/virtual directory ..../*
Format:/directory/directory/* This type of mapping focuses on the directory, as long as the directory conforms to the mapping mode, regardless of the file name, the servlet can respond to multiple request URLs.
<url-pattern>/aaa/bbb/ccc/*</url-pattern>//* represents any
3) Match extension: Format: *. extension;
Format: *. The extension is URL-mapped in a way that matches the extension, regardless of the directory information of the file, or in response to a multi-address request.
<url-pattern>*.abcd</url-pattern>
Note: The second is mixed with the third type:/AAA/BBB/*.CBA (Error)
2) The server initiates the instantiation of the servlet configuration
When the servlet was created: default first access created
Why is the default?
When the configuration in the servlet is, add a config <load-onstartup>;
The Servlet object is created when the server is started. <!--numbers represent priorities, the smaller the number the higher the priority-
<load-on-startup>4</load-on-startup> best to take the median number 4/5.
3) Default servlet
The Url-pattern can be configured with a/, which means that the servlet is the default servlet. What is the default servlet? The default servlet assignment is handled when you access resource addresses where all servlets do not match. In fact, all the resources in the Web application are responsive to the servlet, including static resources (HTML pages). (There is a default servlet configured to not have access to static resources.) 5.3. The servlet created is inherited from HttpServlet, rather than directly implementing the Servlet interface in the life cycle of the servlet, as can be seen, the service method is executed, why do we only need to write Doget and Dopost method? View the source code, HttpServlet inheritance structure httpservlet inherit genericservlet. The person who understands should know immediately, what is the role of Genericservlet (Universal servlet)? That's probably it.a way to implement a servlet interface that simplifies the process of writing a servlet。 Detailed below
Genericservlet inherits the structure, implements the Servlet interface and the ServletConfig interface
Servlet interface Content
From here, there are three key approaches to 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 to the servlet , Servletname, ServletContext, Initparameter, Initparameternames, By looking at the ServletConfig interface, you can know:
ServletConfig interface Content
Where the ServletContext object is a servlet context object , there are many functions, and with the ServletContext object, we can get most of the information we need, such as getting the path of the servlet, and so on .
To this, we know the content and function of the servlet interface, summed up is, three life cycle operation method, get ServletConfig, and through ServletConfig can get to ServletContext. When the Genericservlet implements the Servlet interface,
Also shows that we can directly inherit Genericservlet, we can use the above we introduced the servlet interface of the several methods, can get servletconfig, can also get servletcontext, but that too much trouble, Can't get ServletContext directly,
So Genericservlet In addition to the implementation of the Servlet interface, but also the implementation of the ServletConfig interface, so that you can directly obtain ServletContext .
The contents of the Genericservlet class are detailed
See, the Red box is the implementation of the servlet and ServletConfig interface implementation of the method, there are 9, which is normal, but we can find that the Init method has two, one with parameter ServletConfig, a method with no parameters, why this design?
You need to know what's going on here and see what these two methods have done separately.
Init (servletconfig config)
Init ()
A member variable config
Getservletconfig ()
In this way, the init (servletconfig config) method is first seen, because only init (servletconfig config) has servletconfig objects. To facilitate the direct use of ServletConfig objects in other places, not just in the init (servletconfig config) method,
so create a private member variable config, assign it to config in the init (servletconfig config) method, and then pass the Getservletconfig () Method is able to get the ServletConfig object , which is understandable, but in init (servletconfig config), 158 lines, also called an init () method,
And this init () method is empty, what read no, what is this for? 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 it is to inherit Genericservlet and rewrite the init (servletconfig config) method, so dependent,
Destroys the code originally written in the Genericservlet class by init (ServletConfig config), where the member variable config in the Genericservlet class is always null and cannot be assigned because it is rewritten, The code in the init (servletconfig config) method in Genericservlet is not executed.
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 inconvenient, afraid sometimes forget to write this code, so in the Genericservlet class to add an init () method,
Later you need to initialize the other data in the Init method, only need to rewrite the init () method, and do not need to overwrite the init (servletconfig config) This method, so the design is much better, not in the pipe init (servletconfig Config) is the content of this. There is no other problem.
Service (ServletRequest req, servletresponse Res)
An abstract method, stating that the content is not implemented in the Genericservlet class, then we think that there must be another layer on it, that is, there is a subclass that inherits it, to implement this method, and if we let our own servlet inherit Genericservlet,
It would be exhausting to write your own service method, and we can see that the parameters in the service method are still servletrequest,servletresponse. is not hooked up with HTTP-related objects, so let's go ahead and look down.
HttpServlet class explanation
Inheriting the Genericservlet class, the main function of this class is certainly to implement the various details and designs of the service method through our speculation above. And with the class name you know, the class is hooked up to HTTP.
Follow the service (HttpServletRequest req, HttpServletResponse resp) method and service (ServletRequest req, Servletresponse res) method.
Service (ServletRequest req, servletresponse res) method
One thing to do in this approach is to convert the ServletRequest and Servletresponse objects to HttpServletRequest and HttpServletResponse objects strongly. Why would you do that?
The first thing to know req, res is what type, by printing System.out.println (req), you can know, req the actual type is Org.apache.catalina.connector.RequestFacade
The source code in Tomcat:
Through the graph can know,req inheritance structure: Requestfacade, HttpServletRequest, ServletRequest, we know itself req is ServletRequest, then from the inheritance structure, It can also be seen as a httpservletrequest, or as a servletrequest,
So strong to HttpServletRequest is possible, if not understand, I give an example, ArrayList, List, Object this, object obj = new ArrayList (); List List = new ArrayList (); A ArrayList object can be viewed as a list object, or as an object.
Can obj be called a list object now? The answer is yes, because obj is the ArrayList object, and since it is a ArrayList object, it can be considered a list object. The same reason, Requestfacade corresponds to ArrayList, httpservlerequest corresponding List, servletrequest corresponding to the Object.
After you convert the HttpServletRequest and HttpServletResponse objects, call the service (HttpServletRequest req, HttpServletResponse resp) method.
Service (HttpServletRequest req, HttpServletResponse resp)
This method is to determine the browser come over the way of the request , each kind of processing is not the same, we commonly used is get,post, and, we handle the way there may be a lot of content, so, in this method will be get,post and other 5 kinds of request methods extracted,
Become a single method, and then we need to write a servlet, we can directly rewrite the Doget or Dopost method, rather than rewrite the service method, more targeted. So here we go back to the case when we wrote the servlet, inheriting HttpServlet,
And as long as rewrite two methods, a doget, a dopost, is actually the service method will call one of these two methods (see Request Way). The
Like on the point of a "recommendation" Oh!
Javaweb (i) the servlet