Javaweb servlet: Request and response

Source: Internet
Author: User
Tags html form apache tomcat

1 Introduction

There are many types of browsers and servers, and to communicate between them, you must follow certain guidelines, and the HTTP protocol is such a "guideline".

HTTP protocol: Specifies a format for browser and server data transfer.

When the browser wants to get the server's service, it sends a request to the server, which is sent to the server using the format specified in the HTTP protocol, and the server receives the request and sends the server's response to the browser in the format specified in the HTTP protocol.

Let's take a look at an example of this "format"

Format of Request:

Get/day09/first http/1.1             --Request line host:localhost:8080                  --Request header (multiple key-value pairs) user-agent:mozilla/5.0 (Windows NT 6.1; WOW64; rv:33.0) gecko/20100101 firefox/33.0accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q= 0.8accept-language:en-us,zh-cn;q=0.8,zh;q=0.5,en;q=0.3accept-encoding:gzip, deflateconnection:keep-alive                                  -- Blank line name=eric&password=123456         --Entity content

Format of response:

http/1.1 OK                        --Response line server:apache-coyote/1.1                --Response header (multiple key-value pairs) content-type:text/html;charset= Utf-8content-length:46date:sat, 01:42:06 GMT                                    --Empty line xxxxxx                                --Entity content (the part that the browser body window sees)

Now just pay attention to the format, the specific content we explain below one by one

2.Http Request 2.1 Request Line

Get/day09/first http/1.1

There are three main sections in a request line:

1) GET represents the requested way. Commonly used are: Get requests, and post requests.

Request method:GET,POST,HEAD,PUT,CONNECT ,TRACE

2)/day09/first represents the URI of the resource that the request wants to get

                   URI: The Uniform Resource tag.

URL: Uniform Resource location parent.

3) http/1.1 represents the version of the HTTP protocol for the request format.  

http:1.0: Once a connection is established between the current browser and the server, only one request can be made once.

http:1.1: Once a connection is established between the current browser and the server, multiple requests can be made once.

So what's the most common way to get and post? It's about our form.

Only requests that are supported in an HTML form have two values: GET and POST.

Here is a piece of code for the form:

  

<formAction= "submitted Address"Method= "Get/post">User name:<inputtype= "text"name= "Name"/>Password:<inputtype= "Password"name= "Password"/>    <inputtype= "Submit"value= "Submit"/></form>

After the form is submitted, the form data is sent to the server with the request, and the data is written in the request, but the Get and post methods write the data in different places within the request.

Get mode
get/day09/testgetpost.html? name=eric&password=123456 http/1.1host:localhost : 8080user-agent:mozilla/5.0 (Windows NT 6.1; WOW64; rv:33.0) gecko/20100101 firefox/33.0accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q= 0.8accept-language:en-us,zh-cn;q=0.8,zh;q=0.5,en;q=0.3accept-encoding:gzip, Deflatereferer:http://localhost : 8080/day09/testgetpost.htmlconnection:keep-alive

As you can see, the request submitted by the Get method, the data of the form is written in the request line and separated by a question mark after the resource is requested.

Therefore, the form data will appear in the browser's address bar, get method is not suitable for submitting sensitive data, and the amount of data can not be too large, not more than 1KB.

Post mode
post/day09/testgetpost.html http/1.1host:localhost:8080user-agent:mozilla/5.0 (Windows NT 6.1; WOW64; rv:33.0) gecko/20100101 firefox/33.0accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q= 0.8accept-language:en-us,zh-cn;q=0.8,zh;q=0.5,en;q=0.3accept-encoding:gzip, Deflatereferer:http://localhost : 8080/day09/testgetpost.htmlconnection:keep-alivename=eric&password=123456

1) The parameters are placed in the requested entity content. The parameters are split between & .

2)POST method to submit sensitive data

3) There is no limit to the size of the POST submission data.

The above is the analysis in the request line, let's analyze the request header.

