Java web daily Servlet working principle details analysis, assumervlet

Source: Internet
Author: User
Tags error status code

Java web daily Servlet working principle details analysis, assumervlet

In the previous article, we introduced the Servlet implementation method and the Servlet lifecycle. This article will introduce common objects.

Click to review: Working Principle Analysis of servlets learned by Java Web every day; Working Principle Analysis of servlets learned by Java Web every day (2)

1. HttpServletRequest object

1. Introduction
HttpServletRequest object: it is used to receive the request information sent by the client. For example, the request parameters and the sent header information all belong to the information sent by the client. service () the parameter in the method receives the instantiated object of the HttpServletRequest interface, indicating that the object is mainly applied to the HTTP protocol, and the object is encapsulated and transmitted by Tomcat.

HttpServletRequest is a sub-interface of ServletRequest. ServletRequest has only one sub-interface, that is, HttpServletRequest. Since there is only one subinterface, why not merge the two interfaces into one?

In the long run, the main protocol currently used is HTTP, but more new protocols may appear in the future. To support this new protocol in the future, you only need to inherit the ServletRequest interface directly.

There are many methods defined in the HttpServletRequest interface, but they all focus on receiving client parameters.
But how can we get this object? No, it is passed in directly by the container in the Service method. What we need to do is retrieve the data in the object for analysis and processing.

2. Common Methods
Request Method + url + version
GetRequestURL: returns the complete URL when the client sends a request.
GetRequestURI: return the resource name in the request line (project name starts)
GetQueryString: return the parameter section of the request line.
GetMethod: Obtain the client request method.
GetProtocol: Get the HTTP Version Number
GetContextPath: Get the webapp name

Obtain several client Message Headers
GetHeader (String name): obtains the content of a single request header.
Enumeration <String> getHeaderNames (): obtains a set of all request header names.

Obtain client request parameters (data submitted by the client)
GetParameter (name): gets the parameter value of the specified name. This is one of the most common methods.
GetParameterValues (String name): obtains an array of all values of the specified name parameter. It is applicable when a parameter name corresponds to multiple values, for example, the check box in the page form and the value submitted in the multiple choice list.

GetParameterNames (): returns an Enumeration object containing all parameter names in the request message. By traversing this Enumeration object, you can obtain all the parameter names in the request message.

GetParameterMap (): returns a Map object that saves all parameter names and values in the request message. The key of the Map Object is the parameter name of the string type, and value is the array of values of the Object type corresponding to this parameter.

3. Request garbled Solution
Because the current request is a parameter of the receiving client, it must have its default language encoding, it is mainly because the default encoding method used in the parsing process is ISO-8859-1 (this encoding does not support Chinese), so the parsing will appear garbled. To solve this garbled problem, you need to set the encoding method in the request to tell the server how to parse the data.

① Req. setCharacterEncoding ("UTF-8"); this method is only valid for POST
② New String (req. getParameter (name). getBytes ("ISO-8859-1 "));
GET will not contain garbled characters After Tomcat 8
Tomcat8 and above Get will not be garbled, don't worry

4. Jump
Request. getRequestDispacther ("address to jump"). forword (request, response );
Request forwarding, server jump, the URL in the address bar remains unchanged.

When writing a path, the path starting with/or http: // is an absolute path. If it does not start with/, it is a relative path. During request forwarding, "/" indicates the server path + site name, http: // localhost: 8080/site name

Request forwarding process:
The customer first sends a request to the server. The server finds a matched servlet and specifies it for execution. After the servlet is executed, it calls the getRequestDispacther () method, forward the request to the specified test. jsp: the whole process is completed on the server side and in the same request. Therefore, servlet and jsp share the same request and put everything in the servlet, in jsp, The getAttribute () result can be obtained. After getAttribute () is obtained, the result is returned to the client after execution. The whole process is a request and a response.

5. request domain object
This object can be used to transmit data in a request. The value is valid in a request, that is, the server jump is valid.
Request. setAttribute (): sets the content of the request domain object.
Request. getAttribute (String name): obtains the content of the specified request domain object.
Request. removeAttribute (String name): deletes the specified request domain object.

2. HttpServletResponse object

1. Introduction
When the Web server receives an http request from the client, it creates a request object representing the request and a response object for each request.

