Request objects and Response objects

Source: Internet
Author: User
Tags border color

The Web server receives the HTTP request from the client and creates a response object for each request that represents the requested request object and represents the response.

1. To get the data submitted by the client, just need to find the request object on the line.

2, to the client output data, just need to find response object on the line.


One, Response object

1.1 Send data to the client, in bytes (be sure to set the encoding first, then output)

[Java] view plain copy print?   String data = "Hello, China 1";   OutputStream out = Response.getoutputstream (); Out.write (Data.getbytes ());//Find native default encoding for encoding

        String data = "Hello, China 1";
        OutputStream out = Response.getoutputstream ();
        Out.write (Data.getbytes ());//Find native default encoding for encoding

[Java]View Plain copy print?   String data = "Hello, China 2";   OutputStream out = Response.getoutputstream (); Out.write (Data.getbytes ("UTF-8"))//UTF-8 encoding//telling the browser how to encode Response.setheader ("Content-type", "text/html;charset= UTF-8 ");
           String data = "Hello, China 2";
        OutputStream out = Response.getoutputstream ();
        Out.write (Data.getbytes ("UTF-8"))//UTF-8 encoding
        //telling the browser how to encode
        response.setheader ("Content-type", "text/ Html;charset=utf-8 ");

[Java]View Plain copy print?   String data = "Hello, China 3";   OutputStream out = Response.getoutputstream (); Out.write ("<meta http-equiv= ' content-type ' content= ' Text/html;charset=utf-8 ' >". getBytes ());//// Use meta tag to simulate request header Out.write (data.getbytes ("UTF-8"));//To encode 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 meta tag to simulate request header
        Out.write (data.getbytes ("UTF-8"));//To encode UTF-8

[Java]View Plain copy print?       String data = "Hello, China 4";       OutputStream out = Response.getoutputstream ();       Response.setcontenttype ("Text/html;charset=utf-8"); Out.write (Data.getbytes ("UTF-8"))//encoded in UTF-8
      String data = "Hello, China 4";
        OutputStream out = Response.getoutputstream ();
        Response.setcontenttype ("Text/html;charset=utf-8");
        Out.write (Data.getbytes ("UTF-8"))//encoded in UTF-8
[Java]View Plain copy print?

[Java] view plain copy print? Response.setcontenttype ("Text/html;charset=utf-8");

Response.setcontenttype ("Text/html;charset=utf-8");

The effect is equivalent to the following two lines of code:

Response.setcharacterencoding ("UTF-8")//change the default encoding of the server to send data
Response.setheader ("Content-type", "Text/html;charset=utf-8"), or notify the client of the decoding method

[Java] view plain copy print?   int x=97;   OutputStream out = Response.getoutputstream (); Out.write ((x+ ""). GetBytes ());////send a number to the client

       int x=97;
          OutputStream out = Response.getoutputstream ();
          Out.write ((x+ ""). GetBytes ());////send a number to the client
1.2 Sending data to the client in character units

String data = "Who Are you?" ”;
Response.setcharacterencoding ("UTF-8"); Set Encoding to UTF-8
Response.setheader ("Content-type", "text/html;charset=utf-8");//Tell the client how to encode


The second method: the equivalent of the above two lines of code
Response.setcontenttype ("Text/html;charset=utf-8");
PrintWriter writer = Response.getwriter ();//default encoding is iso-8859-1 you must set the encoding before you create the object

Writer.write (data);
System.out.println (Response.getcharacterencoding ());

1.3 Let the client to open the file to solve the Chinese file name garbled problem (Urlencoder.encode (name, "UTF-8"))

