Java Web Daily Learn the servlet working principle detail analysis

Source: Internet
Author: User

上篇文章中我们介绍了Servlet的实现方式以及Servlet的生命周期,我们这篇文章就来介绍一下常用对象。

Click to review: "Java Web every day to learn the work of the servlet of the principle of analysis"; "Java Web learning of the servlet of the working principle of the Analysis (ii)"

First, HttpServletRequest object

1. Introduction
HttpServletRequest object: The main function is to receive the client sends the request information, for example: the request parameter, sends the header information and so on all belongs to the client sends the information, the service () The parameter in the method receives the instantiated object of the HttpServletRequest interface, indicating that the object is primarily applied to the HTTP protocol, which is passed by the Tomcat package.

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

In the long run: The main protocol now is the HTTP protocol, but more new protocols may appear later. If you want to support this new protocol in the future, simply inherit the ServletRequest interface directly.

In the HttpServletRequest interface, there are many methods defined, but all around receiving client parameters.
But how do we get the object? Not required, directly in the service method by the container passed in, and what we need to do is to take out the data in the object, for analysis, processing.

2, the common method
Request Mode +url+ version number
Getrequesturl: Returns the full URL when the client makes a request
Getrequesturi: Returns the resource name portion of the request line (project name start)
GetQueryString: Returns the parameters section in the request row
GetMethod: Get client request mode
Getprotocol: Get the HTTP version number
Getcontextpath: Get WebApp Name

Get client Several message headers
GetHeader (String name): Gets the contents of a single request header
Enumeration<string> getheadernames (): Gets all the request header name collections

Get client request parameters (client-submitted data)
GetParameter (name): Gets the parameter value of the specified name, which is one of the most common methods.
Getparametervalues (String name): Gets an array of all values for the specified name parameter. It applies when a parameter name corresponds to multiple values: such as a check box in a page form, the value of a multiple-selection list submission.

Getparameternames (): Returns a enumeration object that contains all the parameter names in the request message. By traversing the enumeration object, you can get all the parameter names in the request message.

Getparametermap (): Returns a Map object that holds all the 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 an array of values for the object type corresponding to this parameter

3. Request garbled Solution
Because now the request belongs to the receiving client's parameters, so it must have its default language encoding, mainly because the default encoding method used in the parsing process is iso-8859-1 (this encoding does not support Chinese), so parsing must be garbled. To solve this garbled problem, you need to set the encoding in the request and 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 garbled after TOMCAT8
Tomcat8 and above Get will not garbled, no tube

4. Jump
Request.getrequestdispacther ("Address to Jump"). ForWord (Request,response);
Request forwarding, server jump, Address bar URL unchanged.

When the path is written, either the start or the http:///is the absolute path, and does not start with a relative path, and when the request is forwarded, "/" represents the server path + site name, that is, http://localhost:8080/station names

The process of requesting forwarding:
The client first sends a request to the server side, the server side discovers the matching servlet, and specifies that it executes, and when the servlet executes, it calls the Getrequestdispacther () method, forwards the request to the specified test.jsp, The whole process is done on the server side, and it is done in the same request, so the servlet and JSP are sharing the same requests, everything in the servlet can be taken out in the JSP, so the JSP can getattribute the result () Out, GetAttribute () comes out and executes the result back to the client. The whole process is a request, a response.

5. Request Domain Object
The object can pass data in a request, scoped: Valid in a single request, that is, the server jump is valid.
Request.setattribute (): Set request domain object contents
Request.getattribute (String name): Gets the contents of the specified request domain object
Request.removeattribute (String name): Deletes the specified request domain object

Second, HttpServletResponse object

1. Introduction
The Web server receives the client's HTTP request, creating a Request object for each request and a response object representing the response, respectively.

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

The primary function of the httpservletresponse is for the server to respond to client requests and return the results of the Web server processing to the client. The parameter in the service () method receives the instantiated object of the HttpServletResponse interface, which encapsulates the method of sending data to the client, sending a response header, and sending a response status code.

2. Common methods
Addcookie (Cookie cookie): 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 that determines whether the head of the response is set
Encodeurl (String URL): Encodes the specified URL
Senderror (int SC): Sends an error to the client using the specified status code
Sendredirect (String location): sends a temporary response to the client, redirects
SetHeader (String name,string value): Sets the given name and value to the head of the response
SetStatus (int SC): Sets the state for the current response
setContentType (String ContentType): Sets the MIME type of the response
Getwriter (): Gets the output character stream
Getoutputstream (): Gets the output byte stream

3, set the header information
1), Refresh, jump page
All header information is automatically sent to the server side (client) as the request and response, in response a more commonly used header information is the refresh instructions, you can complete the function of timed refresh.
Resp.setheader ("Refresh", "2");

For the refreshed header information, in addition to the timing of the function, but also has a timed jump function, you can have a page timed to jump to a specified page. (Has been registered successfully, two seconds later to jump to the landing page)
Response.setheader ("Refresh", "3; Url=ok.html ");

But this jump is not omnipotent, and sometimes can not jump operation, return after the refresh will not jump;
For this timing jump header information can also be set in HTML, HTML itself can also set the header information. (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 that the servlet returns to the client, which is used to set the state without errors and is not normally used. If the servlet runs incorrectly, the servlet can use the Senderror method to set the status code, such as the senderror (int sc) method, to set the error status codes. The senderror (int sc,string msg) method also sends an error message to the customer in addition to setting the status code.
3), add cookies
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 session state.
4. Jump
Response.sendredirect ("Path to jump");
Through response can also jump, this kind of jump called request redirect, belong to the client jump, address bar change, there are two requests. The parameters in the request cannot be passed between this type of jump.
When the path is written, either the start or the http:///is the absolute path, and does not start with a relative path, and when redirected, "/" represents the server path, i.e. http://localhost:8080

