"Head first Servlets and JSP" Note 6: What is the response header

Source: Internet
Author: User

Build a simple test environment

What is the response header

The simplest response header--content-type

Setting the response header

Request redirection and Response header

View response Headers in the browser

1, first quickly build a simple test environment, the future content will be based on the following code, Tomcat Webapps:html5+web.xml+servlet

<!DOCTYPE HTML><HTML>    <Body>        <formAction= "Mytest.do"Method= "Get">Username:<BR>            <inputtype= "text"name= "username"value="">            <BR>Password:<BR>            <inputtype= "text"name= "passwd"value="">            <BR><BR>            <inputtype= "Submit"value= "Submit">        </form>         <P>This is a simple test.</P>    </Body></HTML>
<?XML version= "1.0" encoding= "Iso-8859-1"?><Web-appxmlns= "HTTP://JAVA.SUN.COM/XML/NS/J2EE"Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"xsi:schemalocation= "Http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"version= "2.4">    <servlet>        <Servlet-name>MyTest</Servlet-name>        <Servlet-class>Com.example.web.MyTest</Servlet-class>    </servlet>    <servlet-mapping>        <Servlet-name>MyTest</Servlet-name>        <Url-pattern>/mytest.do</Url-pattern>    </servlet-mapping></Web-app>
 PackageCom.example.web;Importjavax.servlet.*;Importjavax.servlet.http.*;ImportJava.io.*; Public classMyTestextendsHttpServlet { Public voidDoget (httpservletrequest req, HttpServletResponse resp)throwsIOException, servletexception {resp.setcontenttype ("Text/html"); PrintWriter out=Resp.getwriter (); Out.println ("Hello world<br/>"); }}

This servlet should be well understood, that is, clicking submit will jump out of a page with a line of "Hello World".

2, what is the response header.

The response header (Response Headers) belongs to one of the HTTP headers.

First of all, it is necessary to understand that the response header does not include the information that the user wants to see, the "multimedia" page, that is to say, for ordinary netizens, do not need to know this information.

So, what is the response header for? It is primarily used to facilitate communication between the client and the server, for example, if the server tells the client in the response header whether the content returned is HTML, or jar, or zip, so that the browser can respond correctly: The display page or provides the download.

3. The simplest response header--content-type

In the response header, the Content-type field represents the object type of the message body, and you can do a test if the servlet is modified as:

 PackageCom.example.web;Importjavax.servlet.*;Importjavax.servlet.http.*;ImportJava.io.*; Public classMyTestextendsHttpServlet { Public voidDoget (httpservletrequest req, HttpServletResponse resp)throwsIOException, servletexception {resp.setcontenttype ("Text/html"); Resp.setheader ( " Content-type", "Application/jar"); //SetHeader Effect: If a header with the same name already exists in the response, replace the original value with this value. Otherwise, add a new header and value to the response header. PrintWriter out=Resp.getwriter (); Out.println ("Hello world<br/>"); }}

After the modification, when we click Submit in the browser page, we will not get a Hello World page, but the download mytest.do this file directly, but its content will be Hello world<br/>. It is important to note that if you make the content-type wrong, then SetHeader will not help you to point out the error, but add a "typo" header!

4, you can set the response header, you can also increase the response header.

Continue modifying the servlet to change the SetHeader to AddHeader:

 PackageCom.example.web;Importjavax.servlet.*;Importjavax.servlet.http.*;ImportJava.io.*; Public classMyTestextendsHttpServlet { Public voidDoget (httpservletrequest req, HttpServletResponse resp)throwsIOException, servletexception {resp.setcontenttype ("Text/html"); Resp.addheader ( " Content-type", "Application/jar"); //AddHeader Effect: Adds a new header and value to the response header, or adds another value to the existing one. PrintWriter out=Resp.getwriter (); Out.println ("Hello world<br/>"); }}

It is easy to guess the results of the run: both the download and the Hello World page, but this is wrong, the actual test results are: only to provide download and not provide page display.

There is also a way to set the header: Setintheader, the effect is similar to SetHeader, but the header value is no longer a string type, but an int type.

Other ways to set the header can be see the official API, not many.

5, redirect the request to another completely different URL, that is, to forward the request to another person to handle. You can use the following code to complete the form:

 PackageCom.example.web;Importjavax.servlet.*;Importjavax.servlet.http.*;ImportJava.io.*; Public classMyTestextendsHttpServlet { Public voidDoget (httpservletrequest req, HttpServletResponse resp)throwsIOException, servletexception { resp.sendredirect ( "http://www.cnblogs.com/xkxf/"); }}

After the modification, when we press submit, we will jump directly to the new URL, (of course, the new URL here does not handle the request).

Sendredirect's usage is not difficult to understand, then when Resp.sendredirect, what happens in essence?

This time we think, must have changed the response of the first, if there is a way to view the HTTP message directly, then we can know exactly what happened.

6. What if you look at response headers?

In Google Chrome, press F12 to enter the developer page, you can use this method to observe the above code on the response header (Response Headers) the actual impact. As shown below (click to view larger image):

Click on the network, you can observe a header named Loction, the content is exactly the URL we redirect, then if the servlet code is changed to "Resp.setheader (" Location "," http://www.cnblogs.com/xkxf/"); Can I implement redirection? The answer is no, but add the words "resp.setstatus (302);" It is possible to achieve this effect.

7. Finally, what does Sendredirect ("another URL") mean? The explanation in the book is that you want the browser to process the request with "another URL," and its true usage is:

        if (worksforme) {            //  Some codes ...        Else {            resp.sendredirect ("another URL");        }

The "Other URL" can also use a relative URL, which needs to be differentiated

    • Sendredirect ("foo/hi.html"); redirects to the full URL established relative to the current URL
    • Sendredirect ("/foo/hi.html"); redirects to the full URL relative to the Web app root directory

"Head first Servlets and JSP" Note 6: What is the response header

Related Article

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.