The request and response objects represent requests and responses: Get client data, output data to the client through the request object, and use the response object.

The main functions of HttpServletResponse are used by the server to respond to client requests and return the results processed by the WEB server to the client. The parameter in the service () method receives the instantiated object of the HttpServletResponse interface. This object encapsulates the method for sending data to the client, sending a response header, and sending a response status code.

2. Common Methods
AddCookie: adds the specified Cookie to the current response.
AddHeader (String name, String value): adds the specified key value to the response header information.
ContainsHeader (String name): returns a Boolean value to determine whether the response header is set.
EncodeURL (String url): encode the specified URL
SendError (int SC): Send an error to the client using the specified status code
SendRedirect (String location): Send a temporary response to the client, redirect
SetHeader (String name, String value): sets the Response Header for the given name and value.
SetStatus (int SC): Set the status of the current response
SetContentType (String ContentType): sets the MIME type of the response.
GetWriter (): gets the Output Response stream.
GetOutputStream (): Get the output byte stream

3. Set header information
1) refresh and jump to the page
All header information is automatically sent to the server (client) along with the request and response. A common header information in response is a refresh command, which can be used to complete the timed refresh function.
Resp. setHeader ("refresh", "2 ");

In addition to the timed function, the refreshed header also provides the timed jump function, allowing a page to jump to a specified page at a scheduled time. (Registered successfully. You will be redirected to the login page in two seconds)
Response. setHeader ("refresh", "3366url1_ OK .html ");

However, this type of jump is not omnipotent. Sometimes the jump operation cannot be performed at all, and the jump will not be refreshed after the return;
You can also set the header information for this scheduled jump in HTML mode. You can also set the header information for HTML itself. (Client jump)
<Meta http-equiv = "refresh" content = "3; http://www.shsxt.com>

2) return status code
The setStatus method is used to set the status code returned by the Servlet to the client. It is used to set the status without errors, which is usually not used. If the Servlet fails to run, the Servlet can use the sendError method to set the status code, for example, the sendError (int SC) method to set the error status code. The sendError (int SC, String msg) method sends an error message to the customer in addition to setting the status code.
3) add Cookie
The addCookie method can add a Cookie object to the Web server response, which will be saved by the browser. The Cookie mechanism is also used to maintain the session status.
4. Jump
Response. sendRedirect ("the path to jump ");
You can also jump through response. This type of jump is called request redirection, which is a client jump. The address bar is changed and there are two requests. Parameters in the request cannot be transferred between these redirects.
When writing a path, the path starting with/or http: // is an absolute path. A relative path is not starting with/. During redirection, "/" indicates the server path, that is, http: // localhost: 8080

5. Redirection process:
The client browser sends an http request ---> the web server sends a 302 status code response and corresponding location to the client browser after receiving the request --> the browser finds that the response is 302, A new http request is automatically sent, and the request url is the new location address --> the server searches for resources based on the request and sends them to the customer.

6. Respond to garbled code
Garbled characters may exist when the server responds to the client in Chinese.
Two response methods: PrintWriter and ServletOutputStream
The getOutputStream and getWriter methods are mutually exclusive. After you call any of the methods, you cannot call another method.
PrintWriter (): Must be garbled, the server automatically uses the ISO-8859-1 encoding, through the following method to solve garbled
Response. setCharacterEncoding ("UTF-8 ");
Response. setHeader ("content-type", "text/html; charset = UTF-8 ");
The first two sentences:
Response. setContentType ("text/html; charset = UTF-8 ");
OutputStream (): Garbled

