1. HTTP protocol
HTTP (hypertext transport protocol) protocol, which specifies the rules for mutual communication between browsers and World Wide Web servers.
1.1 characteristics of HTTP protocol
-
Support client / server mode.
-
Simple and fast: when a client requests a service from the server, it only needs to send the request method and path. The common request methods are GET and POST. Each method specifies the type of contact between the client and the server. Due to the simple HTTP protocol, the program scale of HTTP server is small, so the communication speed is very fast.
-
Flexible: HTTP allows any type of data object to be transmitted. The type of transmission is marked by content type (message header).
-
No connection: no connection means that only one request is processed for each connection. After the server processes the customer's request and receives the customer's response, it disconnects. In this way, the transmission time can be saved.
HTTP1. Sustainable connection is supported after version 1. Through this connection, it is possible to send requests and get responses after establishing a TCP connection, and then send more requests and get more responses. By allocating the cost of establishing and releasing TCP connections to multiple requests, the relative cost caused by TCP is greatly reduced for each request. Moreover, a pipeline request can also be sent, that is, request 2 can be sent before the response after sending request 1 arrives. It can also be considered that a connection sends multiple requests, and the client confirms whether to close the connection, while the server will think that these requests come from different clients. -
Stateless: HTTP protocol is a stateless protocol. Stateless means that the protocol has no memory ability for transaction processing. The lack of status means that if the previous information is required for subsequent processing, it must be retransmitted, which may increase the amount of data transmitted per connection. On the other hand, when the server does not need previous information, its response is faster.
1.2 HTTP URL
HTTP URL is a special type of URL that contains enough information to find a resource. The format of the URL is as follows:
http://host[:port]/[abc_path] http://IP (host name / domain name): port / resource path accessed
- HTTP means to locate network resources through HTTP protocol;
- Host indicates the legal Internet host domain name or IP address;
- Port specifies a port number. If it is empty, the default port 80 will be used;
- abs_path specifies the URL of the requested resource; If ABS is not given in the URL_ Path, then when it is used as the request URL, it must be given in the form of "/". Usually, this work is completed automatically by the browser.
1.3 HTTP request message
HTTP request message consists of three parts: request line, request header, blank line and request body (request body). Among them, the Get request has no request body, and the Post request has a request body.
- Request line: composed of request method (Get/Post), request address (url path) and HTTP request protocol version
- Request header: a series of key value pairs
- Empty line
- Request body: the parameter content in FromData. When the address bar of the browser cannot hold too long transmission parameters, part of the content will be placed in FormData and transmitted as a request body. When fewer parameters are passed, it will directly follow the request line without the request body. The request body of the Get request is empty. Only the Post request has a request body.
Request line format: method request URI HTTP version CRLF
- Method indicates the request method (GET/POST)
- Requst URI is a uniform resource identifier
- HTTP version indicates the HTTP protocol version of the request
- CRLF means carriage return and line feed.
1.4 HTTP response message
after receiving and interpreting the request message, the server returns an HTTP response message. The HTTP response is also composed of three parts: status line, message header, blank line and response body.
- Status line: description of protocol version + status code + status code
- Message header: a series of key value pairs that describe the corresponding text
- Empty line
- Response body: the content in reply, that is, the web page seen in the browser, that is, HTML file, etc.
2. Tomcat server
The Tomcat directory structure is as follows:
- bin: start and close the bat file of tomcat
- conf: configuration file server XML this file is used to configure server related information, such as the port number of tomcat startup, and configure the host
(Host) ; web.xml file configuration and web application (web application is equivalent to a web site); tomcat-user.xml configuration user name, password and related permissions - lib: this directory places the jar packages needed to run tomcat
- Logs: store logs. When we need to view logs, we can query information
- webapps: place our web applications
- work working directory: this directory is used to store the corresponding server files and files generated after the jsp is accessed class file
3. Implementation of Servlet
servlet is the abbreviation of Server and Applet, which means small program on the Server side. The Server-side program written in Java language can generate dynamic web pages. Servlet mainly runs on the Server and is called and executed by the Server. It is a class developed according to the servlet standard. It is a technology provided by SUN company for developing dynamic web resources. (implication: to realize web development, you need to implement servlet standard)
Servlet is also a Java class in essence, but it should be written according to the Servlet specification. There is no main method. Its creation, use and destruction are managed by the Servlet container (such as Tomcat). (implication: write your own class, don't write the main method, others will call it automatically)
Servlet is closely related to HTTP protocol. It can handle all contents related to HTTP protocol. This is also one of the reasons why servlets are widely used.
servers that provide Servlet functions are called and Servlet containers. There are many common containers, such as Tomcat, Jetty, WebLogic Server, WebSphere, JBoss and so on.
3.1 creating a Web project
3.1.1 web project structure
- The src directory stores java code.
- The web directory stores HTML, CSS, JavaScript and other page style codes.
3.1.2 creating packages and classes
in the src folder, create the package first and then the class.
3.2 implementation of Servlet specification
implement the Servlet specification, that is, inherit the HttpServlet class and connect it to the response package. Then this class has completed the communication rules, and we only need to implement the business.
package com.liangshao.servlet; import javax.servlet.http.HttpServlet; public class Servlet01 extends HttpServlet { }
3.3 rewrite service method
meeting the Servlet specification only enables our class to meet the requirements of receiving requests. After receiving requests, we need to analyze the requests and process the business logic. If we calculate the results, we need to add code. In the specification, there is a method called service, which is specially used for request processing, and the business code can be written in this method.
package com.liangshao.servlet; /** * Implementation of Servlet -- Method 1 * 1. Create a normal java class * 2. Implement the specification of Servlet and inherit the HttpServlet class * 3. Implement / rewrite the service method to process the request -- > rewrite the shortcut key: Ctrl+O * 4. Set the annotation and specify the access path */ import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; // @WebServlet("/ser01") / / add a path for the current resource // @WebServlet(name = "Servlet01", value = "/ser01") // @WebServlet(name = "Servlet01", urlPatterns = "/ser01") // @WebServlet(name = "Servlet01", value = {"/ser01", "/ser001"}) @WebServlet(name = "Servlet01", urlPatterns = {"/ser01", "/ser001"}) public class Servlet01 extends HttpServlet { @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("Hello Servlet!"); resp.getWriter().write("Hello World!"); } }
3.4 setting notes (labels)
In order to make different settings to the server, you need to make comments to the server. Therefore, after writing all the codes, you need to explain to the server that a specific request corresponds to a specific resource.
develop a servlet project and use @ WebServlet annotation to inherit one from javax servlet. http. The class of httpservlet is defined as a servlet component. In servlet3 0, you can use the @ WebServlet annotation to inherit one from javax servlet. http. The class of httpservlet is marked as a servlet that can handle user requests.
the value value of the annotation indicates the external access path of a class, and value can have multiple values, indicating that the same class can be accessed using different access paths. be careful!!! The slash of the path cannot be omitted.
3.5 modify external access path
click the option box next to the run button ---- > click Edit Configuration... ---- > deployment ---- > application context, which is the project access path, where you can modify it.
3.6 other three methods to implement Servlet
Method 2:
/** * Implementation of Servlet -- Method 2 * 1. Create a normal java class * 2. Implement the specification of Servlet and inherit the GenericServlet class * 3. Implement / rewrite the service method to process the request -- > rewrite the shortcut key: Ctrl+O * 4. Set the annotation and specify the access path */ import javax.servlet.GenericServlet; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.annotation.WebServlet; import java.io.IOException; @WebServlet("/ser02") public class Servlet02 extends GenericServlet { @Override public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException { System.out.println("inherit GenericServlet Class method"); servletResponse.getWriter().write("inherit GenericServlet Method"); } }
Method 3:
import javax.servlet.*; import javax.servlet.annotation.WebServlet; import java.io.IOException; /** * Implementation of Servlet -- Method 3 * 1. Create a normal java class * 2. Realize the specification of Servlet and realize the Servlet interface * 3. Implement the method under the interface and rewrite the service method to process the request * 4. Set the annotation and specify the access path */ @WebServlet("/ser03") public class Servlet03 implements Servlet { @Override public void init(ServletConfig servletConfig) throws ServletException { } @Override public ServletConfig getServletConfig() { return null; } @Override public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException { System.out.println("realization Servlet Interface method"); servletResponse.getWriter().write("realization Servlet Interface method"); } @Override public String getServletInfo() { return null; } @Override public void destroy() { } }
Method 4:
import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * Implementation of Servlet -- Method 4 * 1. Create a normal java class * 2. Implement the specification of Servlet and inherit the HttpServlet class * 3. Implement / override the doGet and doPost methods to process requests * 4. Set the annotation and specify the access path * However, it is impossible to know whether the request method of the browser is Get or Post, so the code needs to be written repeatedly */ @WebServlet("/ser04") public class Servlet04 extends HttpServlet { /** * GET Request call * @param req * @param resp * @throws ServletException * @throws IOException */ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("rewrite doGet Method"); } /** * POST Request call * @param req * @param resp * @throws ServletException * @throws IOException */ @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("rewrite doPost Method"); } }
because method 4 rewrites doGet method and doPost method, there is too much code redundancy, so it is not recommended to use it.
Summary: to implement a Servlet, either rewrite the service method, or rewrite the doGet method and doPost method. However, the latter often uses another method - doGet and doPost call each other. As follows:
import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * Implementation of Servlet -- Method 4 * 1. Create a normal java class * 2. Implement the specification of Servlet and inherit the HttpServlet class * 3. Implement / rewrite doGet and doPost methods to process requests However, just write code in one method and another method calls the method. * 4. Set the annotation and specify the access path * However, it is impossible to know whether the request method of the browser is Get or Post, so the code needs to be written repeatedly */ @WebServlet("/ser05") public class Servlet05 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("rewrite doGet Method"); // code } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("rewrite doPost Method"); // Call doGet method doGet(req, resp); } }
4. Servlet life cycle
the life cycle of a Servlet can be summarized into four steps: service class loading – > instantiation – > service – > destruction
servlet has no main() method and cannot run independently. Its operation is completely controlled and scheduled by servlet engine. The so-called life cycle refers to the whole process of when the servlet container creates a servlet instance, when it calls its methods to process requests, and when it and destroys its instances.
- Instance and initialization timing
when the request reaches the container, the container will find out whether the servlet object exists. If it does not exist, the instance will be created and initialized. - Ready / call / service phase
when a request arrives at the container, the container calls the service() method of the servlet object, and the method for processing the request can be called many times in the whole life cycle; The service() method of HttpServlet will call doGet() or doPost() method according to the request method. However, these two do methods throw exceptions by default and need subclasses to override. - Destruction timing
when the container is closed (when the application stops), the Servlet instance in the program will be destroyed.
the above life cycle can be observed through the life cycle method in Servlet. There are three life cycle methods in the Servlet, which are not called manually by the user, but automatically called by the container at a specific time. Observe these three life cycle methods to observe the life cycle of the Servlet.
1. init() method: execute after the Servlet instance is created (prove that an instance of the Servlet has been created).
public void init(Servletconfig config) throws servletException { system.out.print1n("Instance created..."); }
2. The service method is executed every time a request reaches a Servlet method to process the request (proving that the Servlet has served)
protected void service(HttpservletRequest req,HttpservletResponse resp) throws servletException,IOException { system.out.println("Service called..."); }
3. destroy method, which is executed when the Servlet instance is destroyed (proving that the Servlet instance has been destroyed)
public void destroy() { System.out.println("Instance destroyed..."); }
5. Working principle of servlet and Tomcat
- The Web Client sends an Http request to the Servlet container (Tomcat)
- The Servlet container receives requests from the Web Client
- The Servlet container creates an HttpServletRequest object and encapsulates the information requested by the Web Client into this object
- The Servlet container creates an HttpServletResponse object
- The Servlet container calls the HttpServlet object service method, takes Request and Response as parameters, and passes them to HttpServlet
- HttpServlet calls relevant methods of HttpServletRequest object to obtain Http request information
- HttpServlet calls relevant methods of httpservletreply object to generate response data
- The Servlet container transmits the response result of HttpServlet to the Web Client
6. HttpServletRequest object
HttpServletRequest object: it is mainly used to receive the request information sent by the client. For example, the request parameters and sent header information belong to the information sent by the client. The formal parameters in the service() method receive the instantiated object of the HttpServletRequest interface, indicating that the object is mainly applied to the HTTP protocol, The object is passed by Tomcat.
HttpServletRequest is the sub interface of ServletRequest. ServletRequest has only one sub interface, that is, HttpServletRequest. Since there is only one sub interface, why not combine the two interfaces into one?
in the long run: the main protocol used now is HTTP protocol, but more new protocols may appear in the future. If you want to support this new protocol in the future, you only need to directly inherit the ServletRequest interface.
there are many methods defined in the HttpServletRequest interface, but the functions are to receive various parameters from the client. How do we get the object? No, they will be directly passed in from the container in the service method, and all we need to do is take out the data in the object for analysis and processing.
6.1 receiving requests
6.1.1 common methods
1. Method
method | function |
---|---|
getRequestURL() | Get the full URL when the client sends the request, that is, the full path of the project |
getRequestURI() | Gets the resource name part in the request line (the relative path from the beginning of the project name) |
getQueryString() | Get the parameter part in the request line. The parameter is usually followed in the URL? Following string |
getMethod() | Get client request mode |
getProtocol() | Get HTTP version number |
getContextPath() | Get the webapp name, that is, the external access path of the current project, that is, the site name |
2. Examples
//Get the complete URL of the client request (starting from http and ending before) String url = request.getRequestURL.tostring(); System.out.println("Gets the complete of the client request URL:" + url); //Get the partial URL requested by the client (starting from the site name and ending before) String uri = request.getRequestURI(); System.out.println("Gets the portion of the client request URL: " + uri); //Gets the parameter part of the request line String queryString = request.getQueryString(); System.out.println("Gets the parameter part of the request line:" + queryString); //Get the request mode of the client String method = request.getMethod(); System.out.println("Get the request mode of the client:" + method); // Get HTTP protocol version String protocol = req.getProtocol().toString(); System.out.println("Get current HTTP Protocol version:" + protocol); // Get the site name (i.e. the external access path of the project), also known as the context path and the project name String webapp = req.getContextPath().toString(); System.out.println("Get the current project site name:" + webapp);
6.1.2 obtaining request parameters
1. Method
method | function |
---|---|
getParameter(name) | Gets the parameter with the specified name |
getParameterValues(String name) | Gets all values that refer to the name parameter |
2. Example
// Get the parameter value of the specified name (important and difficult, Returns a string // If it is passed in the way of parameter passing in the URL, the parameter name in parentheses must be the same as the parameter name passed in the browser // If it is sent in the form of a form, the parameter name in parentheses should be the same as the value of the name attribute of the form String uname = req.getParameter("uname"); String upwd = req.getParameter("upwd"); System.out.println("User name is:" + uname + ";The user password is:" + upwd); // Gets all parameter values of the parameter with the specified name (mainly used for check box value transfer) // Returns an array of strings String[] hobbys = req.getParameterValues("hobby"); System.out.println("Hobbies include:"); // It's best to make non empty judgment before traversing the array if (hobbys != null && hobbys.length > 0) { for (String hobby : hobbys) { System.out.println(hobby); } }
6.2 request garbled code
since the current request belongs to the parameter of the receiving client, it must have its default language code. Mainly because the default coding method used in the parsing process is iso-8859-1 (this code does not support Chinese), there will be garbled code during parsing. To solve this problem, you need to set the encoding method in the request to tell the server how to parse the data. Or after receiving the garbled data, restore it through the corresponding coding format. And the encoding format must be set before obtaining the request object, not after obtaining it.
One way:
request.setCharacterEncoding("UTF-8");
However, this method is only valid for POST requests (it must be set before receiving all data).
Mode 2:
new String(request.getParameter(name).getBytes("ISO-8859-1"),"UTF-8");
With the help of the method of String object, this method is effective for any request and is universal.
Note: tomcat8 Since 0, in the above versions, GET requests will not be garbled, but POST requests will still be garbled
import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * Request garbled problem * Reason for garbled Code: * The default encoding method used in the parsing process is iso-8859-1 (this encoding does not support Chinese) * Tomcat8.0 Above tomcat8 Below 0 * GET No random code * POST Garbled code * * Tomcat8 0 server, the request mode is GET mode, and there will be no garbled code, but the POST request will still be garbled * Use the form to implement the POST request for testing, and it is found that there are garbled codes * Eliminate garbled code by setting the format of the server parsing code * The reason for garbled code is that the server has a default code, so we need to manually modify the default code request setCharacterEncoding("UTF-8"); * Note: * 1. request.setCharacterEncoding("UTF-8")Only valid for POST request garbled code * 2. new String(request.getParameter(name).getBytes("ISO-8859-1"),"UTF-8");For any request * However, when the character itself is not encoded by ISO-8859-1, an error will be reported using this method */ @WebServlet("/request03") public class ServletRequest03 extends HttpServlet { @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // Set the encoding format of the request and solve the problem of garbled code of POST request req.setCharacterEncoding("UTF-8"); // Get parameters passed by foreground / client String uname = req.getParameter("uname"); String upwd = req.getParameter("upwd"); System.out.println("full name:" + uname + ";password:" + upwd); // Solve the GET garbled problem of Tomcat7 and below, for any request. // But not for Tomcat 8 0 or above, because tomcat8 The encoding format of GET request above 0 is not ISO-8859-1 String name = new String(req.getParameter("uname").getBytes("ISO-8859-1"), "UTF-8"); String password = new String(req.getParameter("upwd").getBytes("ISO-8859-1"), "UTF-8"); System.out.println("full name:" + name + ";password:" + password); } }
6.3 request forwarding
we talked about how to get the request from the client, so how does the server respond? Request forwarding is required here. Request forwarding is a behavior of the server. When the client request arrives, the server forwards it. At this time, the request object will be saved, and the URL address in the address bar will not change. After receiving the response, the server will send the response to the client, and only one request will be sent from beginning to end. The implementation method is as follows to achieve the effect of collaborative response of multiple resources.
import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * Request forwarding jump * request.getRequestDispatcher(url).forward(request, response); * You can jump the client request from the server to the client (or specify a Servlet) * This is a server-side behavior, which is controlled by the server * characteristic: * 1.You can only jump once * 2.The address bar does not change * 3.From beginning to end, only one request is forwarded, rather than copying a request and forwarding it again * 4.Data can be shared * Function: * Jump request from background to foreground */ @WebServlet("/request04") public class ServletRequest04 extends HttpServlet { @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // Parameters for receiving client requests String uname = req.getParameter("uname"); System.out.println("request04 Medium uname: " + uname); // Request forwarding jumps to request05 // req.getRequestDispatcher("request05").forward(req, resp); // Request forwarding jump to jsp page // req.getRequestDispatcher("login.jsp").forward(req, resp); // Request forwarding jump to html page req.getRequestDispatcher("login.html").forward(req, resp); } }
in Web applications, when we operate the browser page, we actually execute the behavior of transmitting data from the foreground to the background. If you do not request jump, the browser will be blank after the data is transferred to the background. Therefore, we need to transfer the requested data to another browser page and open it in the browser after data processing. The implementation principle of this process is request call.
6.4 request scope
data can be transferred in a request through the request scope object. Scope: valid in one request, that is, valid once the server jumps, that is, valid when the request is forwarded and jumped.
//Set the contents of domain objects and key value pairs request.setAttribute(String name, Object value); //Get domain object content request.getAttribute(String name); //Delete domain object content request.removeAttribute(String name);
if the data in the request domain object is valid in a request, the data in the request domain still exists after request forwarding, and the data can be transmitted / shared through request during request forwarding.
7. HttpServletReponse object
Each request object is used to create a response to the request of the Web server, which represents the response of each request.
request and response objects represent requests and responses: to obtain client data, you need to use the request object; To output data to the client, you need to use the response object.
the main function of HttpServletResponse is to respond to the request of the client and return the processed result of the Web server to the client. The formal parameter in the service() method receives the instantiation object of the HttpServletResponse interface. This object encapsulates the method of sending data, response header and response status code to the client.
7.1. Response data
after receiving the client request, you can respond directly through the HttpServletResponse object. When responding, you need to obtain the output stream. There are two forms: (Note: the following two methods cannot be used at the same time)
- getWriter(): get character stream (only characters can be responded back)
- getOutputStream(): get byte stream (can respond to all data)
The data returned from the response is parsed by the browser to the client.
/* getWriter() Character output stream */ // Get character output stream PrintWriter writer = resp.getWriter(); // output data writer.write("Hello!"); /* getOutputStream() Byte output stream */ // Get byte output stream ServletOutputStream out = resp.getOutputStream(); // output data out.write("Hi".getBytes()); // Where getBytes() can specify parameters of encoding method out.write("Hi".getBytes("UTF-8"));
7.2 response to garbled code
in the response, if the content of our response contains Chinese, there may be garbled code. This is because the data responded by the server will also be transmitted through the network. There is an encoding method on the server side and on the client side. When the encoding methods used at both ends are different, there will be random codes.
7.2.1 character garbled code of getwriter()
for the character stream obtained by getWriter(), the Chinese response must be garbled. Because the server will use the encoding in ISO-8859-1 format by default, this encoding method does not support Chinese.
to solve this kind of garbled code, we can only tell the server to use a coding format that can support Chinese, such as "UTF-8" we usually use.
// Set the encoding format on the server side response.setCharacterEncoding("UTF-8");
At this time, only half of the work is completed. To ensure the correct display of data, you need to specify the decoding method of the client.
// Set the decoding format of the client and the MIME type of the response response.setHeader("content-type", "text/html;charset=UTF-8");
After the codes are specified at both ends, the garbled code is solved.
//Set the code of the server response.setCharacterEncoding("UTF-8"); //Set the response type and code of the client response.setHeader("content-type","text/html;charset=UTF-8"); //Get character output stream Printwriter writer = response.getwriter(); writer.write("<h2>Hello</h2>");
The above two end codes can also be replaced by one sentence, and the coding format of the server and client can be specified at the same time.
response.setContentType("text/html;charset=UTF-8");
7.2.2 byte garbled code of getoutputstream()
for the byte stream obtained by getOutputStream(), when responding to Chinese, because it is the transmitted byte itself, it may appear garbled code or be displayed correctly. Whether the code is garbled or not depends on whether the byte encoding mode of the server is consistent with that of the client. When the bytes given by the server are exactly the same as the encoding method used by the client, the text will be displayed correctly, otherwise garbled code will appear. In any case, we should accurately grasp the coding format used by the server and client to ensure the correct display of data.
Specifies that the client and server use the same encoding.
response.setHeader("content-type","text/html;charset=UTF-8");
//Set the code and response type of the client ServletOutputStream out = response.getOutputStream(); response.setHeader("content-type","text/html;charset=UTF-8"); out.write("<h2>Hello</h2>".getBytes("UTF-8"));
7.3 redirection
redirection is a behavior of the client guided by the server. After the client sends the first request and is received and processed by the server, the server will respond. While responding, the server will give the client a new address. When the client receives the response, it will immediately, immediately and automatically launch the second request according to the new address given by the server. The server receives the request and responds, and the redirection is completed.
it can be seen from the description that there are two requests for redirection, which belong to the client behavior.
//Redirect to index jsp response.sendRedirect("index.jsp");
by observing the browser, we found that the response code obtained for the first request is 302 and contains a location header. And the address finally seen in the address bar is different from the first request address, and the address bar has changed.
7.4 difference between request forwarding and redirection
Request forwarding – > req getRequestDispatcher(url). forward(req,resp) | Redirect – > resp sendRedirect(url) |
---|---|
Once a request, the data is shared in the request field | Two requests, the data in the request field is not shared |
Server Behavior | Client behavior |
The address bar does not change | The address bar has changed |
After the absolute address is located to the site, the forwarded resources can only be the resources under the current site name, that is, the resources under the current project | The absolute address can be written to http: / /, and can span any address |
both can realize page Jump, which can be selected according to actual needs.
the most important difference: the address of request forwarding can only be the resources under the current site (current project); When redirecting, the address can be any address. Therefore, if you want to jump across domains, you can only use redirection; If cross domain is not used, both can be used. At the same time, if you need to share the request object, you can only use request forwarding; If you do not need to share the request object, you can use both.
8. Cookie object
Cookie is a technology provided by the browser. Through the program of the server, some data that only needs to be saved in the client or processed in the client can be placed in the hard disk or memory of the local computer without transmission through the network, so as to improve the efficiency of web page processing and reduce the load of the server, However, because cookies are the information saved by the server to the client, their security is also very poor. For example, the common method of remembering passwords can be realized through cookies. In addition, the principle of advertisement push is also based on cookies. When the client browses a large amount of certain information, the browser will record the Cookie information of these contents, and then push relevant advertisements according to these Cookie information.
there is a special class javax for operating cookies servlet. http. Cookie. With the server-side response sent to the client, it is saved in the browser. Bring the cookie back to the server the next time you visit the server.
Cookie format: key value pairs are linked with "=", and multiple key value pairs are linked with ";" separate.
why use cookies: Web programs are transmitted using HTTP protocol, which has a feature of "statelessness" and has no memory function for things. If the previous information needs to be processed later, it must be retransmitted, which will increase the amount of data transmitted each connection. Therefore, cookies can make up for the shortcomings of HTTP protocol. And because HTTP protocol is a stateless protocol, the server cannot know the identity of the client only from the network link, so it needs to issue a pass to the client to facilitate the server to identify the client information.
every time you visit the server, the browser will send the Cookie back to the server (background).
8.1 creation and sending of cookies
via new Cookie("key", "value"); To create a cookie object. If you want to send the cookie to the client with the response, you need to first add it to the response object, response addCookie(cookie);, At this time, the cookie object is sent to the client with the response. It can be seen in the browser.
//Create Cookie object Cookie cookie = new Cookie( "uname","zhangsan"); //Send Cookie object response.addCookie(cookie);
8.2 obtaining cookies
only one getCookies() method is provided on the server side to obtain an array composed of all cookies returned by the client. There is no method to obtain a specific cookie. If you need to obtain a single cookie, you need to traverse, getName() to obtain the name of the cookie and getValue() to obtain the value of the cookie.
//Get cookie array Cookie[] cookies = request.getCookies(); //Determine whether the array is empty if (cookies != nu11 && cookies.length > 0) { //Traversal cookie array for (Cookie cookie : cookies){ System.out.println(cookie.getName()); System.out.println(cookie.getValue(); } }
8.3 Cookie setting expiration time
in addition to the name and content of the cookie, we also need to care about a message, expiration time, which is used to specify when the cookie expires. The default is that the current browser will expire when it is closed. We can manually set the effective time of the cookie (calculated by the expiration time) through setMaxAge(int time); Method to set the maximum effective time of a cookie, in seconds.
Cookie is a browser technology that has nothing to do with the server. Whether the server is opened or not does not affect the value of the Cookie. It is only related to whether the browser is opened or not.
Value of Cookie expiration time:
-
negtive integer
╭ if the cookie is not stored, it means that it is not a negative number. The default value of the maxAge attribute of the cookie is - 1, which means it only exists in the browser memory. Once the browser window is closed, the cookie will disappear.
-
positive integer
if it is an integer greater than 0, it indicates the number of seconds stored. Indicates the specified number of seconds that the cookie object can survive. When the life is greater than 0, the browser will save the cookie to the hard disk (generally in the user directory of drive C). Even if the browser is closed and the client computer is restarted, the cookie will survive for the corresponding time.
-
Fatal Frame
if it is 0, it means to delete the cookie. Cookie life equal to 0 is a special value, which means that the cookie is invalidated! In other words, if the original browser has saved the cookie, you can delete the cookie through setMaxAge(0) of the cookie. This cookie will be deleted either in the browser memory or on the client hard disk.
8.4 precautions for cookies
1. The cookie is saved in the current browser.
in general sites, there is often an operation to remember the user name. This operation only saves the information on the local machine. After changing the computer or reinstalling the browser, these information will be invalid. And cookies can't cross browser.
2. The cookie is stored in Chinese
Chinese cannot appear in the Cookie. If there is Chinese, you need to go through urlencoder first Encode(), and then use urlcoder Decode ().
String name ="full name"; String value ="Zhang San"; //Through urlencoder Encode() name = URLEncoder.encode(name); value = URLEncoder.encode(value); //Create cookie object Cookie cookie = new Cookie(name, value); //Send cookie object response.addCookie(cookie);
//Get through urlcoder Decode () URLDecoder.decode(cookie.getName()); URLDecoder.decode(cookie.getValue();
3. Cookie with the same name
if the server sends duplicate cookies, the new Cookie will overwrite the original Cookie.
4. Number of cookies stored in the browser
different browsers also have restrictions on cookies, and there is an upper limit on the storage of cookies. Cookie s are stored in the client (browser), and are generally created and set by the server. In the later stage, Session tracking is implemented in combination with Session.
8.5 Cookie path
setPath of cookie sets the path of the cookie, which directly determines whether the server's request will load some cookies from the browser.
Scenario 1: any resource of any item under the current server can obtain Cookie objects
/*The current project path is: s01*/ Cookie cookie = new Cookie( "xxx", "xXX"); //Set the path to "/", which means that any item under the current server can access the Cookie object cookie.setPath("/"); response.addCookie(cookie);
Scenario 2: the Cookie object can be obtained from the resources under the current project (that is, by default, the path of the Cookie is not set)
/*Current project path: s01*/ Cookie cookie = new Cookie( "xxx", "xxx"); //Set the path to "/ s01", which means that any project under the current project can access the cookie object cookie.setPath("/s01"); //By default, the value of path can not be set response.addCookie(cookie);
Scenario 3: the Cookie object can be obtained from the resources under the specified item
/*Current project path: s01*/ Cookie cookie = new Cookie("xxx", "xXX"); //Setting the path to "/ s02" means that the cookie object can only be accessed under s02 project cookie.setPath("/s02"); //The cookie can only be obtained under the s02 project. Even if the cookie is generated by s01, s01 cannot obtain it response.addCookie(cookie);
Scenario 4: the Cookie object can be obtained from the resources in the specified directory
/*Current project path: s01 */ cookie Cookie = new Cookie("xxx" , "xXX"); //Set the path to "/ S01 / cookie", which means that the cookie object can be accessed only in the S01 / cookie directory cookie.setPath("/s01/cook"); response.addCookie(cookie);
if we set path, if the current access path contains the path of the cookie (the current access path is smaller than the range of the cookie based on the cookie path), the cookie will be loaded into the request object.
the path of a cookie refers to the top-level directory where the cookie can be accessed, and the sub path of the path can also access the cookie.
Summary: when the accessed path contains the path of the cookie, the request will bring the cookie; If the access path does not contain a cookie path, the request will not carry the cookie.
9. HttpSession object
the HttpSession object is javax servlet. Http. An instance of HttpSession. Unlike HttpServletRequest or HttpServletResponse, this interface also has a parent interface, which is just a pure interface. This is because Session itself belongs to the category of Http protocol.
Session is also called Session. For the server, every client connected to it is a Session. The Servlet container uses this interface to create a Session between the HTTP client and the HTTP server. Sessions are retained for a specified period of time, across multiple connections or page requests from users. A Session usually corresponds to a user who may visit a site multiple times. Through this interface, you can view and operate information about a Session, such as Session identifier, creation time and last access time. In the whole Session, the most important thing is the operation of attributes.
Session can be perceived by both the client and the server, but if you reopen a new browser, you cannot obtain the previously set Session, because each Session is only saved in the current browser and obtained on the relevant page. Restarting the server or browser, changing browser access and other operations will empty the Session object in the Servlet container.
Http is stateless. When the client sends the first request, it sends the second request. The second request cannot obtain the data or information in the first request, that is, we cannot share data among multiple requests. Session is used to identify a session, or confirm a user. Each browser's access site corresponds to a SessionId; And share data during a session (multiple requests from a user). We can use request Getsession () method to obtain the session object of the current session.
A session includes multiple requests and responses, and the data between requests during a session can be shared.
// If the Session object exists, get; If not, create HttpSession session = request.getSession();
Session refers to a user. Because a browser is a user, you can access the same site in the same browser, and the session identifier remains unchanged. Changes only when the browser is changed.
9.1 identifier JSESSIONID
Since the purpose of Session is to identify a Session, this Session should have a unique flag, which is sessionld.
every time a request arrives at the server, if a Session is opened (Session is accessed), the server will check whether a cookie named JSESSIONID is returned from the client. If not, it will be considered as a new Session, a new Session object will be created, and a unique Session LD will be used to mark the Session. If the cookie "JSESSIONID" is returned, the server will check whether there is a Session object with id of JSESSION value according to the value of JSESSIONID. If not, it will be considered as a new Session, re create a new Session object and mark the Session; If the corresponding Session object is found, it is considered to be a previously marked Session. The Session object is returned and the data is shared.
a Cookie called JSESSIONID is mentioned here. This is a special Cookie. When a user requests the server, if he accesses a Session, the server will create a Cookie object named JSESSIONID with the value of sessionld of the acquired Session (whether acquired or newly created) and add it to the response object, Respond to the client, and the effective time is to close the browser.
therefore, the bottom layer of Session depends on cookies.
9.2 Session domain object
Session is used to represent a Session in which data can be shared. At this time, Session exists as a domain object. You can add data to the domain object through setAttribute(name,value) method, obtain data from the domain object through getAttribute(name), and remove data from the domain object through removeAttribute(name).
//Get session object HttpSession session = request.getSession(); //Set session domain object session.setAttribute( "uname","admin"); //Gets the session domain object with the specified name String uname = (String) request.getSession().getAttribute("uname"); //Removes the Session domain object with the specified name session.removeAttribute("uname");
data is stored in the Session domain object. When the Session object does not exist or there are two different Session objects, the data cannot be shared. We have to talk about the life cycle of Session.
session domain objects are very different from request domain objects. Session domain objects exist as long as the browser is not closed; The request domain object exists in only one request.
9.3 destruction of session object
as long as the Session is not destroyed, the Session domain object can always share data
9.3.1 default time expiration
when the client requests the Servlet for the first time and operates the Session, the Session object is generated. The default survival time of the Session in Tomcat is 30min, that is, the time when you do not operate the interface. Once there is an operation, the Session will be timed again. Can the default time of Session be changed? The answer is yes.
it can be found on the web under the conf directory in Tomcat XML file.
<!-- session The default maximum inactivity time. Company:minute.--> <session-config> <session-timeout>30</session-timeout> </session-config>I
9.3.2 set your own expiration time
of course, in addition to the above modification methods, we can also set the life cycle of Session in the program through Session Setmaxinactivlnterval (int) to set the maximum inactivity time of the Session, in seconds.
//Get session object Httpsession session = request.getSession(); //Set the maximum inactivity time of the session to 15 seconds session.setMaxInactiveInterval(15);
of course, we can also check the maximum inactivity time of the current Session object through the getmaxinactivity interval () method.
9.3.3 directly and immediately destroy the Session object
or we can use Session The invalidate (0) method invalidates the Session. This will make each visit to the site a new Session, and JSESSIONID will be different.
//Destroy session object session.invalidate();
9.3.4 close browser
as can be seen from the previous JSESSIONID, the underlying layer of the Session depends on the Cookie implementation, and the Cookie object only lives in the browser memory by default, that is, the effective time of the Cookie is to close the browser, so the Session is equivalent to invalidation when the browser is closed (because there is no JSESSIONID to correspond to it).
9.3.5 shut down the server
The session object belongs to the server and is controlled by the server. Server shutdown resets all configurations, so the session is destroyed when the server is shut down. Session destruction means that the session ends and data sharing ends.
10. ServletContext object
every Web Application has only one ServletContext object, also known as Application object. From the name, it can be seen that this object is related to the Application. When the Web container starts, a corresponding ServletContext object will be created for each Web Application.
this object has two functions:
- First, as a domain object, it is used to share data. At this time, the data is shared in the whole application.
- Second, the object stores the relevant information of the current application. For example, you can get the current server information through getServerInfo() method, and get the real path of resources through getRealPath(Stringpath).
10.1 acquisition of ServletContext object
There are many ways to get ServletContext objects. For example:
-
Get through request object
ServletContext servletcontext = request.getServletContext();
-
Get through the session object
ServletContext servletcontext = request.getSession().getServletContext();
-
Obtained through the servletConfig object, the getServletConfig method is provided in the Servlet standard
ServletConfig servletconfig = getServletConfig(); ServletContext servletcontext = servletconfig.getServletContext();
-
Direct acquisition
However, this method can only be used in servlets. If it is not in the Servlet class, it cannot be called directly.
ServletContext servletcontext = getServletContext();
10.2 ServletContext domain object
ServletContext can also be used as a domain object. By accessing data to ServletContext, the whole application can share some data. Of course, it is not recommended to store too much data, because once the data in ServletContext is stored and not manually removed, it will always be saved.
//Get ServletContext object ServletContext servletcontext = request.getServletContext(); //Set domain object servletcontext.setAttribute("name", "zhangsan"); //Get domain object String name = (String) servletcontext.getAttribute("name"); //Remove domain object seryletcontext.removeAttribute("name");
Three domain objects of Servlet
- request domain object
Valid in one request. The request forwarding is valid and the redirection is invalid. It is most used in future applications. - session domain object
Valid in one session. Both request forwarding and redirection are valid, and the session fails after being destroyed. - servletContext domain object
Valid throughout the application. Failure after server shutdown.
11. Upload and download of documents
when surfing the Internet, we often encounter file uploading, such as uploading avatars, uploading materials, etc; Of course, in addition to uploading, there are many cases of downloading. Next, let's see how to upload and download files in our Servlet.
11.1 file upload
file upload involves the preparation of the foreground page and the background server-side code. The foreground sends the file, and the background receives and saves the file to the specified page. This is a complete file upload.
11.1.1 front page
when uploading files, there will be an interface for uploading files. The foreground page can be HTML page or JSP page. First, we need a form, and the request method of the form is POST; Secondly, the enctype of our form must be set to "multipart / form data", that is, enctype = "multipart / form data", which means to set the form type to file upload form. By default, this form type is "application/x-www-form-urlencoded" and cannot be used for file upload. Only when multipart / form data is used can the file data be transferred completely.
<!-- File upload form 1. Submit form type method= "post" 2.form types enctype= "multipart/form-data" 3.Form element type file field settings name Attribute value 4. Address of document submission action="" --> <form method="post" action="uploadservlet" enctype="multipart/form-data"> full name: <input type="text" name="uname" > <br> file: <input type="file" name="myfile" > <br> <button type="submit">Submit</button> </form>
11.1.2 background implementation
use the annotation @ MultipartConfig to identify a servlet as supporting file upload. Servlet encapsulates the POST request of multipart / form data into Part, and operates the uploaded file through Part.
package com.liangshao.fileUpload; import javax.servlet.ServletException; import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.Part; import java.io.IOException; @WebServlet("/UploadServlet") @MultipartConfig // If it is a file upload form, be sure to add this annotation!!!!! public class UploadFile extends HttpServlet { @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("File upload"); // Set the encoding format of the request req.setCharacterEncoding("UTF-8"); // Get common form items String uname = req.getParameter("uname"); System.out.println("uname: " + uname); /* get files */ // Get Part object Part part = req.getPart("myfile"); // Get the uploaded file name through the Part object String fileName = part.getSubmittedFileName(); System.out.println("The uploaded file name is:" + fileName); // Get the file storage path String filePath = req.getServletContext().getRealPath("/"); System.out.println("File storage path:" + filePath); // Upload files to the specified directory part.write(filePath + "/" + fileName); } }
11.2 file download
file download refers to downloading (copying) the resources on the server to the local. We can download them in two ways. The first is to download through the characteristics of hyperlinks themselves; The second is through code download.
11.2.1 hyperlink Download
when we use a tag in HTML or JSP pages, the original intention is to jump, but when the hyperlink encounters resources that the browser does not recognize, it will be downloaded automatically; When you encounter resources that the browser can display directly, the browser will display them by default, such as txt, png, jpg, etc. Of course, we can download through the browser attribute. But some browsers don't support it.
Default download
<!--When a hyperlink encounters a resource that is not recognized by the browser, it will be automatically downloaded--> <a href="test.zip">Hyperlink Download</ a>
Specify the download attribute to download
<!--When a hyperlink encounters a resource recognized by the browser, it will not be downloaded by default. adopt download Properties can be downloaded--> <a href="test.txt" down1oad>Hyperlink Download</ a>
The download attribute can not write any information and will automatically use the default file name. If the value of the download property is set, the set value is used as the file name. When users open the browser and click the link, they will download the file directly.
11.2.2 background download
Implementation steps
- You need to pass the response The setcontenttype method sets the value of the content type header field, which is the MIME type that the browser cannot use some way or activate a program to process, such as "application / octet stream" or "application/x-msdownload".
- You need to pass the response Setheader method sets the value of content disposition header as "attachment,filename = filename"
- Read the downloaded file and call response The getoutputstream method writes the attachment content to the client.