Java Web development-response object

Source: Internet
Author: User

Response object

I,Introduction

 

When the lweb server receives the HTTP request from the clientEach timeCreate a request object for the request and a response object for the response.

The lrequest and response objects represent requests and responses. To obtain the data submitted by the client, you only need to find the request object. To output data to the client, you only need to find the response object.

1. httpservletresponseResponse. This object encapsulates the methods for sending data to the client, sending response headers, and sending response status codes.

 

 

 

 

 

void

 

 

setStatus(int  sc)
Sets the status code for this response.

 

 

void

 

 

addHeader(java.lang.String  name, java.lang.String value)

Adds a response header with the given name and value.

 

 

java.io.PrintWrite

 

 

getWriter()
ReturnsPrintWriterObject that can send character text to the client.

 

 

ServletOutputStream

 

 

getOutputStream()
ReturnsServletOutputStreamSuitable for writing binary data in the response.

 

 

2,Common response applications

L output Chinese data to the client

• Output with outputstream and printwriter respectively

Solution to browser garbled characters:

Method 1,

Private void Test2 (httpservletresponse response)
ThrowsIoexception{

Response. setheader ("Content-Type", "text/html; charset = gb2312 ");

String STR = "Chinese people ";

Response. getoutputstream (). Write (Str. getbytes ());

}

Method 2,

Private voidTest1 (httpservletresponse response)
ThrowsIoexception,

Unsupportedencodingexception {

Response. setheader ("Content-Type", "text/html; charset = UTF-8 ");

String STR = "Chinese people ";

Response. getoutputstream (). Write (Str. getbytes ("UTF-8 "));

}

 

 

Method 3: • Learn More: Use the <meta> tag in the HTML language to control browser behavior

Private voidTest3 (httpservletresponse response)
ThrowsIoexception,

Unsupportedencodingexception {

String data = "China ";

Response. Getoutputstream (). Write ("<meta http-equiv = 'content-type' content = 'text/html; charset = UTF-8 '>". getbytes ());

Response. getoutputstream (). Write (data. getbytes ("UTF-8 "));

}

 

 

• Thinking: outputstream is used to output 1. Why do users not see 1?

The browser is a character display tool. The browser obtains the decoding of number 1, but the character represented by number 1 will be searched from the character encoding during display. Then, 1 will not be seen, the solution is as follows:

Response. getoutputstream (). Write ("89". getbytes ("UTF-8 "));

The specified character encoding is optional.

 

Use the character output stream to solve the garbled problem:

 

Private voidTest4 (httpservletresponse response)
ThrowsIoexception {

Response. setcharacterencoding ("UTF-8 ");

Response. setheader ("Content-Type", "text/html; charset = UTF-8 ");

// Response. setcontenttype ("text/Html;Charset= UTF-8 "); this sentence is equal to the above two sentences.

String data = "China ";

Printwriter writer = response. getwriter ();

Writer. Write (data );

}

 

L file download and Chinese File Download

 

Note that the first parameter of string replaceall (string RegEx, string replacement) is a regular expression.

If it is a Chinese file name, the file name must go throughURLEncoding

Private voidDown (httpservletresponse response)
ThrowsIoexception,

