"Head first Servlets and JSP" Note 5

Source: Internet
Author: User

"HttpServletResponse resp"

1, generally can be used through the RESP to obtain an output stream (writer), and then through the output stream to write the HTML response. For example:

      Resp.setcontenttype ("text/html");         = Resp.getwriter ();        Out.println ("Beer Selection advice<br>");

2, a number of common methods.

3. Sometimes it will be used.

4. Of course, it is more common to use JSP to return HTML.

5. Suppose you want to send a jar to the client ...

//a bunch of import Public classCodereturnextendsHttpServlet { Public voidDoget (httpservletrequest req, HttpServletResponse resp)throwsIOException, servletexception { resp.setcontexttype ( "Application/jar"); // things you want your browser to know ServletContext CTX=Getservetcontext (); InputStream is= Ctx.getresourceasstream ("/bookcode.jar"); intRead = 0; byte[] bytes =New byte[1024]; OutputStream OS=Resp.getoutputstream ();  while(read = Is.read (bytes))! =-1) {os.write (bytes,0, read); } //The jar packet is read into memory before being transcribed into the output stream. Os.flush ();    Os.close (); }}

PS: You cannot write a type first, and then change to another type to continue writing.

6. Why should I return a file through a servlet instead of returning it directly? The reason is that you want to perform some logic before and after returning a specific type of file, such as determining whether the user has permission to download the file.

7, some things to remember, about the output, there are only two choices: characters or bytes.

Output streams that can be returned via resp ...

        /* Omit parameter */ // can write any content        // similar to SYSTEM.OUT.PRINTLN () for processing character data. is actually the advanced flow printwriter that wraps the OutputStream

"Head first Servlets and JSP" Note 5

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.