[Java] View Plain copy print? Get the true path of the file    String realpath = getservletcontext (). Getrealpath ("/files/beautiful girl. jpg");   //Get filename    string name = realpath.substring (realpath.lastindexof ("\"));      //Set the response header to notify the client of the way the file is downloaded    response.setheader ("Content-disposition", ) Attachment;filename= "+urlencoder.encode (name, " UTF-8 ");     //Build input stream        inputstream in = new fileinputstream (Realpath);             //output to the client stream       OutputStream out =  Response.getoutputstream ();      int len = -1;       byte buf[] = new byte[1024];      while (Len=in.read (BUF))!= -1)       {       out.write (buf, 0,&nbSp;len);      }            in.close ();   

       Get the real path of the file
        String Realpath = Getservletcontext (). Getrealpath ("/files/beautiful girl. jpg");
        Gets the filename
        String name = realpath.substring (Realpath.lastindexof ("\"));

        Sets the response header to notify the client to open the file
        response.setheader ("Content-disposition", "Attachment;filename=" +urlencoder.encode ( Name, "UTF-8"));

        Construct input stream
        inputstream in = new FileInputStream (realpath);

        Output to the client stream
        outputstream out = Response.getoutputstream ();
        int len =-1;
        byte buf[] = new byte[1024];
        while ((Len=in.read (BUF))!=-1)
        {
            out.write (buf, 0, Len);
        }

        In.close ();

1.4 Output Random number generation verification code picture

[Java] View Plain copy print?         //settings do not cache (3 methods, recommended three are set to prevent browser does not support)             response.addheader ("Pragma",  "No-cache");             response.setheader ("Cache-control",  "No-cache");            response.setheader ("Expires",  "0");               &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;//1. Memory image  BufferedImage           bufferedimage image =  new bufferedimage (WIDTH,HEIGHT,BUFFEREDIMAGE.TYPE_INT_RGB);                       //2. Creating brushes             graphics g = image.getgraphics ();                      // 2.1 Draw Border            g.setcolor (Color.gray);//Set Border color            g.drawrect (0, 0, width, height)//Draw rectangular border             //2.2 filled 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&NBSP;I=0;I&Lt;4;i++)            {                            G.setfont (New font ("Arial", font.bold,20));                g.drawstring (R.nextint) + "",  x, 20);                x+=30;           }                        //2.4 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  using response output stream output image           imageio.write (image, "JPEG", Response.getoutputstream ()); <pre  name= "Code"  class= "Java" >       //response.setheader ("Expires ",  (System.currenttimemillis () +24*3600*10*1000) +" ");/cache 10 days             response.setdateheader ("Expires", System.currenttimemillis () +10*24*1000*60*60);</pre> <br>   <pre></pre>   <p></p>   <pre></pre >   1.5&nbsp. Control client Refresh Time    <p></p>   <p></p>   <pre name= " Code " class=" Java >       //response.setheader ("Refresh",  "5; Url=/day05/default.html ");//5 Seconds after jump, url is jump link              Response.getoutputstream (). Write ("<meta http-equiv=\" refresh\ " content=\" 3; Url=/day05/login.html\ ">". GetBytes ());</pre>1.6  Control client cache time    <p></p>    <p></p>   <pre name= "code"  class= "Java" >       //response.setheader ("Expires",  (System.currenttimemillis () +24*3600*10*1000) + "");/cache 10 days            response.setdateheader ("Expires", System.currenttimemillis () +10*24*1000*60*60);</pre><br>   1.7  Use response to implement request redirection     <p></p>   <p></p>   <p> Features: The address bar will change, send two requests to increase the server burden. </p>   <p> Implementation: Response.sendredirect () <br>   Implementation principle: 302 status Code and location header can be achieved redirect <br>   </p>   <pre name= "code"  class= "Java" >            //response.sendredirect ("/day05/servlet/responsedemo5");//absolute path      Note       // response.sendredirect ("/servlet/responsedemo5" //relative path is wrong here, because redirection is initiated by the client               Response.setstatus (307);//302  or  307 can               response.setheader ("Location",  "Http://localhost:8080/day05/servlet/ResponseDemo1"); </pre ><br>   1.8  Small details    <p></p>   <p></p>   <pre name= "code"  class= "Java" >           String  s1 =  "abc";              String  s2 =  "def";              response.getoutputstream (). Write (S1.getbytes ());              //response.getwriter ()-Write (S2);              //Note: Both Getoutputstream and getwriter are mutually exclusive,              //call any one of these methods, you cannot call another method, throwing an exception.              //java.lang.illegalstateexception:               //getoutputstream ()  has  already been called for this response</pre><br>   <p><br>   </p>   <p> II, Request (HttpServletRequest) Object </p>   <p>2.1.get method </p>   <p></p> <pre name= "Code"  class= "Java" >         string  locale = request.getlocalname ()//Transfer Protocol              string url = request.getrequesturl (). toString ();//The address of the request              string uri = request.getrequesturi ()//address with no host name              String protocol =  Request.getprotocol ()//acquisition protocol             String  &NBSP;ADD&NBSP;=&NBSP;REQUEST.GETREMOTEADDR ()//client ip             String host = Request.getremotehost ()//client host name             String  Port = request.getremoteport () + "";//Client port number              string method = request.getmethod ()//client's request mode   

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.