Request object and response object

Source: Internet
Author: User
Tags border color

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.

1. To obtain the data submitted by the client, you only need to find the request object.

2. to output data to the client, you only need to find the response object.

1. Response object

1.1 send data to the client in bytes (encoding method must be set before output)

String data = "Hello, China 1"; outputstream out = response. getoutputstream (); Out. Write (data. getbytes (); // find the local default encoding for encoding

String data = "Hello, China 2"; outputstream out = response. getoutputstream (); out. write (data. getbytes ("UTF-8"); // encode in UTF-8 // tell the browser encoding method response. setheader ("Content-Type", "text/html; charsets = UTF-8 ");

String data = "Hello, China 3"; outputstream out = response. getoutputstream (); out. write ("<meta http-equiv = 'content-type' content = 'text/html; charset = UTF-8 '> ". getbytes (); // use the meta tag to simulate the request header out. write (data. getbytes ("UTF-8"); // encoded in UTF-8

String data = "Hello, China 4"; outputstream out = response. getoutputstream (); response. setcontenttype ("text/html; charsets = UTF-8"); out. write (data. getbytes ("UTF-8"); // encoded in UTF-8
 

response.setContentType("text/html;charset=UTF-8");

It is equivalent to the following two codes:

Response. setcharacterencoding ("UTF-8"); // change the default encoding of data sent by the server
Response. setheader ("Content-Type", "text/html; charset = UTF-8"); // notify the client of the decoding method

Int x = 97; outputstream out = response. getoutputstream (); Out. Write (x + ""). getbytes (); // send a number to the client

1.2 send data to the client in characters

String data = "who are you? ";
Response. setcharacterencoding ("UTF-8"); // set the encoding to UTF-8
Response. setheader ("Content-Type", "text/html; charset = UTF-8"); // tell the client encoding method


// Method 2: equivalent to the above two Codes
// Response. setcontenttype ("text/html; charset = UTF-8 ");
Printwriter writer = response. getwriter (); // The default encoding is that the encoding method must be set before the iso-8859-1 creates the object

Writer. Write (data );
System. Out. println (response. getcharacterencoding ());

1.3 let the client open the file as a download to solve the Chinese file name garbled problem (urlencoder. encode (name, "UTF-8 "))

// Obtain the true file path string realpath = getservletcontext (). getrealpath ("/files/Beautiful eyebrow .jpg"); // get the file name string name = realpath. substring (realpath. lastindexof ("\"); // sets the response header to notify the client to open the file response as a download. setheader ("content-disposition", "attachment; filename =" + urlencoder. encode (name, "UTF-8"); // construct the input stream inputstream in = new fileinputstream (realpath); // output the stream outputstream out = response to the client. getoutputstream (); int Len =-1; BYT E Buf [] = new byte [1024]; while (LEN = in. Read (BUF ))! =-1) {out. Write (BUF, 0, Len);} in. Close ();

1.4 output a random number to generate a verification code Image

// Set not to cache (three methods are recommended, to prevent the browser from not supporting) response. addheader ("Pragma", "No-Cache"); response. setheader ("cache-control", "No-Cache"); response. setheader ("expires", "0"); // 1. memory image bufferedimagebufferedimage image = new bufferedimage (width, height, bufferedimage. type_int_rgb); // 2. create brush graphics G = image. getgraphics (); // 2.1 draw the border G. setcolor (color. gray); // set the border color G. drawrect (0, 0, width, height); // draw a rectangular border // 2.2 fill the border G. fillrect (1, 1, width-1, height-1); // 2.3 output verification Random Number 4 random r = new random (); G. setcolor (color. blue); int x = 5; For (INT I = 0; I <4; I ++) {G. setfont (new font ("", Font. bold, 20); G. drawstring (R. nextint (10) + "", X, 20); x + = 30;} // draw interference line G. setcolor (color. yellow); For (INT I = 0; I <9; I ++) {G. drawline (R. nextint (width), R. nextint (height), R. nextint (width), R. nextint (height);} // 3 Outputs imageimageio using the response output stream. write (image, "Jpeg", response. getoutputstream ());
// Response. setheader ("expires", (system. currenttimemillis () + 24*3600*10*1000) + ""); // cache for 10 days response. setdateheader ("expires", system. currenttimemillis () + 10*24*1000*60*60 );

1.5 control the client refresh time

// Response. setheader ("refresh", "5; url =/day05/default.html"); // jump in 5 seconds, and the URL is the jump link response. getoutputstream (). write ("<meta http-equiv = \" Refresh \ "content = \" 3; url =/day05/login.html \ "> ". getbytes ());

1.6 control the Client Cache Time

// Response. setheader ("expires", (system. currenttimemillis () + 24*3600*10*1000) + ""); // cache for 10 days response. setdateheader ("expires", system. currenttimemillis () + 10*24*1000*60*60 );

1.7 use response for request redirection

Feature: the address bar changes and two requests are sent, increasing the server load.

Implementation Method: Response. sendredirect ()
Implementation principle: 302 status code and Location header to achieve redirection

// Response. sendredirect ("/day05/servlet/responsedemo5"); // absolute path note // response. sendredirect ("/servlet/responsedemo5"); // The relative path is incorrect because the redirection is the response initiated by the client. setstatus (307); // either 302 or 307 can be response. setheader ("location", "http: // localhost: 8080/day05/servlet/responsedemo1 ");

1.8 small details

String S1 = "ABC"; string S2 = "def"; response. getoutputstream (). write (s1.getbytes (); // response. getwriter (). write (S2); // Note: The getoutputstream and getwriter methods are mutually exclusive. // after you call any of these methods, you cannot call another method, an exception is thrown. // Java. Lang. illegalstateexception: // getoutputstream () has already been called for this response

2. Request (httpservletrequest) object

2.1.get Method

String locale = request. getlocalname (); // transmission protocol string url = request. getrequesturl (). tostring (); // request URL string uri = request. getrequesturi (); // address without a host name string protocol = request. getprotocol (); // obtain the Protocol string add = request. getremoteaddr (); // Client IP string host = request. getremotehost (); // client host name string port = request. getremoteport () + ""; // client port number string method = request. getmethod (); // client request method string localadd R = request. getlocaladdr (); // obtain the server address string username = request. getparameter ("username"); // After the address? Request Parameter string SERVERPORT = request. getserverport () + ""; // server port number string servername = request. getservername (); // server name

2.2 obtain the client request header

Response. setcontenttype ("text/html; charset = UTF-8"); printwriter out = response. getwriter (); // gets the value out of a single request header. write (request. getheader ("Accept-language") + "<br/>"); // obtain multiple enumeration headers = request. getheaders ("User-Agent"); While (headers. hasmoreelements () {out. println (headers. nextelement () + "<HR/>");} // obtain all request header names enumeration names = request. getheadernames (); While (names. hasmoreelements () {// obtain the corresponding value string name = (string) names based on the request header name. nextelement (); out. println (name + "=" + request. getheader (name) + "<br/> ");}

2.3 obtain Request Parameters

String usernamevalue = request. getparameter ("username"); // null if the parameter does not exist

String Names [] = request. getparametervalues ("username"); For (string name: names) {system. out. println (name); // obtain all values of a request parameter}
// Obtain all request parameter names enumeration names = request. getparameternames (); While (names. hasmoreelements () {// obtain the value string name = (string) names based on the parameter name. nextelement (); system. out. println (name + "------->" + request. getparameter (name ));}

2.4 encapsulation to Bean

public class Student {   private String[] username;   private String password;   public String[] getUsername() {return username;}public void setUsername(String[] username) {this.username = username;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}      }
// Use beanutils and getparametermap () to encapsulate the object to beanprivate void test5 (httpservletrequest request) {// todo auto-generated method stubmap map = request. getparametermap (); student s = new student (); try {beanutils. populate (S, MAP);} catch (illegalaccessexception e) {// todo auto-generated catch blocke. printstacktrace ();} catch (invocationtargetexception e) {// todo auto-generated catch blocke. printstacktrace ();} string [] names = S. getUserName (); system. out. println (Names [0]); // aasystem. out. println (Names [1]); // bbsystem. out. println (S. getPassword (); // 123} // two usernames passed from the client (for example, AA and BB) and one password (for example, 123)

2.5 obtain the Request body

// Obtain the Request body inputstream in = request. getinputstream (); byte [] Buf = new byte [1024]; int Len =-1; while (LEN = in. read (BUF ))! =-1) {system. Out. println (new string (BUF, 0, Len ));}

2.6 solve Chinese garbled characters in Request Parameters

Get method: first obtain the original bytecode according to the original encoding, and then re-encoding. For example: Name = new string (name. getbytes ("ISO-8859-1"), "UTF-8 ");

Post mode: Specifies the encoding of the client and the encoding of the request data sent. The server is notified of the encoding method based on the client encoding.

For example: request. setcharacterencoding ("UTF-8"); // only applicable to POST request methods

2.7 forward requests

Requestdispatcher RD = request. getrequestdispatcher ("path"); // obtain the forwarder. The path can be a relative or absolute path (because it was initiated by the server)
Rd. Forward (request, response );

2.8 include

Requestdispatcher RD = request. getrequestdispatcher ("/servlet/requestdemo9 ");
Rd. Include (request, response );

3. Path writing:
A. absolute path Syntax: serveltcontext must all use absolute paths. "/" (For example, servletcontext. getrequestdispatcher ("path") path must be an absolute path)
B. Relative Path: You can use relative paths or absolute paths in other cases.

C. When using an absolute path, do you need to add "/" or a project name? If the server calls the path, do not add a project name, "/" indicates the root directory of the current application.
If it is called by the client, the project name must be added.

1. forwarding: request. getrequestdispather (string URL)
Absolute path: URL/servlet/servletdemo
2. Redirection: Response. sendredirect (string URL)
Absolute path: URL/day05/servlet/servletdemo

3. hyperlink: <a href = "url"/>
Absolute path: URL/day05/servlet/servletdemo
4. Path of the Class-Loaded File
Only relative paths can be used in Web applications.
5. <fomr action = "url"/>
Absolute path:/day05/servlet/servletdemo
6. Frame)
Absolute path:/day05/servlet/servletdemo
7. servletcontext. getrealpath (URL)
Absolute path: URL/servlet/servletdemo

Urlencoder. encode ("name", "UTF-8") // fix Chinese garbled characters in the file download name

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.