This article to the previous article, distance is a bit distant ah, separated by about two months, the middle of the home after a year, haha ~ now start picking up, recently in a personal feel great book, "Java Web integration Development King return", now write this series is basically from the book summed up, Personally think that it is more important and need to understand, because I found that after so long did not study, the previous many things have been forgotten, such as the simplest, what is a servlet? I can't answer it, I used to be just a simple to create a servlet, know it some of the forwarding redirect to another page, but specifically to say, then the brain blank, what is not clear, on the one hand may be not solid, will only press gourd painting scoop, on the other hand may be such things need to record down, Later on May forget, back to look at some of their own notes, so as to review, so open the old road, Java Web Learning record.
--wh
First, what is a servlet?
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, then this specific process, how is the step? This is a look at HTTP requests and responses.
Request, Response: By giving the link should be able to know the two specific content
Ii. the relationship 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 client. The servlet is a component that runs on a server that supports the Java language. 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.
①: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.
②:tomcat the information to be responded to is encapsulated as a response object of type HttpServletResponse, by setting the response property, you can control what you want to output to the browser, and then give response to Tomcat, Tomcat sends it into the format of the response text to the browser
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.
Iii. Preparation of Servlets
In front, we already know what the servlet is, why it needs a servlet? (to implement dynamic Web pages, instead of displaying static Web pages, the specifics can be Baidu check), Tomcat and servlet relationship? and other issues. Now let's write a servlet manually.
3.1. Write the servlet manually.
1, create a myservlet inheritance httpservlet, rewrite Doget and Dopost methods, that is, to see whether the request is a GET or post, and then handle the request in different ways,
2. Why do I need to configure Myservlet in Web. xml? 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.
Configure four things.
After configuration, the browser is how to find the corresponding servlet through the information we have configured.
Follow the steps to first browser via http://localhost:8080/test01/ Myservlet 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, to the third step, also To know the location of the servlet. The corresponding processing method is then found in the process.
3, experiment, verify the above configuration is successful.
3.2. New Myservlet with 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 and have the option to create a new servlet directly in the new option
2. Configure the information in the Myservlet class
3. Configuring servlet information in Web. xml
4, look at the code in the MyServle01 class and Web. XML, where the configuration is the same as the manual configuration, but with a graphical interface, so that we more convenient to create a servlet generated.
3.3. How to create a servlet
1. What is the life cycle of the servlet?
2. Why is the servlet created to inherit from HttpServlet instead of directly implementing the Servlet interface?
3, the servlet life cycle, you can see, the implementation of the service method, why we only need to write Doget and Dopost method?
This series of questions, we should all know, and should not simply know how to configure and use the servlet? The above question, hit solution.
1. What is the life cycle of the servlet?
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.
2. Why is the servlet created to inherit from HttpServlet instead of directly implementing the Servlet interface?
3, the servlet life cycle, you can see, the implementation of the service method, why we only need to write Doget and Dopost method?
View the source code, HttpServlet inheritance structure.
HttpServlet inherits Genericservlet. The person who understands should know immediately, what is the role of Genericservlet (Universal servlet)? Presumably, the way to implement a servlet interface is to simplify the steps 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, ServletConfig object can get some information to the servlet, Servletname, ServletContext, Initparameter, Initparameternames, by looking at ServletConfig this interface 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. and genericservlet implementation of the Servlet interface, it also shows that we can directly inherit the 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 troublesome, can not directly get ServletContext, so genericservlet in addition to implement Servlet interface, but also implemented the ServletConfig interface, so, You can get the ServletContext directly.
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 ability to use ServletConfig objects directly elsewhere, not just in the init (servletconfig config) method, create a private member variable, config, in Init (servletconfig Config) method is assigned to config, and then the Getservletconfig () method is able to get the ServletConfig object, which is understandable, but in init (servletconfig config), 158 rows , and also called an init () method, and the Init () method is empty, what does it read? 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 add an init () method in the Genericservlet class, you need to initialize the other data in the Init method later, only need to rewrite the init () This method, and do not need to overwrite the init ( ServletConfig config) This method, so the design, is much better, not in the tube init (servletconfig config) 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 regarded as httpservletrequest, can also be regarded as 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 judge 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 may have a lot of content, so, in this method will be get,post and other 5 kinds of request methods extracted, into a single method, Then, when we need to write a servlet, we can simply rewrite the doget or Dopost method instead of rewriting the service method, which is more targeted. So here we go back to the situation where we wrote the servlet, inherit 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 mode). So it answers the questions we started with 3.
Four, a few focus on the object. ServletConfig, Servletcontext,request, response
Explain four classes, ServletConfig object, ServletContext object, Request object, Response object
ServletConfig Object
Access route: Getservletconfig ();
Function: Above probably mentioned, can get four things,
Getservletname (); Gets the name of the servlet, which is the servlet-name that we configured in Web. xml
Getservletcontext (); Get the ServletContext object, the role of the object see below to explain
Getinitparameter (String); Gets the value of the initialization parameter in the servlet. Here, note the distinction with global initialization parameters. This gets only the initialization parameters under the servlet
Getinitparameternames (); Gets the name of all initialization parameters in the servlet, which is the key value, which can be used to find the value of each initialization parameter by using the key value. Note that the enumeration type is returned
Note: In the above we analyzed the source code process, we knew, actually can not obtain the ServletConfig first, then obtains its various parameters, may use the method directly, for example above we use ServletConfig (). Getservletname (); Can be written directly to Getservletname (), rather than get ServletConfig (), the reason is that in the Genericservlet, has helped us to obtain the data, we only need to directly take the line.
ServletContext Object
Access route: Getservletcontext (); , Getservletconfig (). Getservletcontext (); The difference between the two methods of acquisition is the same as the above explanation, the first is to take directly, in the Genericservlet has helped us to use Getservletconfig (). Getservletcontext (); Got the ServletContext. We just have to get it straight, and the second is the same as we're getting it again, and the two readings are the same.
Features: Tomcat creates a ServletContext instance for each Web project, Tomcat is created at startup, destroyed when the server shuts down, shares data in a Web project, manages Web project resources, configures public information for the entire web, and so on, in layman's words, is a Web project, there is a ServletContext instance where each servlet read 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 a Web project so that all servlets in the Web project can read access to the
GetAttribute (String name) obtains content by specifying a name
RemoveAttribute (String name) removing content by specifying a name
2, the entire Web project initialization parameters//This is the global initialization parameters, each servlet can get the initialization value
Getinitpatameter (String name)//Gets the initialization value by specifying a name
Getinitparameternames ()//Get enum type
Web. XML configures the initialization of the entire website project
3. Get Web Project Resources
3.1 Gets the path to the specified resource under the WEB Project: Getservletcontext (). Getrealpath ("/web-inf/web.xml")
3.2 Gets the contents of the specified resource under the Web project, and returns the byte input stream. InputStream getResourceAsStream (java.lang.String path)
Prerequisite knowledge: Need to understand flow. I don't know, I can take a look at the article on Io Flow summary
Part of output content
4, Getresourcepaths (java.lang.String path) specifies all content under the path.
5 There are many other methods, the temporary use of these several, in the future need to use, see the source code, look at the API.
Request Object
We know that request is the object that encapsulates the requested text, so that all content in the request text is obtained through request, requesting the header, the request body, and the request line.
1, the request line content acquisition.
2 acquisition of the request header
Casually Baidu a thing, and then look at the request header, including the following content, a little to understand.
String GetHeader (java.lang.String name) gets the specified header content string ""
Long Getdateheader (java.lang.String name) gets the specified header content date
int Getintheader (java.lang.String name) gets the specified header content int
Enumeration Getheaders (java.lang.String name) gets the specified name all content
3 acquisition of request body--acquisition of request parameters
There are two kinds, a GET request, a POST request
Get request parameter: http://localhost:8080/test01/MyServlet?username=jack&password=1234
Post request parameters: <form method= "POST" ><input type= "text" name= "username" >
String Request.getparameter (String) Gets the specified name, a request parameter value.
String[] Request.getparametervalues (String) Gets the specified name, all request parameter values. Example: CheckBox, SELECT, etc.
Map<string, string[]> Request.getparametermap () get all the request parameters
4 Request Forwarding
Request.getrequestdispatcher (String Path). Forward (Request,response); Path: Forwarded after the page, regardless of the use of "/" at the beginning of the Web project root, because this is request forwarding, request forwarding is only limited to the same Web project to use, so this has always been from the Web project root under the start,
Web Project Root:
Development: G:\Workspaces\test01\WebRoot\.
Run time: D:\java\tomcat\apache-tomcat-7.0.53\webapps\test01\.
Web site Root:
Run time: D:\java\tomcat\apache-tomcat-7.0.53\webapps\.
As can be seen from here, the Web project root is starting from the Web project name, so when we request forwarding, we only need to follow the project name to access the path to write the line,
Features: The URL in the browser does not change, that is, the browser does not know what the server did, is the server to help us jump page, and in the forwarded page, can continue to use the original request, because it is the original request, so the request domain properties can continue to get.
Response Object
A common method: Response.setheader (java.lang.String name, java.lang.String value) sets the specified header, which is generally used.
For example: The setting is automatically refreshed every 3 seconds,
Response.setheader ("Refresh", 3);
This allows you to see the number of seconds in the current time and will automatically refresh the page every three seconds.
The most important one is redirection, and some of the other operations are encapsulated in the response object, with emphasis on redirection
Redirect (page jump)
Mode one: Manual scheme
Response.setstatus (302); Status Code 302 means redirect
Response.setheader ("Location", "http://www.baidu.com");
Mode two: The use of encapsulated good, through the Response.sendredirect ("http://www.baidu.com");
Features: The server tells the browser to jump to the page, is the browser to jump to the page, the browser knows, also the browser address bar URL will change, is the browser re-launch a request to another page, so request is re-initiated, and request forwarding is not the same.
Note: response.sendredirect (path); //
The first type: Response.sendredirect ("/test01/myservlet01"); Using "/" begins with the Web site root, so you need to write test01/myservlet01
The second type: Response.sendredirect ("MyServlet01"); Without the beginning of the "/", the description starts at the root of the Web project, so there is no need to write test01.
Redirection does not have any limitations, you can redirect any path within the Web project, you can also access paths in other Web projects, and this is distinguished by "/", If you use "/", it means I want to start again, do not access just the Web project, write the project name, if not use "/" Start, then you know that you can omit the project name by accessing the servlet under that Web project. That's the difference.
V. Summary
This section is long, but it's a lot easier to clarify.
1. What is a servlet? What if you write a servlet?
2, analysis of the servlet part of the source code, know some of the clever design things, for example, the original servlet can see its life cycle, but in its design, we only focus on Doget and Dopost method, why can this? Can be learned through the source code.
3. The servlet's life cycle, the configuration of Web. xml
4, the ServletConfig object in the servlet, ServletContext object, Request object, Response object's detailed explanation. Includes some of the commonly used methods.
5, the next article to explain the request, response the problem of Chinese garbled solution
Java Web (a) servlet detailed!!