5. REDIRECT process:
The client browser sends an HTTP request---The >web server accepts a 302 status code response and corresponds to the new location to the client browser--the browser discovers a 302 response, automatically sending a new HTTP request, The requested URL is the new location address-the server looks for resources and sends them to the customer based on this request.

6, Response garbled solution
When the server side responds to the client Chinese, there may be garbled
Two ways of responding back to data: PrintWriter and Servletoutputstream
The two methods of Getoutputstream and getwriter are mutually exclusive, and any one of them is called, and no other method can be called.
PrintWriter (): Must be garbled, the server automatically uses ISO-8859-1 encoding, the following way to solve garbled
Response.setcharacterencoding ("Utf-8");
Response.setheader ("Content-type", "text/html;charset=utf-8");
A sentence to the top two sentences:
Response.setcontenttype ("Text/html;charset=utf-8");
OutputStream (): May be garbled

7, the use of OutputStream flow output Chinese Note:
Server-side, the data output encoding method, is the client open encoding method
Example: Outputstream.write ("China"), GetBytes ("Utf-8"), using OutputStream to output Chinese to the browser, encoding is utf-8; The client browser is also opened with Utf-8 encoding. Otherwise there will be garbled characters in Chinese. The server-side control client browser is displayed in Utf-8 encoding, which can either be resolved printwriter or by setting the response header information as follows:
Response.setheader ("Content-type", "text/html;charset=utf-8");

Third, HttpSession object
1. Introduction
The HttpSession object is an instance of javax.servlet.http.HttpSession, which does not have a parent interface like HttpServletRequest or HttpServletResponse, which is simply a purely interface. Because the session belongs to the HTTP protocol category.

For a server, each client connected to it is a session,servlet container that uses this interface to create a session between the HTTP client and the HTTP server. The session retains the specified time period, across multiple connections or page requests from the user. A session usually corresponds to a user who may visit a site multiple times. This interface allows you to view and manipulate 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 operation of the property
The session can be obtained either on the client or server side, and if you reopen a new browser, you cannot get the previously set session because each session is only saved in the current browser and is made on the relevant page.

1. function
Common methods
SetAttribute (String name,object value): Binds the value object to the session by name
GetAttribute (String name): Gets the property value of name and returns NULL if the property does not exist
RemoveAttribute (String name): Removes the name attribute from the session and does not throw an error if it does not exist.
Enumeration Getattributenames (): Returns the enumeration value associated with the session
Invalidate (): Invalidates the session while deleting the Property object
IsNew (): Used to detect whether the current customer is a new session
Long GetCreationTime (): Returns the session creation time
Getlastaccessedtime (): Returns the last request time of the Web container received by the client during the session time
int Getmaxinactiveinterval (): Returns the maximum time a customer request is in seconds during a session
Setmaxinactiveinterval (int seconds): Maximum time allowed for customer requests
ServletContext getservletcontext (): Returns the context of the current session, ServletContext object enables the servlet to communicate with the Web container
String getId (): Returns the identification number during the session

Session: Default is created when the session is first used
Cookies: Most are set to the browser by the server Active (program manual), only Jsessionid is set by the service itself, do not need the programmer to worry about
Session ID

For each user, the fact is that a different session, the server through the session ID to differentiate these users, that is, every user connected to the server through the browser will be assigned by the server a unique no duplicate number.
The value of the Jsessionid automatically set by the cookie is the session ID of each user, so the session uses the cookie processing mechanism when doing the operation.

End of Session ID
① life cycle Expiration (default browser open and close)
② Shutdown Server Session destruction
Gracefully shuts down the server, the session object will not be destroyed, but will be serialized to disk
Working space work directory under Session.ser
③ Call Session invalidate () method
Session in all project development, the most used place is the login verification and logout operation function
3. Session Field Object
A session creates a HttpSession object that can be shared across multiple requests in the same session
To enjoy the data in session.
Request.getsession (). SetAttribute (): Set Session Field object contents
Request.getsession (). getattribute (String name): Gets the contents of the specified Session Field object
Request.getsession (). RemoveAttribute (String name): Delete the specified session Field object

Iv. ServletContext Objects
1. Introduction
A web app has only one ServletContext object, and all Servlets share the ServletContext object, also known as the Application object. When the Web container starts, a corresponding ServletContext object is created for each Web application that represents the current web app. ServletContext defines a set of methods that the servlet uses to communicate with other servlet containers, ServletContext objects are contained in ServletConfig objects, ServletConfig objects are initialized Servlet is provided by the Web server to the servlet.

2. Common methods
Getinitparameter (String name): Get initialization parameters
GetResource (String Parh) method: Where path must be/begins, representing the root directory of the current Web application. Returns a URL object that represents a resource that is returned.
Getresoutceasstream (String Parh): Returns the file stream. The advantage is that you can access all files in the Web directory using a path relative to the root directory, without having to know the absolute path.
Getcontextpath (): Get the path to the web App
Getrealpath (): Get absolute path

3. ServletContext domain Object
ServletContext is a global space for storing information, the server is in existence, and the server shuts down before it is released.
Request, one user can have multiple; session, one user; ServletContext, all users share one. Therefore, in order to save space and improve efficiency, in servletcontext, it is necessary to put the required, important, all users need to share the thread is a security of some information.
Request.getservletcontext (). SetAttribute (): Set domain object contents
Request.getservletcontext (). getattribute (String name): Gets the contents of the domain object
Request.getservletcontext (). RemoveAttribute (String name): Delete domain object

Shanghai Java Training Thank you for your reading, reprint please indicate the source, please pay more attention to support, Java related Technical articles in succession!

Java Web Daily Learn the servlet working principle detail analysis

Related Article

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.