20160314 Request and response

Source: Internet
Author: User

First, Response
1.Resonse Inheritance structure:
The 2.Response represents the response, so the status code, the response header, and the entity content in the response message can be manipulated by it, thereby projecting the following experiment:
3. Using response to output data to the client
Response.getoutputstream (). Write ("Chinese". GetBytes ()) output data, which is a byte stream, what bytes are output, and the browser defaults to open the data sent by the server with platform bytecode, If the server side uses non-platform code to output character byte data, you need to explicitly specify the browser encoding when the code table used to prevent garbled problems. Response.AddHeader ("Content-type", "text/html;charset=gb2312")
Response.getwriter (). Write ("Chinese"), output data, which is a stream of characters, response will output this character to the browser after transcoding, this process by default uses the Iso8859-1 code table, and Iso8859-1 is not Chinese, So in the process of transcoding to replace the Chinese, resulting in garbled problems. You can specify the target code table used by response during transcoding to prevent garbled characters. Response.setcharcterencoding ("gb2312");
In fact response also provides the setContentType ("text/html;charset=gb2312") method, this method will set the Content-type response header, notify the browser to open the Code table, while setting the Response transcoding code table , so that a line of code to solve garbled.
4. Using response to set content-disposition header for file download
Set the response header content-disposition to "Attachment;filename=xxx.xxx"
Use the stream to read the file in, and then use response to get the response stream output
If the file name is in, must be URL encoding, encoding the code table used must be utf-8
5.refresh Head Control Timing Refresh
Sets the response header refresh to a numeric value, specifying how many seconds after the current page is refreshed
Set the response header refresh to 3;url=/day05/index.jsp, specify how many seconds to refresh to which page
Can be used to implement the registration "successful registration, 3 seconds after the jump to the home" function
In HTML you can use <meta http-equiv= "" content= "" > tag to simulate the function of the response header.
6. Use response to set expires, Cache-control, pragma to realize whether the browser cache resources, these three headers can be implemented, but due to historical reasons, different browser implementations, so generally with these three headers use
6.1 Control browser do not cache (Captcha picture not cached) set expires to 0 or-1 set Cache-control to No-cache, pragma to No-cache
6.2 Control Browser Cache resources. Resources are cached even if the browser is not explicitly specified, and the cache does not have a deadline. The cache is used when the address is re-entered in the Address bar, but the resource is re-accessed when the browser is refreshed or re-opened.
If you explicitly specify the cache time, the browser cache is, there will be a deadline, until the expiration date, when the address bar re-enter the address or re-open browser access will be used in the cache, and when the refresh will regain resources.
7.Response Implementing Request Redirection
7.1 Ancient Methods: Response.setstatus (302), Response.AddHeader ("Location", "URL");
7.2 Shortcut: Response.sendredirect ("URL");
*8. Output Verification Code picture

9.Response Note content:
9.1 For a single request, Response's Getoutputstream method and Getwriter method are mutually exclusive and can only be called one, paying special attention to forward and not violating this rule.
9.2 When using response output data, not directly to the browser, but write to the response buffer, wait until the entire service method is returned, the server takes out the information in the response to form an HTTP response message returned to the browser.
After the 9.3service method returns, the server will check itself response get OutputStream or writer is closed, if not closed, the server automatically help you shut down, generally do not shut down the two streams themselves.

Second, request:request represents the Request object, which encapsulates the request to have the request line, the request header, the entity content the method of operation
1. Obtaining Client Information
The Getrequesturl method returns the client to make a request for the full URL
The Getrequesturi method returns the resource name portion of the request row, which is commonly used in permission control
The GetQueryString method returns the parameters section in the request line
The Getremoteaddr method returns the IP address of the client that made the request
GetMethod How to get the client request
Getcontextpath get the current Web App virtual directory name, especially important!!! , all the paths in the project should not be written dead, in which the Web application name is to be obtained in this way.

2. Get Request header information
The GetHeader (name) method---String that gets the value of the request header for the specified name
The Getheaders (String name) method---enumeration<string>, gets a collection of the value of the request header for the specified name, because multiple request headers with duplicate names may appear
Getheadernames Method---enumeration<string>, gets a collection of all request header names
The Getintheader (name) method---int to get the value of the request header of type int
The Getdateheader (name) method---Long (the date corresponds to milliseconds), gets the value of a date-type request header, returns a Long value, and a millisecond value starting January 1, 1970 0 O'Clock