7. Note the following when OutputStream is used to output Chinese characters:
The data output encoding method on the server is the encoding method opened by the client.
Example: outputStream. write ("China ". getBytes ("UTF-8"); Use OutputStream to output Chinese characters to the browser. The encoding method is UTF-8. In this case, the client browser must also open the code in UTF-8; otherwise, Chinese characters may be garbled. On the server side, you can control the display of the client browser in UTF-8 encoding mode. In this case, you can either solve the PrintWriter mode or set the response header information:
Response. setHeader ("content-type", "text/html; charset = UTF-8 ");

Iii. HttpSession object
1. Introduction
The HttpSession object is an instance of javax. servlet. http. HttpSession. This interface does not have a parent interface like HttpServletRequest or HttpServletResponse. This interface is just a pure interface. Because session belongs to the scope of HTTP protocol.

For a server, each 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. The session retains the specified time range for cross-connection or page requests from the user. A session usually corresponds to a user who may access a site multiple times. You can use this interface to view and operate information about a session, such as the session identifier, Creation Time, and last access time. In the entire session, the most important thing is the attribute operation.
Sessions can be obtained from both the client and the server. If you open a new browser, you cannot obtain the previously set session because each session is only saved in the current browser, and get it on the relevant page.

2. Use
Common Methods
SetAttribute (String name, Object value): bind the value Object to the session with the name
GetAttribute (String name): gets the attribute value of name. If the attribute does not exist, null is returned.
RemoveAttribute (String name): deletes the name attribute from the session. If the attribute does not exist, it will not be executed or thrown an error.
Enumeration getAttributeNames (): returns the session-related enumerated values.
Invalidate (): invalidates the session and deletes attribute objects.
IsNew (): used to check whether the current customer is a new session
Long getCreationTime (): returns the session creation time.
GetLastAccessedTime (): returns the time when the web Container receives the last request from the client during the session time.
Int getMaxInactiveInterval (): returns the maximum time for a customer request during a session to be in seconds.
SetMaxInactiveInterval (int seconds): maximum time allowed for client requests
ServletContext getServletContext (): returns the context of the current session. The ServletContext object allows the Servlet to communicate with the web container.
String getId (): returns the identification number during the session.

Session: It is created by default when Session is used for the first time.
Cookie: most of them are set to the browser through the active server (Program manually). Only the JSESSIONID is set by the service itself, so programmers do not need to worry about it.
Session id

Each user actually represents different sessions. The server uses session IDs to distinguish these users, that is, each user connected to the server through a browser will be assigned a unique number that will not be duplicated by the server.
The JSESSIONID value automatically set by cookie is the session id of each user. Therefore, the session uses the cookie Processing Mechanism during operations.

End of session id
① The lifecycle expires (the browser is opened and closed by default)
② Disable Server session destruction abnormally
If the server is shut down normally, the session object will not be destroyed, but will be serialized to the disk.
SESSION. ser in the workspace work directory
③ Call the invalidate () method of the session
In all project development, the most commonly used session is the login verification and logout function.
3. session domain object
One session creates an HttpSession object.
Data in the session.
Request. getSession (). setAttribute (): sets the content of the session domain object.
Request. getSession (). getAttribute (String name): obtains the content of the specified session domain object.
Request. getSession (). removeAttribute (String name): deletes the specified session domain object.

4. ServletContext object
1. Introduction
A web Application has only one ServletContext object. All servlets share this ServletContext object, also known as the Application object. When a WEB container is started, a corresponding ServletContext object is created for each WEB application, which represents the current WEB application. ServletContext defines a set of methods. servlet uses these methods to communicate with other servlet containers. The ServletContext object is included in the ServletConfig object, And the ServletConfig object is provided to the servlet by the web server during servlet initialization.

2. Common Methods
GetInitParameter (String name): Get initialization parameters
GetResource (String parh) method: path must start with/, representing the root directory of the current web application. Returns a URL object that represents a resource.
GetResoutceAsStream (String parh): returns the file stream. This advantage is that you can access all files in the web directory using the path relative to the root directory without having to know the absolute path.
GetContextPath (): Obtain the web Application Path.
GetRealPath (): Get the absolute path

3. servletcontext domain object
ServletContext is a space for storing information globally. It exists at the beginning and is released only when the server is shut down.
Request, one user can have multiple; session, one user; while servletContext, all users share one. Therefore, in order to save space and improve efficiency, it is safe to put necessary, important threads that all users need to share in ServletContext.
Request. getServletContext (). setAttribute (): sets the domain object content.
Request. getServletContext (). getAttribute (String name): obtains the content of a domain object.
Request. getServletContext (). removeAttribute (String name): deletes a domain object.

Thank you for your reading the Shanghai Java training. Please refer to the source for reprinting. Please pay more attention to the support and provide relevant Java technical articles one after another!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.