Based on the Servlet summary in the javaWeb stage, the servlet in the javaweb stage
1. Servlet Overview
Servlet is a server program written in Java. It uses the request-response mode to provide Web services and supports standard ServletAPI. Servlet is a small Java program running on the web server, it is used to process and respond to requests sent from web clients. Current version is 3.1.
2. Servlet implementation process
1). the client sends a request to the server;
2) the server sends the request to the Servlet;
3). The Servlet generates the response content and then transmits it to the server (generally, the generated response content is determined by the request from the client in the server );
4). The slave server returns a response to the client;
3. Servlet Lifecycle
To put it simply, the Servlet life cycle is the whole process from creation in the server to request response to destruction.
In eclipse, the init () method is Servlet instantiation, that is, it is created. Note: no matter how many requests or responses the Servlet receives from the server, init () will only be executed once;
The service () method calls the doPost or doGet Method Based on the Request Method of the client (generally referred to as the previous paragraph), and executes the request and response of the server; destroy () when the Servlet is removed from or closed from the server, the Servlet is destroyed.
4. Servlet loading at startup
The ervlet object will be created when it is accessed for the first time, and the init method will be executed, which will consume some time to configure the web in eclipse. in the xml file, the Servlet instantiation process is placed at the server startup (the Servlet object is created when the server is started ). Use <load-on-startup> for configuration. Note that loading on the Tomcat server is 1 second. Therefore, we recommend that you set the time to be less than 1 second.
Configure Servlet in web. xml
<Servlet>
<Serlvet-name> custom name </serlvet-name>
<Servlet-class> class path with package name </servlet-class>
<Load-on-startup> time unit: seconds </load-on-startup>
</Servlet>
<Servlet-mapping>
<Serlvet-name> custom name </serlvet-name>
<Url-pattern>/the path appears in the address bar. </url-pattern>
</Servlet-mapping>
5. Servlet access path Configuration
Full path match starts "/"
Directory matching starts with "/" and ends "*"
The extension name must start "*".
Scope size: Full Path Matching> directory matching> extension matching
6. Differences between Servlet and HttpServlet
HttpServlet inherits from Servlet, while HttpServlet satisfies all Servlet methods. HttpServlet is a class and Servlet is an interface. HttpServlet is a protocol-related Servlet that is used to process Http requests. Generally, compiling a Servlet will make the Servlet inherit from HttpServlet and rewrite the service method. Therefore, after inheriting HttpServlet, you do not need to override the service method. You only need to override the doGet and doPost methods. The code of the content to be processed by requests is usually the same. Therefore, it is necessary to make doGet and doPost mutually called to simplify programming.
7. Differences between ServletConfig and ServletContext
ServletConfig is in the Servlet configuration file. When you use the <url-pattern> label to configure some Servlet initialization parameters, the data is encapsulated in ServletConfig. While ServletContext is used throughout the web application, the initialized parameters are encapsulated in ServletContext, and all the parameters of ServletConfig are also included, servletContext is used for communication between multiple Servlet objects.
In short, ServletConfig is the object for obtaining Servlet-related configuration, which is equivalent to a class, while ServletContext is the object for obtaining configuration related to the entire web, which is equivalent to the entire project.
8. Methods of ServletConfig and ServletContext
1). ServletConfig Method
Get the ServletConfig object: getServletConfig ()
Get Servlet initialization parameter: getInitparameterNames ()
Get Servlet initialization parameter (single): getInitparameter (String name)
Get the ServletContext object: getServletContext ()
Get Servlet name: getServletName ()
2). ServletContext Method
Get the ServletContext object: getServletContext ()
Get the object MIME type: getMimeType (String file)
Get a web project request Project name: getContextPath ()
Obtain the global initialization parameter: getInitparameterNames ()
Obtain the global initialization parameter (single): getInitparameter (String name)
9. Scope and method of ServletContext
Scope: stores data into the domain object, and this data has a certain scope of effect. Scope refers to a certain scope of action. Therefore, the scope of ServletContext is global and the entire web project.
Method:
Stored data: setAttribute (String name, Object object)
Get data: getAttribute (String name)
Remove Data: removeAttribute (String name)
10. Response Request data
The difference between the ServletResponse interface and the HttpServletResponse interface: HttpServletResponse inherits from ServletResponse, and HttpServletResponse satisfies all ServletResponse methods. HttpServletResponse has Http protocol and is consistent with HttpServlet.
Common response status codes: 200 is correct; 302 is redirected; 304 is used to find the local cache; 404 The requested resource does not exist; 500 is an internal server error
11. Response Method
Set the response status code: setStatus (int so)
Set the response header: setHeader (String name, String value)
Add Response Header: addHeader (String name, String value)
Response stream write response body: getWriter ()
Byte stream write response body: getOutoutStream ()
Redirection: sendRedirect (String string)
Set the character set used by the browser: setContentType (String string)
SetCharacterEncoding (String charset)
The server writes the Cookie back to the browser: addCookie (Cookie cookie)
12. Request to receive data
The difference between the ServletRequest interface and the HttpServletRequest interface: the difference is the same as that between the ServletResponse interface and the HttpServletResponse interface.
13. Request Method
Request Method: getMethed ()
String of the request parameter after obtaining the Request Path: getQueryString ()
Get the URL of the Request Path: getRequestURL ()
Get the URI of the Request Path: getRequestURI ()
Get the Client IP Address: getRemoteAddr ()
Get the request header corresponding to a value for a key: getHeader (String name)
GetHeaders (String names)
Submitted parameter (a name corresponds to a value): getParameter (String name)
Submitted parameter (one name corresponds to multiple values): getParameterValues (String names)
Submitted parameters (Map set method): getParameterMap ()
Data storage: setAttribute (String name, Object object)
Get data: getAttribute (String name)
Remove Data: removeAttribute (String name)
14. Chinese garbled characters of Response and Request
Because the Servlet language settings are ISO-8850-1, it does not support Chinese, so in the request and response is a Chinese garbled.
1). Response solves Chinese garbled characters
A. byte stream response (Chinese)
Cause: in fact, the generation of this Garbled text is related to the conversion of Chinese characters into byte arrays and the browser opening method (the default character set used when opening.
Solution: Convert Chinese to byte array and browser default open when using the character set can be consistent, are converted to UTF-8.
Solution code:
ServletOutoutStream out = response. getOutoutStream ();
Response. setHeader ("Content-Type", "text/html; charset = UTF-8 ");
Out. write ("Chinese string". getBytes ("UTF-8 "));
B. Simplified stream response
Cause: the response stream has a buffer, response gets the response stream, and response design the default buffer encoding is the ISO-8859-1.
Solution: Set response to get the encoding of the response stream buffer and set the character set used when the browser is opened by default.
Solution code:
Response. setHeader ("Content-Type", "text/html; charset = UTF-8 ");
Response. setCharacterEncoding ("UTF-8 ");
Response. getWriter (). println ("Chinese character string ");
Simplified Version:
Response. setContentType ("text/html; charset = UTF-8 ");
Response. getWriter (). println ("Chinese character string ");
2). Request to solve Chinese garbled characters
A. the Post method receives Chinese Characters
Cause: the post method of submitting data is in the request body, the request object is put into the buffer after receiving the data, it will produce the buffer encoding is ISO-8859-1.
Solution: Modify the request Buffer code.
Solution code:
Request. setCharacterEncoding ("UTF-8 ");
String str = request. getInitparameter ("// parameter to be modified ");
System. out. println (str );
B. Receive Chinese Characters in Get Mode
Cause: the post method for data submission is after the Request Line url, and the url encoding will be performed in the address bar.
Solution: store the value in the buffer to decode the ISO-8859-1 in UTF-8
Solution code:
String encode = URLEncoder. encode (// parameter to be modified, "ISO-8859-1 ");
String decode = URLDecoder. decode (encode, "UTF-8 ");
System. out. println (decode );
Solution Code 2:
String // The parameter to be modified = request. getParameter ("// The parameter to be modified ");
String str = new String (// parameter to be modified. getBytes ("ISO-8859-1"), "UTF-8 ");
System. out. println (str );
15. Differences between Get requests and Post requests
* Get submission Mode features: data is spliced to the address bar without a request body. Post submission Mode features: No submitted data is spliced to the address bar with a request body;
* The parameter list submitted by Get is spliced to the end of the address bar; the address bar is not spliced in Post mode;
* The sensitive data submitted by the Get method is insecure; the data submitted by the Post method is relatively secure;
* The Get method has a limited amount of data submitted; the Post method theoretically has an unlimited amount of data submitted.
Therefore, developers generally use Post requests to send data.