Request and responseauthor: lxy
1. Understand request and Response Request: request object response: the response Object Request and response object are created by the server. Each request creates a new request response object. The response ends and the object disappears automatically. Purpose: request can process all HTTP requests. ---- get http request information. response can process all HTTP responses. ---- set HTTP response information to supplement: the Request Message consists of the request line, request header, and request content.
2. request and response system Introduction |-servletrequest interface |-httpservletrequest interface |-requestfacade (implemented by the server) |-servletresponse interface |-httpservletresponse interface |-responsefacade (implemented by the server) supplement: facade design mode (used in the server) ----- This is a unified definition of external methods. The specific internal code snippet for implementing the method: Public requestfacade (request) {This. request = request}
3. response object [1]. the response object is the [2] received in the service method. response operation response information: row --- response. setstatus (INT index); // The status dock of the response status line --- setheader setdateheader setintheader body-getoutputstream ()-getwriter ()
4. example 4-1. using response to implement redirection, you can access resources inside and outside the Site Server: Status Code (302) Response Header (location) code snippet: response. setstatus (302); // set the status code to 302 response. sethesder ("location", "/day8_4/myweb.html"); // set the value of the Response Header location. The redirection completed in actual application development is response. sendredirect ("/day8_4/myweb.html"); // This is equivalent to directly calling the encapsulation method 4-2 on the server. send the HTTP header to control the browser's timed jump to response. setheader ("refresh", "5; url =/day8_4/myweb.html"); // the browser accesses the specified address after the specified time, this operation is rarely performed on the server. Generally, code snippets are completed on the browser: <meta http-equiv = "refresh" content = "5; url = http: // www.192.168.1.25: 8080/day8_4/myweb.html "> Extension: display on the Browser Side" -- jump in seconds... <SCRIPT type = "text/JavaScript"> var time = 5; funcation change () {var span = document. getelementbyid ("S"); span. innerhtml = time; Time --; setTimeout ("Change ()", 1000) ;}</SCRIPT> <body onload = "Change (); "> the page will jump to... </body> response header-Server Resolution response body-browser resolution 4-3. by sending an HTTP header, you can control the browser to prohibit caching in multiple ways. Different browsers may adopt different settings and can be used at the same time to achieve response effect on all browsers. setheader ("Pragma", "No-Cache"); response. setheader ("cache-control", "No-Cache"); response. setdateheader ("expires",-1); // sets the effective time. The number is a long integer that represents the time.
5. to operate the response body in the servlet, You need to obtain the output stream through the response object for the operation. getwriter (); ----- servletoutputstreamresponse. getoutputstreaam (); ---- two features of the printwriter print stream: You can set Automatic refresh to output the information as it is. If you want to customize the operation information, use the render stream servlet to get the output stream in use. Note: at the same time, you can only select either a response stream or a byte stream, which is mutually exclusive. You can disable it, and the server can close the servlet to display the operation code snippet: response. setheaader ("Content-Type", "text/html; charset = UTF-8"); out. println ("<form action =" # "method = 'post'>"); Response Information garbled response. setcharacterencoding (string Code); // sets the response body encoding response. setcontenttype (string mimetype); // sets the response body encoding and tells the browser how to parse response. setheader ("Content-Type", "text/html; charset = UTF-8 ");
6. the verification code can prevent malicious registration. It is an image supplement: When the browser cache contains information on the current page, it will be cached when accessed again. In order to prevent the browser from caching, obtain the new page information and add the following code snippet Function Change () {document. getelementbyid ("im "). src = "/day8_4/imagecode? Time = "+ new date (). gettime (); // Add the current time after the original address}
7. request object: used to obtain HTTP request information about post and get requests 1. the post request can submit big data get and can only submit 1kb2. the post request information is not displayed in the browser (secure). The GET request information is displayed in the browser (Insecure). 3. POST Request Parameters GET request information in the Request body in the resource path [1] request line operation request. getmethod (); // obtain the Request Method Request. getprotocol (); // obtain the request protocol such as http: // 1.1request.getrequesturi (); // return urirequest. getrequesturl (); // The returned url uri contains the URL [2]. obtain client information request. getremotaddr (); // obtain the Client IP address request. getlocationaddress (); // get the server iprequest. getcontentpath (); // obtain the virtual directory name (project name -- not necessarily the project name) to obtain the resource path: URI address-virtual directory name [3]. GET request header information string getheader (string name); // get a request header information enumeration getheaders (); // get the information of multiple request headers getdateheader (); getintheader (); [4]. obtain the request parameter [++] string getparameter (string name); string [] getparametervalues (string name); // checkbox getparameternames (); // obtain all the Map Name values in the form <; string, string []> getparametermap (); // use the parameter name as the key, the input or selected value as value is a string []
8. processing after obtaining Request Parameters [1]. after obtaining the parameters on the server side, the server verifies the parameters through Java code-fly-empty verification and rule validation string. trim (). length ()> 0; [2]. garbled processing garbled reason: the encoding value of Chinese Characters in each encoding table is not the same when the program runs the page UTF-8, Tomcat server uses iso8859-1 decoding, Servlet obtained is garbled information page Encoding Server decoding inconsistent, solution: encode the obtained information with a iso8859-1 and then use UTF-8 to decode the snippet: mag. getbytes ("ios8859-1"); new string (Mag. getbytes ("iso8859-1"), "UTF-8"); sample code: Page string S = "Zhang San"; string code = urlencoder. encode (S, "UTF-8"); // s --> utf-8tomcat Server String MSG = urldeco Der. decode (Code, "iso8859-1"); simulate solution -- reverse back string c = urlencoder. encode (MSG, "iso8859-1"); string M = urldecoder. decode (C, "UTF-8"); or directly decode string username = request in the string class. getparameter ("username"); usernamae = new string (username. getbytes ("iso8859-1"), "UTF-8"); Request in the post request. Setcharacterencoding (string charsetname );
9. request domain object [1]. lifecycle: the lifecycle is created when a request is sent, and the request is destroyed when the response ends [2]. as long as it is a domain object, you can perform the following operations: setattribute () getattribute () removeattrespon() [3]. request forwarding; Code: requestdispatcher RD = request. getrequestdispatcher ("/second"); Re. forward (request, response); Application: Recipient string username = request. getparameter ("username"); string passw = request. getparameter ("passw"); If ("Tom ". equals (username. trim () & "123 ". equals (passw. trim () {request. setattribue ("loginmessage", "Logon successful");} else {request. setattribue ("loginmessage", "Logon Failed");} // request forwarding requestdispatcher RD = request. getrequestdispatcher ("/second"); Rd. forward (request, response); handler respons. setcontenttype ("text/html; charset = UTF-8"); string message = (string) request. getattribute ("loginmessage"); response. getwriter (). write (Message); after forward or rendredirect is executed, the server will clear the buffer and perform buffer-related operations.
10. difference between request forwarding and redirection [1]. the request is forwarded to the server. Only one request is redirected once. Two requests are redirected twice. [2] ...... internal operation, will not affect the address bar path redirection address bar changes [3] ...... redirection can only be redirected to the current site. You can jump out of the Site [4] ...... request initiated by request. getrequestdispatcher (""). forward (...,...); redirect response. sendredirect (); [5] ...... "/" indicates the current project, server path redirection "/" indicates the root directory of the server, and client path [6] ...... whether data sharing is required if the request domain exists and the request domain does not exist.
Tc608 -- Request and Response Request Response Technology in Servlet