Java EE HTTP request and response principle, servlet processing principle

Source: Internet
Author: User
Tags response code server port

HTTP requests and Responses

When the following events occur, the browser sends an HTTP request to the Web server:

1. The user clicks a hyperlink on the webpage;

2. The user submits the form which fills on the webpage;

3. The user enters the URL address in the browser address bar and returns.

The process of processing HTTP requests in the servlet:

1.Web the browser initializes an HTTP request by opening a TCP socket socket to the Web server, and the input stream of the socket contains the HTTP request data, and the output stream of the socket contains the number of HTTP responses.

2. For each access request to a servlet, the Web container resolves the HTTP request data in the socket input stream, creates a request object, and also creates a response object.

The 3.Web container invokes the service () method of the requested Servlet object and passes the request and response object as a parameter to the method, where the response object passed in as a parameter is the HttpServletResponse object. Within the service () method of the Servlet object, you can invoke various methods of the Httpservletrespnse object to create a response message.

The 4.HttpServletResponse Response object provides a PrintWriter object to the servlet so that the servlet can produce a response message body.

When a user submits a Web page or form, the browser sends a request to the server in the following ways: Get,head,post,put,delete,option,reace, in the servlet, each method objects to a request method, which, when used, We generally only need to implement the required methods in the servlet. The most commonly used request methods are the Get and post methods, Use these two methods under these conditions: 1. Use the Get method when requesting a static page or graphic file, because only the file name needs to be sent; 2. When sending large data, use the Post method; 3. When uploading files, use the Post method; 4. Send User name, The Post method is used for passwords or other confidential information.

In the servlet we need to access the requested line information, and we need to invoke the following method with the Request object:

GetMethod (): Obtain HTTP request method, such as: Get and post

Getrequesturi (): Gets the requested URI resource, such as:/lovobook/index.html

Getrequesturl (): Gets the URL of the request that contains the protocol name, server name, or IP, port number, and request resource but does not include query string parameters, such as: http://127.0.0.1:8080/lovobook/index.html

GetQueryString (): Gets the query string after the request URL, such as: NAME=AAA (Post does not have this method)

Getprotocol (): Get protocol name and version number, such as: http/1.1

Getcontextpath (): Gets the context path of the request URI resource, always beginning with "/", such as:/lovobook

Getservletpath (): Gets the mapping path of the servlet (see http://hi.baidu.com/pangang107/blog/item/ Servlet deployment in Web.xml in fd664d2d0cad45f48b139925.html)

The HTTP request header is invoked through the following methods of the HttpServletRequest object:

GetHeader (String name): Returns the value of the request header, or null if no

Getheaders (String name): If the requested value has more than one, this method returns a enumeration enumeration containing the values

Getheadernames (): Returns a enumeration containing the names of all the request headers

Getintheader (String name): Gets the value of the request header and converts to the int type, returns 1 if it does not exist, and does not convert to run an exception, numberformatexception

Getdateheader (String name): Gets the value of a particular request header and converts to the date type

Call the following method to obtain the request parameter, the form data, by requesting the object HttpServletRequest:

GetParameter (String parametername): Gets the form parameter value through the parameter name (case-sensitive, same as the form parameter name), applies to the Get/post method, and returns null if this argument is not available

Getparametervalues (String parametername): Returns an array containing all the values of this parameter name

Getparameternames (): Returns a enumeration containing all the parameter names

Note that when you upload a file, the form on the Web page should contain these parameters:

<form type= "File" method= "post" enctype= "Mutipart/form-data" >

....

</form>

Request forwarding can be implemented by Javax.servlet.RequestDispatcher objects, RequestDispatcher objects can be obtained in the following ways:

Getrequestdispatcher (String Path): path path must start with root directory "/" and can be directed to any resource in the Web application, such as: Request.getrequestdispatcher ("/ HelloWorld "), the container will see this as starting at the root of the Web application, and if you do not start with"/", the container will assume that the path is relative to the original request.

Getnameddispatcher (String name): Name name must be defined in Web.xml servlet-name element

obtained by Getrequestdispatcher () of the context object ServletContext, the path must begin with the root directory "/"

The RequestDispatcher object provides two ways to contain different resources and forward requests to different resources

Forward (ServletRequest, Serverletresponse): Distributes request and response objects to new resources (servlet,jsp, or HTML, etc.) determined by the RequestDispatcher object. This resource handles HTTP requests by leveraging request and response objects, such as: Request.getrequestdispatcher ("/success.html"). Forward (Request,response);

Include (ServletRequest, servletresponse): Usage with Forward () method, there are some limitations, it can contain server-side resources, the contained resources can not change the response status Code or set header information, any attempt to change the format will be ignored , usually not.

The response status code setting generally uses the response.setstaauts (int) method, but HttpServletResponse defines a specific method for both cases:

Senderror (int code,string message): Generates a 404 response while generating a short HTML error information document sent to the client

Sendredirect (String URL): Generates a 302 response while indicating the URL address of the new document in location, which is redirect

How to set response header information:

Containsheader (String name): Returns a Boolean value indicating whether the specified response header is set

SetHeader (String name,string value): A common way to set the response header with a given name and string value, such as if the response header has already been set, overrides the

Setintheader (String name,int value): ibid., Value int type

Setdateheader (String name,long date): Ibid., Date value, date value should reflect a long integer accurate to millisecond since 1970-1-1 Day (GMT)

AddHeader (String name,string value): Used to add a response header for a given name and string in response, regardless of whether a header with the same name already exists, because the method allows multiple values for the response header

Addintheader (String name,int value): ibid., Value int type

Adddateheader (String name,long date): Ditto, long integer value with date value

setContentType (String mimetype): Sets the MIME type returned to the client, which is used by most servlet methods, such as: Responde.setcontenttype ("text/html; Charset=utf-8 ");

Addcookie (Cookie C): Used to insert a cookie into the Set-cookie header because you can set multiple cookies, all without setcookie methods.

The redirect process is: 1. A Web browser sends a request via HTTP; 2. The servlet of the server-side response sends the real connection URL address and the 302 response code to the client; 3. The response ends, the browser disconnects but the front is connected, and then the HTTP request is issued based on the URL address of the location response header. To set redirects:

Typically, an absolute address is used and is a complete URL path to achieve redirection, such as:

Response.sendredirect ("http://127.0.0.1:8080/lovobook/bar.html");

Or start with the "/" of the Web application, using a URL path, such as:

Response.sendredirect ("/lovobook/bar.html");

Web applications can be deployed to the war file, and the HttpServletRequest Getcontextpath () method obtains an absolute path to the Web application root directory and can be used for a union of URL addresses, such as:

Response.sendredirect (Request.getcontextpath () + "/lovobook/bar.html");

Set up automatic refresh and wait pages (not guaranteed by all browsers), code:

Response.setheader ("Refresh", "Time"); Url=url ");

such as: Response.setheader ("Refresh", "10; Url=http://127.0.0.1/foo.html ");

The raw byte data of the parameter in the request can be obtained by using the getInputStream () method of the HttpServletRequest object to obtain a byte stream, or through the Getreader () method to get the character streams through which to access the form data.

After the request is received, the server uses a character stream Java.io.PrintWriter object (obtained by Response.getwriter ()) to return the text content, and the byte Streams Servletoutputstream objects ( Response.getoutputstream () to allow developers to manipulate byte streams

1, httpservletrequest Introduction:

(1) The HTTP request message sent to the Web server by the Web client is divided into three parts:

A) Request line Post/demo/login http/1.1

b) Request message headers