2.2 Request Header
accept:text/html,image/*    --The browser tells the server which data types are supported Accept-charset:iso-8859-1   --The encoding accept-encoding:gzip supported by the browser, Compress   ---Browser supported data compression format accept-language:en-us,zh---      browser supported language host:www.it315.org:80            -- Browsers need access to the host and Port If-modified-since:tue, 18:23:51 GMT  -The last updated cache time for the browser referer:http://www.it315.org/ index.jsp     -which resource user-agent:mozilla/4.0 the current request is from (compatible; MSIE 5.5; Windows NT 5.0)  --Browser type cookie:name=eric                  --browser-saved cookie information connection:close/keep-alive         -the state of the browser connection. Close: Off. Keep-alive: Stay Connected Date:tue, one Jul 18:23:51 GMT    --Time of request

The request header contains a lot of information from the browser, we can get this information from the request header, which is actually some key value pairs, use this information to determine the state of the browser user, and use this information to implement some functions.

So what do we get from these packaged information and how do we use the code?

There is a class in Java that is used to get the information inside the request line:

httpservletrequest Object : Used to get the requested information (very important), then process it, and arrive at a different response.

Core approach:

Request Line:

Request.getmethod (); Get the Request method

Request.getrequesturi ()/Getrequesturl () Gets the URL of the requested resource

Request.getprotocol () Get Protocol version

Request Header:

Request.getheader ( header name )

Request.getheadernames (); get all the heads

Request.getheaders ( header name ) Gets the value of the header with the same name

Entity content:

Request.getinputstream (); Get an input stream of entity content

So how do you get this object? We build a servlet on the server and rewrite the Doget () method of the parent class, and the Doget method is that when the browser sends the request-path server in a Get mode, the server executes the contents of the Doget () method, looking at the following code:

 Public class extends HttpServlet {    publicvoid  doget (httpservletrequest request, HttpServletResponse Response)            throws  servletexception, IOException {            }}

We can see that in the parameters of the Doget () method, there is a parameter of type HttpServletRequest, that is, in the Doget () method, we can use this parameter to invoke the core method of the HttpServletRequest object mentioned above To get the data in the request!

Here we use these methods to get the information in the request line:

     Public void doget (httpservletrequest request, httpservletresponse response)             throws servletexception, IOException {        = request.getmethod ();        System.out.println ("method is:" + method);         = Request.getrequesturi ();        System.out.println ("RequestUri is:" + RequestUri);         = Request.getprotocol ();        System.out.println ("protocol is:" + protocol);    }

Output Result:

method Is:getrequesturi is:/myfirstproject/testservletprotocol is:http/1.1

This will get the information in the request line!

Similarly! Get information about key-value pairs within the request header, as well as information about the entity's content, or you can use the HttpServletRequest in the Doget () method, which is not shown here. Then we'll look under the Doget () method below!

Doxxx () method

As mentioned above, the servlet will call the Doget () method to handle the request submitted in Get mode, which is very easy to understand.

So, if the browser submits the request by post, the servlet calls its Dopost () method to handle the ~

There are so many ways to request it: GET, POST, HEAD, PUT, CONNECT, TRACE

In which case, the servlet invokes the Doxxx () method to process the corresponding request.

Get the data for the form

The data of the form is stored in the request:

Request line (get mode)

Get/day09/testgetpost.html?name=eric&password=123456 http/1.1

Entity content (post mode)

name=eric&password=123456

The attentive reader may find that the core approach to HttpServletRequest described above, although the data in the request can be obtained, but it is very difficult to distinguish the form content clearly, for example, if we want to get the value of name, then we should write a program to judge the parsing string, Gets the value of name. This is a lot of trouble, so the servlet provides some easy ways to get the form data.

  

    A uniform way to obtain form parameters in a request:

Request.getparameter ( parameter name ) Gets the parameters of a single value, such as obtaining the value of name, so write: Request.getparameter ("name");

Request.getparametervalues(parameter name) gets the parameters of multiple values, some form a property has multiple values, for example you have multiple hobbies, so long call this method to get the multiple values of the hobby.

Request.getparameternames (); get all the arguments, this method gets the name of all the parameters of the form, such as a form that has: Name,id,hobit,address,phone, and so on.

In real life, depending on the needs of the user submitted form may be submitted by get, or post, the form data is stored in different places of the request according to different submissions, but we get the form data after the data processing is the same, if the Dopost () and Doget () write the same processing method is the code is too cumbersome, then how do we deal with this situation?

We can call the Doget () method in the Dopost () method, judge the request in Doget (), then get the data based on the two requests and then process the data.

encoding problem for request parameters

1)POSTWay

Request.setcharacterencoding (Code table);   

used to set the Code table for queries when getting entity content parameters. Suggest putting the first line of code

2)GetMethod

2.1 Manual decoding: (recommended)

if ("GET"new String (ah.getbytes ("iso-8859-1"), "Utf-8");}

2.2 Modifying the server's configuration file (server dependent, not recommended)

Locate %tomcat%/conf/server.xml, Modify the following configuration

<connector port= "8080" protocol= "http/1.1"

connectiontimeout= "20000"

Redirectport= "8443" uriencoding= "Utf-8"/> Add uriencoding attribute, set The encoding of the parameters after the URI

HTTP corresponding

After saying the request, we say the corresponding, if you understand the content of the request, the response content is absolutely no problem!

In response to the browser wanting the server to make a request, the server responds, and we look at the following response format:

http/1.1 OK                        -- response line Server:apache-coyote/1.1                -- response header (multiple key value pairs) Content-type:text/html; Charset=utf-8Content-length:4601:42:06 GMT                                    -- empty line  xxxxxx

The format of the response is similar to the format of the request.

Response Line

Consists of three parts:

Http Protocol version http/1.1

Status code: The server tells the browser the result of the request processing.

Common State:

Request processing completed

The 302 client needs to send further requests to complete the process. Typically, this status code is used with the location response header.

404 Requested resource not found

An error occurred on the server's resources.

Status Description: Supplement to the status code

Response header
Location:http://www.it315.org/index.jsp---The redirected address. Usually used in conjunction with 302 status codes. Server:apache Tomcat--type of server content-encoding:gzip--content compression format that the server sends to the browser-LENGTH:80--the server sends the browser's data length content-LANGUAGE:ZH-CN--content languages that the server sends to the browser-type:text/html; charset=gb2312--the content type and encoding of the server sent to the browser last-modified:tue, each Jul 18:23:51 GMT--last modified time for server resources refresh:1;url=http://www.it315.org--timed Refresh or N-second jump pageContent-disposition:attachment; Filename=aaa.zip--tell the browser to open the resource transfer-encoding:chunked Set-COOKIE:SS=Q0=5LB_NQ; Path=/search--server sends cookie information for browser expires:-1--notifies the browser not to use cache caches-control:no-cache--notifies the browser not to use the cache Pragma:no-cache--notifies the browser not to use the cache Connection:close/keep-Alive Connection Status Date:tue,Jul 18:23:51 GMT Response time

The last is the entity content. We can use the HttpServletResponse object to manipulate the content and then send it to the browser in a way that is similar to the HttpServletRequest object. Not explained here.

Javaweb servlet: Request and response

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.