Unsupportedencodingexception, filenotfoundexception {

Response. setcontenttype ("text/html; charset = UTF-8 ");

String filepath =This. Getservletcontext (). getrealpath ("/download/7.jpg ");

Outputstream out = response. getoutputstream ();

File file =NewFile (filepath );

If(! File. exists ()){

Out. Write ("sorry, the downloaded resource has been deleted !! ". Getbytes (" UTF-8 "));

Return;

}

String filename = filepath. substring (filepath. lastindexof ("\") + 1 );

Filename = urlencoder.Encode(Filename, "UTF-8 ");

Filename = filename. replaceall ("\\+", "% 20 ");

Response. setheader ("content-disposition", "attachment; filename =" + filename );

Fileinputstream in =NewFileinputstream (File );

Outputstream OS = response. getoutputstream ();

ByteBuffer [] =New byte[1024];

IntLen = 0;

While(LEN = in. Read (buffer)> 0 ){

OS. Write (buffer, 0, Len );

}

In. Close ();

}

 

 

L random image output

 

 

Import java. AWT. color;

Import java. AWT. Font;

Import java. AWT. graphics;

Import java. AWT. graphics2d;

Import java. AWT. image. bufferedimage;

Import java. Io. ioexception;

Import java. Io. printwriter;

Import java. util. Random;

 

Import javax. ImageIO. ImageIO;

Import javax. servlet. servletexception;

Import javax. servlet. http. httpservlet;

Import javax. servlet. http. httpservletrequest;

Import javax. servlet. http. httpservletresponse;

 

Public class responsepic extends httpservlet {

 

Privatestatic final int width = 130;

Privatestatic final int Height = 30;

Publicvoid doget (httpservletrequest request, httpservletresponse response)

Throws servletexception, ioexception {

Bufferedimage image = newbufferedimage (width, height, bufferedimage. type_int_rgb );

Graphics graphics = image. getgraphics ();

Setbackground (graphics );

Setborder (graphics );

Drawrandomline (graphics );

Drawrandomnum (graphics2d) graphics );

Response. setdateheader ("expires",-1 );

Response. setheader ("cache-control", "No-Cache ");

Response. setheader ("Pragma", "No-Cache ");

Response. setcontenttype ("image/JPEG ");

ImageIO. Write (image, "jpg", response. getoutputstream ());

}

Privatevoid setbackground (Graphics graphics ){

Graphics. setcolor (color. White );

Graphics. fillrect (0, 0, width, height );

}

Privatevoid setborder (Graphics graphics ){

Graphics. setcolor (color. Blue );

Graphics. drawrect (1, 1, width-2, height-2 );

}

Privatevoid drawrandomline (Graphics graphics ){

Graphics. setcolor (color. Green );

For (INTI = 0; I <5; I ++ ){

Int X1 = new random (). nextint (width );

Int Y1 = new random (). nextint (height );

Int X2 = new random (). nextint (width );

Int y2 = new random (). nextint (height );

Graphics. drawline (x1, Y1, X2, Y2 );

}

}

 

// [\ U4e00-\ u9fa5]

Privatevoid drawrandomnum (graphics2d graphics ){

Graphics. setcolor (color. Red );

Graphics. setfont (new font (" ICS", Font. Bold, 20 ));

Stringbase = "\ u7684 \ u4e00 \ u4e86 \ u662f \ u6211 \ Alibaba \ u5728 \ u4eba \ Alibaba \ u6765 \ Alibaba \ u7740 \ u4e2a \ u5730 \ u5230 \ u5927 \ u91cc \ u8bf4 \ u5c31 \ u53bb \ Alibaba \ u90a3 \ u8981 \ Alibaba \ u770b \ u5929 \ u65f6 \ Alibaba \ u51fa \ Alibaba \ u8d77 \ alibaba \ u90fd \ u628a \ u597d \ u8fd8 \ u591a \ u6ca1 \ Alibaba \ u53c8 \ u53ef \ Alibaba \ u53ea \ Alibaba \ u6837 \ u5e74 \ u60f3 \ u751f \ users \ u8001 \ u4e2d \ u5341 \ u4ece \ u81ea \ u9762 \ Users \ u5934 \ u9053 \ Users \ u50cf \ u89c1 \ u4e24 \ u7528 \ u5979 \ u56fd \ u52a8 \ Alibaba \ u6210 \ u56de \ u4ec0 \ u8fb9 \ u4f5c \ u5bf9 \ Alibaba \ u800c \ Alibaba \ u5019 \ u7ecf \ u53d1 \ Alibaba \ u5411 \ u4e8b \ u547d \ u7ed9 \ Users \ u58f0 \ Users \ u9ad8 \ u624b \ Users \ u7406 \ u773c \ Users \ u5fc3 \ u6218 \ alibaba \ u95ee \ u4f46 \ u8eab \ u65b9 \ Alibaba \ u505a \ u53eb \ Alibaba \ u542c \ u9769 \ Alibaba \ u5462 \ Alibaba \ u5168 \ Alibaba \ u56db \ u5df2 \ u6240 \ Users \ u6700 \ u5149 \ u4ea7 \ u60c5 \ u8def \ u5206 \ u603b \ u6761 \ Users \ u4eb2 \ u5982 \ u88ab \ u82b1 \ u53e3 \ u653e \ u513f \ u5e38 \ Alibaba \ u7b2c \ Alibaba \ u5427 \ u6587 \ u8fd0 \ Alibaba \ u679c \ u600e \ Alibaba \ u5feb \ u660e \ u884c \ Users \ u98de \ u5916 \ u6811 \ u00009 \ u6d3b \ u90e8 \ u95e8 \ Users \ u8239 \ u671b \ Users \ u961f \ u5148 \ Users \ alibaba \ u7ad9 \ u4ee3 \ u5458 \ u673a \ u66f4 \ u4e5d \ u60a8 \ Alibaba \ u98ce \ Alibaba \ Users \ u5c11 \ u76f4 \ u610f \ u591c \ alibaba \ u9636 \ Alibaba \ u91cd \ u4fbf \ u6597 \ Alibaba \ u54ea \ u5316 \ u592a \ u6307 \ Alibaba \ u793e \ Alibaba \ u58eb \ u8005 \ u5e72 \ u77f3 \ Alibaba \ alibaba \ u51b3 \ u767e \ u539f \ u62ff \ u7fa4 \ Alibaba \ Users \ u672c \ u601d \ u89e3 \ Users \ u6751 \ Users \ u96be \ Users \ u8bba \ u5417 \ u6839 \ Alibaba \ Users \ u76f8 \ u7814 \ u4eca \ u5176 \ u4e66 \ u5750 \ u63a5 \ Users \ u89c9 \ Users \ u53cd \ u5904 \ u8bb0 \ Users \ alibaba \ Users \ u9886 \ u6216 \ Users \ u5757 \ u8dd1 \ u8c01 \ Users \ u52a0 \ u811a \ Users \ u7231 \ u7b49 \ u4e60 \ u9635 \ u6015 \ users \ u9752 \ u534a \ u706b \ u6cd5 \ u9898 \ u5efa \ Users \ u5531 \ Users \ u5973 \ Users \ u51c6 \ u5f20 \ u56e2 \ u5c4b \ u79bb \ u8272 \ Users \ u79d1 \ u5012 \ u775b \ u5229 \ u4e16 \ u521a \ Users \ u7531 \ u9001 \ Users \ u665a \ u8868 \ Users \ u6574 \ alibaba \ u54cd \ u96ea \ u6d41 \ u672a \ u573a \ u8be5 \ u5e76 \ Alibaba \ u8fd1 \ u4logy \ u8f7b \ u8bb2 \ alibaba \ u53e4 \ Alibaba \ u544a \ Alibaba \ u62c9 \ u540d \ u5440 \ u571f \ u6e05 \ u9633 \ Alibaba \ u53f2 \ u6539 \ Alibaba \ u753b \ u9020 \ u5634 \ alibaba \ u6cbb \ u5317 \ u5fc5 \ u670d \ u96e8 \ u7a7f \ u5185 \ Alibaba \ u83dc \ Alibaba \ u7761 \ Alibaba \ u91cf \ u54b1 \ u89c2 \ u82e6 \ Alibaba \ u901a \ u51b2 \ Alibaba \ u7834 \ u53cb \ u5ea6 \ u672f \ u996d \ Alibaba \ u65c1 \ Alibaba \ u6781 \ u5357 \ u67aa \ u8bfb \ Alibaba \ alibaba \ u91ce \ Alibaba \ u6536 \ u7b97 \ u81f3 \ u653f \ u57ce \ u52b3 \ u843d \ u94b1 \ Alibaba \ u56f4 \ Alibaba \ u80dc \ u6559 \ u70ed \ Alibaba \ u5305 \ alibaba \ u7c7b \ u6e10 \ u5f3a \ u6570 \ u4e61 \ Alibaba \ u6027 \ u97f3 \ Alibaba \ u9645 \ u65e7 \ Alibaba \ u5566 \ u53d7 \ u7cfb \ u4ee4 \ u8df3 \ u975e \ Alibaba \ u53d6 \ Alibaba \ u6133 \ Alibaba \ u79cd \ u88c5 \ u9876 \ u6025 \ u6797 \ u505c \ Alibaba \ u533a \ u8863 \ u822c \ u62a5 \ u53f6 \ u538b \ u6162 \ u53d4 \ u80cc \ u7ec6 ";

// 30*3.14/180

Intx = 10;

For (INTI = 0; I <4; I ++ ){

String CH = base. charat (newrandom (). nextint (base. Length () + "";

Int degree = new random (). nextint () % 30;

Graphics. Rotate (degree * Math. PI/180, X, 20 );

Graphics. drawstring (CH, X, 20 );

Graphics. Rotate (-degree * Math. PI/180, X, 20 );

X = x + 30;

}

}

 

Publicvoid dopost (httpservletrequest request, httpservletresponse response)

Throws servletexception, ioexception {

 

Doget (request, response );

}

 

}

 

HTML call page:

<! Doctype HTML public "-// W3C // dtdhtml 4.01 transitional // en">

<HTML>

<Head>

<Title> login.html </title>

<Meta http-equiv ="Keywords"Content ="Keyword1, keyword2, keyword3">

<Meta http-equiv ="Description"Content ="This is my page">

<Meta http-equiv ="Content-Type"Content ="Text/html; charset = UTF-8">

<SCRIPT type ="Text/JavaScript">

FunctionChangeimage (IMG ){

IMG. src = IMG. SRC + "? "+NewDate (). gettime ();

}

</SCRIPT>

 

</Head>

<Body>

<Form action ="">

Username: <input type ="Text"Name ="Username"> <Br/>

Password: <input type ="Password"Name ="Password"> <Br/>

Verification Code: <input type ="Text"Name ="Checkcode"> <IMG src ="/Day05/servlet/responsedemo4"Alt ="Change one"Style ="Cursor: hand"Onclick = "changeimage (this)"> <br/>

<Input type ="Submit"Value ="Login">

</Form>

</Body>

</Html>

L send an HTTP header and control the browser to regularly refresh the webpage (refresh)

Response. setcontenttype ("text/html; charset = UTF-8 ");

System.Out. Println ("process login !! ");

String message = "<meta http-equiv = 'refresh' content = '3;/day05/index. js'> congratulations! login successful !! This browser will jump in 3 seconds. If there is no jump, click ......";

This. Getservletcontext (). setattribute ("message", message );

This. Getservletcontext (). getrequestdispatcher ("/message. jsp"). Forward (request, response );

 

 

L send the HTTP header, and control the browser to prohibit caching the content of the current document

Response. setdateheader ("expires", system.Currenttimemillis() + 3600*1000 );

String data = "abcddddd ";

Response. getwriter (). Write (data );

L implement request redirection through response.

• Request redirection: A web resource notifies the client to access another Web Resource after receiving a request from the client, which is called request redirection.

L Application Scenario: user login.

 

L Implementation Method

• Response. sendredirect ()

• Implementation principle: equivalent to the following code

• 302 status code and Location header for redirection

Response. setstatus (302 );

Response. setheader ("location", "/day05/login.html ");

 

Redirection features:

 

* 1. Redirection will cause the browser to send two requests to the server (the server will create two requests and response)

* 2. the address bar of the browser changes during redirection.

 

Response Details

The lgetoutputstream and getwriter methods are used to obtain the servletouputstream and printwriter objects that output binary data and text data respectively.

The lgetoutputstream and getwriter methods are mutually exclusive. After you call any of the methods, you cannot call another method.

For example,

Response. getwriter ();

Response. getoutputstream ();

 

The data written by the lservlet program to the servletoutputstream or printwriter object will be obtained by the servlet engine from the response. The Servlet Engine regards the data as the body of the Response Message, then, it is combined with the response status line and Response Headers and then output to the client.

After the service method of lserlvet is completed, the servlet engine checks whether the close method has been called for the output stream object returned by getwriter or getoutputstream. If not, the servlet engine calls the close method to close the output stream object.

 

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.