c) Message body (also called entity content) username=xxxx&password=1234

(2) The ServletRequest interface class defined in the Servlet API is used to encapsulate request messages.

(3) HttpServletRequest is a servletrequest sub-interface dedicated to the HTTP protocol, which encapsulates HTTP request messages.

(4) Call the HttpServletRequest object's various methods inside the service () method to obtain the request message.

2, get information about the request line :

(1) The request line of the HTTP request message includes the request method, the resource path, and the HTTP protocol version:

Get/it315/servlet/requesturi?param1=a&param2=b http/1.1

(2) The GetMethod method returns the request mode in the HTTP request message.

(3) The Getrequesturi method returns the resource name portion of the request line.

(4) The GetQueryString method returns the parameter portion of the request line.

(5) The Getprotocol method returns the protocol name and version in the request line.

(6) The Getcontextpath method returns the path of the Web application to which the request resource belongs.

(7) The GetPathInfo method returns additional path information in the request URL. The extra path information is the content that follows the path of the servlet in the request URL and before the query parameters, and begins with "/".

(8) The GetPathTranslated method returns the true path of the resource corresponding to the additional path information in the URL.

(9) The Getservletpath method returns the name of the servlet or the path mapped by the servlet.  

3, to obtain information on the request line---------examples

4. Get network connection Information

(1) The Getremoteaddr method returns the IP address of the client that issued the request, in the form of "192.168.0.3" character text. (*)

(2) The Getremotehost method returns the full hostname of the requesting client, which is the "pc1.it315.org" format.

(3) The Getremoteport method returns the port number of the network interface used by the requesting client.

(4) The Getlocaladdr method returns the IP address of the network interface on the Web server that receives the current request.

(5) The Getlocalname method returns the host name of the IP address of the network interface on the Web server that receives the current request.

(6) The Getlocalport method returns the port number of the network interface on the Web server that receives the current request.

(7) The getServerName method returns the host name that the current request points to.

(8) The Getserverport method returns the server port number to which the current request is connected.

(9) The Getscheme method returns the requested protocol name, such as HTTP, HTTPS, or FTP.

(a) The Getrequesturl method returns the full URL when the client makes a request.   

5, get all the request headers of the programming instance

Enumeration headernames = Request.getheadernames ();

while (Headernames.hasmoreelements ())

{

String headername = (string) headernames.nextelement ();

Out.print (Headername + ":" + request.getheader (headername) + "<br>");

/* If you want to consider the same request header names may occur multiple times,

Then you should use the following code snippet instead of the above line of program code * *

/*enumeration values = request.getheaders (headername);

while (Values.hasmoreelements ())

{

Out.print (Headername + ":" + (String) values.nextelement () + "<br>");

}*/

}

6, use the Referer request head to prevent "hotlinking"

String referrer = Request.getheader ("Referer");

String Sitepart = "http://" + request.getservername ();

if (Referrer!=null && referrer.startswith (Sitepart))

{

Handling legitimate download requests, here's just a schematic.

Out.println ("Dealing download ...");

}

Else

{

Illegal download request jump to the site's Download Instructions page

RequestDispatcher rd = Request.getrequestdispatcher ("/down.html");

Rd.forward (Request,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.