* Experiment: Through Referer information anti-theft chain
String ref = Request.getheader ("Referer");
if (ref = = NULL | | ref = = "" | |! Ref.startswith ("http://localhost")) {
Response.sendredirect (Request.getcontextpath () + "/homepage.html");
} else {
This.getservletcontext (). Getrequestdispatcher ("/web-inf/fengjie.html"). Forward (request, response);
3. Get Request Parameters
GetParameter (name)---String to get the value by name
Getparametervalues (name)---string[] get a multivalued checkbox by name
Getparameternames---enumeration<string> gets an enumeration of all request parameter names
Getparametermap---map<string,string[]> gets the Map collection of all request parameters, note that the key is String and the value is string[]

Garbled problem when getting request parameters:
What encoding is used for request parameters sent by the browser? What encoding is used when the browser opens the Web page, and what code is used to send it.
Server-side get to send the request parameter by default use Iso8859-1 to decode operation, Chinese must have garbled problem
For data submitted by post, you can set request.setcharacterencoding ("gb2312") to explicitly specify the encoding to use when getting the request parameters. However, this method is only valid for Post mode submission.
For data submitted in get mode, it is only possible to manually resolve garbled characters: string newName = new String (Name.getbytes ("iso8859-1"), "gb2312"), and this method is also valid for post mode.
In Tomcat's server.xml, you can configure the HTTP connector's uriencoding to specify the encoding that the server uses by default when it obtains the request parameters, so that it can once and for all deny the problem of getting the request parameters garbled. You can also specify the Usebodyencodingforuri parameter, so that request.setcharacterencoding also works with requests for get methods, but neither of these properties is recommended because the publishing environment often does not allow this property to be modified.

4. Passing objects using the request domain
Lifecycle: Created by the server before the service method call, passing in the service method. The entire request is over, requesting the end of life.
Scope of action: the entire request chain.
Function: Share data throughout the request chain, most commonly: data processed in the servlet is given to the JSP display, where parameters can be placed in the request domain with the past.

5.request Implementing Request Forwarding
ServletContext can implement request forwarding, and requests can be.
Data entered into the response buffer before forward, if it has been sent to the client, forward will fail, throw an exception
The data entered into the response buffer before forward, but not yet sent to the client, forward can execute, but the buffer will be emptied before the data is lost. Note The missing is only the content in the request body, the header content is still valid.
It is not possible to do multiple forward in a servlet, because the first forward is over, response has been submitted, no chance of forward
In short, one principle, one request can only have one response, after the response is submitted, there is no chance to output the data to the browser.

6.RequestDispatcher for include operations
Forward there is no way to make the output of multiple servlets a single output, so RequestDispatcher provides an include method that allows the output of multiple servlets to be made into one output to return a browser
Request.getrequestdispatcher ("/servlet/demo17servlet"). Include (request, response);
Response.getwriter (). Write ("from Demo16");
Request.getrequestdispatcher ("/servlet/demo18servlet"). Include (request, response);
It is common to write a single file in a fixed part of a page, and include in multiple pages to simplify the amount of code.

Iv. URL Encoding
1. Because the HTTP protocol specifies that only characters in the ASCII code exist in the URL path, URL encoding is required if there are Chinese or special characters in the URL.
2. Coding principle:
Convert a space to a plus sign (+)
The characters between 0-9,a-z,a-z remain the same
For all other characters, the current character set of this character is encoded in the hexadecimal format in memory, and a percent semicolon (%) is added before each byte. If the character "+" is represented by%2B, the character "=" is denoted by%3d, the character "&" is represented by%26, each Chinese character occupies two bytes in memory, the characters "in" is denoted by%d6%d0, and the character "state" uses the%B9%FA to denote that the space can also be directly used with its hexadecimal encoding. %20 means instead of converting it to a plus sign (+)
If you are sure that the special characters of the URL string do not cause ambiguity or conflict in use, you can also pass these characters to the server instead of encoding them. For example, http://www.it315.org/dealregister.html?name= China &password=123
If special characters in the URL string may be ambiguous or conflicting, these special characters must be URL-encoded. For example, the server treats non-encoded "medium +" as "China". Also for example, if the name parameter value is "&", the URL string will have the following form if the "&" is not encoded in it: Http://www.it315.org/dealregister.html?name= & Country & Password=123, should be encoded as: Http://www.it315.org/dealregister.html?name= in%26 country &password=123
Http://www.it315.org/example/index.html#section2 can be rewritten as Http://www.it315.org/example%2Findex.html%23section2
3. URL encoding and decoding in Java
Urlencoder.encode ("xxxx", "utf-8");
Urldecoder.decode (str, "utf-8");

V. Differences in Request redirection and request forwarding
1. Differences
The Requestdispatcher.forward method can only forward requests to components in the same web app, while the Httpservletresponse.sendredirect method also redirects to resources in other applications at the same site. Even resources that are redirected to other sites using an absolute URL.
If the relative URL passed to the Httpservletresponse.sendredirect method begins with "/", it is relative to the root of the server, and if the relative URL specified when the RequestDispatcher object is created starts with "/", It is relative to the root directory of the current Web application.
After the access process that calls the Httpservletresponse.sendredirect method redirects, the URL displayed in the browser's address bar changes, and the initial URL address becomes the target URL of the redirect; Call Requestdispatcher.forward The browser address bar keeps the initial URL address intact after the request-forwarding process for the method is completed.
The Httpservletresponse.sendredirect method responds directly to the request of the browser, and the result of the response is to tell the browser to re-issue the access request to the other URL, and the Requestdispatcher.forward method forwards the request to another server-side A resource, the browser only knows that a request has been made and has received a response, and does not know that a forwarding behavior has occurred inside the server program.
The caller of the Requestdispatcher.forward method shares the same request object and the response object as the callee, which belong to the same access request and response process, while the Httpservletresponse.sendredirect method caller and the The caller uses the respective request object and the response object, which belong to two separate access request and response procedures.
2. Application scenario (refer to diagram)
Always use request forwarding to reduce server pressure
Redirect with request when the address bar needs to be updated, such as jumping to the home page after successful registration.
When you need to refresh the update operation, use a request redirection, such as a shopping cart payment operation.

20160314 Request and response

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.