Servlet--httpservletrequest Object Explanation

Source: Internet
Author: User
Tags form post

The HttpServletRequest object represents the client's request, and when the client accesses the server through the HTTP protocol, all the information in the HTTP request header is encapsulated in the object, and the developer can obtain this information from the client by means of this object.

======================================================================================

HttpServletRequest Common methods

The Getrequesturl method returns the full URL of the client when the request is made
The Getrequesturi method returns the resource name portion of the request row
The GetQueryString method returns the parameter part of the request line (parameter name + value)
The Getremoteaddr method returns the IP address of the client that made the request
The Getremotehost method returns the full host name of the client that made the request
Getremoteport method returns the network port number used by the Web server
Getlocalport method returns the network port number used by the Web server
Getlocaladdr method returns the IP address of the Web server
Getlocalname method returns the host name of the Web server

The following tests are done in the servlet:

Get urlstring URL = Request.getrequesturl (). toString (); System.out.println ("URL:" +url); out.println ("URL:" +url+ "<br>");//get uristring URI = Request.getrequesturi (); System.out.println ("uri:" +uri); Out.println ("uri:" +uri+ "<br>");//Get parameter string query_string = Request.getquerystring (); System.out.println ("QueryString:" +query_string); Out.println ("QueryString:" +query_string+ "<br>");// Obtain the IP address of the requesting party//can be used to block some ipstring remote_addr = Request.getremoteaddr (); System.out.println ("remoteaddr:" +remote_addr); Out.println ("Remoteaddr:" +remote_addr+ "<br>");// Gets the full hostname of the requestor string remote_host = Request.getremotehost (); System.out.println ("RemoteHost:" +remote_host); Out.println ("RemoteHost:" +remote_host+ "<br>");// Gets the requestor's network port number int remote_port = Request.getremoteport (); System.out.println ("RemotePort:" +remote_port); Out.println ("RemotePort:" +remote_port+ "<br>");// Gets the network port number used by the server native int local_port = Request.getlocalport (); System.out.println ("LocalPort:" +local_port); Out.println ("LocalPort:"+local_port+" <br> ");//Get the server native IP address string local_addr = Request.getlocaladdr (); System.out.println ("LOCALADDR:" +local_addr); Out.println ("Localaddr:" +local_addr+ "<br>");// Gets the hostname of the server native string local_name = Request.getlocalname (); System.out.println ("LocalName:" +local_name); Out.println ("LocalName: +local_name+" <br> ");
Browser Run Results:

======================================================================================

Common applications of HttpServletRequest

--------------------------------------------------------------------------------------------------------------- -------------------------------------

1. Get the client request header

GetHeader method gets the content of a header Getheaders method (if the header name is the same, return enumeration, use less) Getheadernames method to get all the HTTP message headers
Test:

GetHeader the message header to obtain information//such as hoststring host = Request.getheader ("host") to get the HTTP request; System.out.println ("Host:" +host); System.out.println ("-----------------");//getheadernames method gets all the message headers//requirements: Please get all the messages for the entire HTTP request enumeration<string > headers= request.getheadernames (); while (Headers.hasmoreelements ()) {//takes out the name of the message header string headername = Headers.nextelement (); System.out.println (headername+ ":" + Request.getheader (Headername));}

Server Output results:

host:localhost:8080-----------------Host:localhost:8080connection:keep-alivecache-control:max-age=0accept:text /html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8upgrade-insecure-requests:1user-agent: mozilla/5.0 (Windows NT 10.0; WOW64) applewebkit/537.36 (khtml, like Gecko) chrome/48.0.2564.116 safari/537.36accept-encoding:gzip, deflate, sdchaccept-language:zh-cn,zh;q=0.8
----------------------------------------------------------------------------------------------------------- -----------------------------------------
2. Get Client request Parameters

GetParameter method Getparametervalues (String name) Getparameternames () method
Here, the GetParameter method returns a parameter with only one value, and the Getparametervalues method returns a parameter that can have more than one value, such as the option to get a check box.

Case: Gets the content that the user submits through the form.
Interface section:

public void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException { Response.setcontenttype ("Text/html;charset=utf-8"); PrintWriter out = Response.getwriter (); Out.println ("<! DOCTYPE HTML public \ "-//W3C//DTD HTML 4.01 transitional//en\" > ") out.println (" <HTML> "); Out.println (" < Head><title>form</title>Servlet code to receive information:

public void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException { Request.setcharacterencoding ("Utf-8"); Response.setcontenttype ("Text/html;charset=utf-8"); PrintWriter out = Response.getwriter (); String u = request.getparameter ("username"); String p = request.getparameter ("pwd"); String sex = request.getparameter ("sex");//If you receive the contents of a check box, you should use getparametervalues//if the check box does not have a selection, it returns NULL. So the following is to be judged by string hobbies[] = request.getparametervalues ("hobby"); String City = Request.getparameter ("city"); String intro = Request.getparameter ("Intro"); String hidden1 = Request.getparameter ("Hidden1"); Out.println ("Username:" +u+ "<br>"); Out.println ("Secret   Code:" +p+ " <br> out.println ("Sex   not:" +sex+ "<br>"); if (hobbies = = null) {OUT.PRINTLN ("You don't have a hobby <br>");} ELSE{OUT.PRINTLN ("Your hobby has:<br>"); Out.println ("<ul>"); for (int i=0;iOperation Result:

After submission:



--------------------------------------------------------------------------------------------------------------- -------------------------------------
3. Implement Request Forwarding

Request forwarding refers to a Web resource that receives a client request and notifies the server to invoke another Web resource for processing.
Request forwarding must be distinguished from the request redirection indicated by Httpservletresponse.sendredirect!

Once a Web resource receives a client request, it notifies the server to call another Web resource for processing, called request forwarding
Once a Web resource receives a client request, it notifies the browser to access Another Web resource, called a request redirection.
The HttpServletRequest object provides a Getrequestdispatcher method that returns a RequestDispatcher object that calls the ForWord method of the object to enable request forwarding.

So what is called request forwarding? What if we are going to take the data to the next page in the way that request forwarding? Take a look at the following example:

If our project has three Servlets, login, Servlet1, and Servlet2,servlet1 receive the data from the login form post, and then the request is forwarded to the Servlet2 for processing.

Login's Code:

public void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException { Response.setcontenttype ("Text/html;charset=utf-8"); PrintWriter out = Response.getwriter ();//Returns an interface Out.println ("<! DOCTYPE HTML public \ "-//W3C//DTD HTML 4.01 transitional//en\" > ") out.println (" <HTML> "); Out.println (" < Head><title>loginservlet</title>Servlet1 's Code:
public void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException { Response.setcontenttype ("Text/html;charset=utf-8"); Request.setcharacterencoding ("Utf-8");//Receive user name string u = Request.getparameter ("username");//Put u into the request domain object Request.setattribute ("username", u);// Represents the use of forwarding methods to pass the request and response objects to the next servlet//here without the Web app name Request.getrequestdispatcher ("/servlet2"). Forward ( request, response);}
Servlet2 's Code:

public void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException { Response.setcontenttype ("Text/html;charset=utf-8"); PrintWriter out = Response.getwriter (); String u = Request.getattribute ("username"). toString (); Out.println ("The user name received is:" +u);
As you can see, SERVLET1 receives data passed by login, then puts the data into the request domain object, and then passes the request object and the response object to the Servlet2 using the forward method, that is, The request object and the response object in Servlet2 are in fact Servlet1.

This interaction can be understood through the following sequence diagram:



As you can see from the time series diagram, the browser only makes one request and receives a result. The forwarding process from Servlet1 to Servlet2 only happens inside the server, and the browser does not know. So, the browser's address bar should stay in Http://localhost:8080/RequestTest/Servlet1, in fact, no matter how many times the server internal forwarding, the browser will not know, its address bar will not change, All of this is happening inside the server.

In contrast to Sendredirect request redirection, the request redirection is the Web resource that the server tells the browser to access next, and the browser receives the notification to request the resource, which is two different requests from the browser, so the address bar also changes.

Here's what to note:

1. Use forward to not forward URLs outside of the Web App.
2. Because forward occurs on a Web server, not a browser, SERVLET1 and Servlet2 use the same request and response object.
3. Use the Sendredirect () method to pass an attribute to the next servlet through the Request.setattribute () method. Obviously, this is two different requests, the request object is not the same, how can pass the data through request.

--------------------------------------------------------------------------------------------------------------- -------------------------------------

Here 's a summary of the differences between request redirection (Sendredirect) and request forwarding:
"1" The Requestdispatcher.forward method can only forward requests to components in the same web app, while the Httpservletresponse.sendredirect method also redirects resources to other applications on the same site, even using absolute URL redirection Resources to other sites.
"2" If the relative URL passed to the Httpservletresponse.sendredirect method begins with "/", it is relative to the root of the entire Web site, and the relative URL specified when the RequestDispatcher object is created starts with "/" , which is relative to the root directory of the current Web application.
"3" After the access process that calls the Httpservletresponse.sendredirect method redirects, the URL displayed in the browser's address bar changes, changing from the initial URL address to the target URL of the redirect, and the request to the Requestdispatcher.forward method is forwarded The browser address bar keeps the initial URL address intact after the process is finished.
"4" The Httpservletresponse.sendredirect method responds directly to the request of the browser, and the result of the response is to tell the browser to re-issue the access request to the other URL, and the Requestdispatcher.forward method forwards the request to another server-side A resource, the browser only knows that a request has been made and has received a response, and does not know that a forwarding behavior has occurred inside the server program.
"5" The caller of the Requestdispatcher.forward method shares the same request object and the response object as the callee, which belong to the same access request and response process, while the Httpservletresponse.sendredirect method caller and the The caller uses the respective request object and the response object, which belong to two separate access request and response procedures.

Servlet--httpservletrequest Object Explanation

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.