Javaweb---Summary (10) HttpServletRequest object (i)

Source: Internet
Author: User
Tags html form

I. Introduction of HttpServletRequest

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 through the methods provided by this object, all the information requested by the client can be obtained.

Second, the request common method 2.1, obtains the client information

  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 parameters section in the request line.
The GetPathInfo method returns additional path information in the request URL. The additional path information is the content in the request URL that precedes the servlet's path and before the query parameter, beginning with "/".
  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.
The Getremoteport method returns the network port number used by the client.
The Getlocaladdr method returns the IP address of the Web server.
The Getlocalname method returns the host name of the Web server.

Example: Obtaining client request information through the Request object

 1 package gacl.request.study; 2 Import java.io.IOException; 3 Import Java.io.PrintWriter; 4 Import javax.servlet.ServletException; 5 Import Javax.servlet.http.HttpServlet; 6 Import Javax.servlet.http.HttpServletRequest; 7 Import Javax.servlet.http.HttpServletResponse;  8/** 9 * @author GACL10 * Obtain client request information through the Request object */12 public class RequestDemo01 extends HttpServlet { void Doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException { /**17         * 1. Obtaining client information */19 String Requesturl = Request.getrequestur  L (). toString ();//Gets the requested URL address of the string requesturi = Request.getrequesturi ();//Gets the requested resource, string queryString =         Request.getquerystring ();//The parameter that is included in the requested URL address is String remoteaddr = request.getremoteaddr ();//Get the IP address of the caller 23 String remotehost = Request.getremotehost (), RemotePort int = Request.getremoteport (), and string remoteUser = Request.getremoteuser ();-String method = Request.getmethod ();//The method used to obtain the requested URL address, string pathInfo = Request.getpathinfo (); string localaddr = Request.getlocaladdr ();//Gets the IP address of the Web server, string localname =         Request.getlocalname ();//Gets the host name of the Web server response.setcharacterencoding ("UTF-8");//Set the character to output "UTF-8" to client browser 31 By setting the response header control browser to UTF-8 encoding display data, if not add this sentence, then the browser will display is garbled Response.setheader ("Content-type", "Text/html;charset=utf-8") ; PrintWriter out = Response.getwriter (); Out.write ("The client information obtained is as follows:"); Out.write ("

Operation Result:

  

2.2. Obtain the client request header

GetHeader (String name) method: string
Getheaders (String Name) method: Enumeration
Getheadernames () method

Example: obtaining client request header information through the Request object

 1 package gacl.request.study; 2 Import java.io.IOException; 3 Import Java.io.PrintWriter; 4 Import java.util.Enumeration; 5 Import javax.servlet.ServletException; 6 Import Javax.servlet.http.HttpServlet; 7 Import Javax.servlet.http.HttpServletRequest; 8 Import Javax.servlet.http.HttpServletResponse;     9/**10 * @author GACL11 * Get client request header Information 12 * Client request Header: * */15 public class RequestDemo02 extends HttpServlet {16 17 public void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, Ioex ception {response.setcharacterencoding ("UTF-8");//Set the character to "UTF-8" encoding output to client browser 20//By setting the response header to control the number of encoded displays in the browser to UTF-8 According to Response.setheader ("Content-type", "Text/html;charset=utf-8"); PrintWriter out = Response.getwriter ( ); enumeration<string> Reqheadinfos = Request.getheadernames ();//Get all Request headers for out.write ("Get all of the clients to the The header information is as follows: "); Out.write (" 

The results of the operation are as follows:

  

2.3. Obtain the client request parameters (data submitted by the client)
    • GetParameter (String) method (Common)

    • Getparametervalues (String name) method (Common)

    • Getparameternames () method ( not commonly used )

    • Getparametermap () method (often used for writing frames)

For example, now you have the form form below

 1 <%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%> 2 <! DOCTYPE HTML public '-//w3c//dtd HTML 4.01 transitional//en ' > 3 

Fill in the form with the data, and then submit it to RequestDemo03, the servlet for processing, and fill in the forms with the following data:

  

Use the GetParameter method and the Getparametervalues method on the server side to receive the form parameters, as follows:

1 package gacl.request.study; 2 Import java.io.IOException; 3 Import Java.text.MessageFormat; 4 Import javax.servlet.ServletException; 5 Import Javax.servlet.http.HttpServlet; 6 Import Javax.servlet.http.HttpServletRequest; 7 Import Javax.servlet.http.HttpServletResponse;  8/** 9 * @author Gacl10 * Gets the parameters that the client submits through the form form */12 public class RequestDemo03 extends HttpServlet {All public void Doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {          16//client is the UTF-8 code to submit form data, so you need to set the server side to UTF-8 code to receive, otherwise the Chinese data will produce garbled request.setcharacterencoding ("UTF-8"); 18 /**19 * &nbsp;&nbsp; (text box): <input type= "text" name= "userid" Value= "No." Size= " 2 "maxlength=" 2 ">21 */22 String userid = Request.GetParameter("userid");//Get fill in the number, UserID is the name of the text box, <input type= "text" name= "userid" >23/**24 * username (text box): <input t Ype= "text" name= "username" value= "Please enter user name" >25 */26 String username = request.getparameter ("username"); /Get filled in username 27/**28 * Secret &nbsp;&nbsp; Code (password box): <input type= "password" name= "userpass" value= "Please enter password" &G t;29 */30 String userpass = Request.getparameter ("Userpass");//Gets the password filled in string sex = Request.get Parameter ("Sex");//Gets the selected gender by String dept = request.getparameter ("dept");//Gets the selected Department 33//Gets the selected interest because multiple values can be selected, so The obtained value is an array of strings, so you need to use the Getparametervalues method to get the string[] insts = Request.getparametervalues("inst"); string note = Request.getparameter ("note");//Get fill in the description information of the string HiddenField = Request.getparam Eter ("HiddenField");//Gets the contents of the hidden field. inststr= "";/**40         * Get array Data tips to avoid NULL pointer exceptions thrown when the insts array is null! */42 for (int i = 0; Insts!=null && i < insts.length; i++) {if (i = = INSTS.L ength-1) {inststr+=insts[i];45}else {inststr+=insts[i]+ ",";   & nbsp                                    }48        }49 String htmlstr = "<table>" +51                             "<tr><td> Fill in number:</td><td>{0}</td></tr>" +52 "<tr><td> username:</td><td>{1}</td></tr>" +53 "&lt ;tr><td> fill in the password:</td><td>{2}</td></tr> "+54" &LT;tr><td> selected gender:</td><td>{3}</td></tr> "+55" <tr><td& gt; Selected department:</td><td>{4}</td></tr> "+56" <tr><td> selected interest: </t D><td>{5}</td></tr> "+57" <tr><td> fill in the instructions:</td><td> {6}</td></tr> "+58" <tr><td> hidden field contents:</td><td>{7}</td> </tr> "+59" </table> "htmlstr = Messageformat.format (Htmlstr, Userid,userna Me,userpass,sex,dept,inststr,note,hiddenfield) response.setcharacterencoding ("UTF-8");//set server side to UTF-8 Encode output data to client Response.setcontenttype ("Text/html;charset=utf-8");//Set client browser to parse data UTF-8 encoding Response.getwrite R (). write (htmlstr);//output HTMLSTR contents to client browser display   &NBSP;}66 (httpservletrequest request, HTT Pservletresponse responsE) throws Servletexception, IOException {       doget (request, response); &NBSP;}71}

The results of the operation are as follows:

  

Use the Getparameternames method on the server side to receive the form parameters, the code is as follows:

1 enumeration<string> paramnames = Request.getparameternames ();//Get all parameter names 2 while         ( Paramnames.hasmoreelements ()) {3             string name = Paramnames.nextelement ();//Get parameter name 4             String value = Request.getparameter (name);//Gets the corresponding value by the parameter name 5             System.out.println (Messageformat.format ("{0}={1}", Name,value)); 6         }

The results of the operation are as follows:

  

Use the Getparametermap method on the server side to receive the form parameters, the code is as follows:

1 The parameters encapsulated by the//request object are 2 map<string stored as Map         , string[]> parammap = Request.getparametermap (); 3 for         ( Map.entry<string, string[]> Entry:p arammap.entryset ()) {4             string paramname = Entry.getkey (); 5             string Paramvalue = ""; 6             string[] Paramvaluearr = Entry.getvalue (); 7 for             (int i = 0; Paramvaluearr!=null && i < Paramvaluearr . length; i++) {8                 if (i = = paramvaluearr.length-1) {9                     paramvalue+=paramvaluearr[i];10                 }else {                     paramvalue+= Paramvaluearr[i]+ ",";  }13  }14             System.out.println (Messageformat.format ("{0}={1}" , Paramname,paramvalue));         

The results of the operation are as follows:

  

Third, request to receive the form to submit the Chinese parameter garbled problem 3.1, the Post method to submit the form Chinese parameter garbled problem

For example, a form page that resembles the following:

1 <%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%> 2  3 <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" > 4 

  

In this case, the server side to receive Chinese parameters will appear in Chinese garbled, as follows:

  

3.2, post method to submit Chinese data garbled causes and solutions

  

You can see that the reason is garbled, because the server and client communication is inconsistent with the encoding, so the solution is to set a unified code between the client and the server, followed by this encoding for data transmission and reception.

Because the client transmits the form data to the server side with the UTF-8 character encoding, the server also needs to be set to receive UTF-8 character encoding, and to do so, the server can directly use the inherited from the ServletRequest interface. Setcharacterencoding (CharSet) "Method for uniform encoding settings. The modified code is as follows:

1 public void DoPost (HttpServletRequest request, httpservletresponse response) 2             throws Servletexception, IOException {3         /**4  * Client is UTF-8 encoding to transmit data to the server side, so you need to set up the server side to receive UTF-8 encoding, otherwise the Chinese data will be garbled 5          */6          Request.setcharacterencoding ("UTF-8"); 7         String userName = Request.getparameter ("UserName"), 8         System.out.println ("UserName:" +username); 9}

Use request.setcharacterencoding ("UTF-8"); After setting up the server to receive data in UTF-8 encoding, there is no Chinese garbled problem at this point, as follows:

  

3.3, to get the form to submit forms Chinese parameter garbled problem

For example, a form page that resembles the following:

1 <%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%> 2  3 <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" > 4 

  

In this case, the server side to receive Chinese parameters will appear in Chinese garbled, as follows:

  

Then this Chinese garbled question how to solve, whether can pass request.setcharacterencoding ("UTF-8"); set up the server to receive UTF-8 encoding to solve the problem of Chinese garbled, note that For the Chinese data transmitted in Get mode, through Request.setcharacterencoding ("UTF-8"), this method can not solve the Chinese garbled problem, as follows:

  

3.4, get the way to submit Chinese data garbled causes and solutions

For data transmitted in a Get mode, the request is not valid even if it is set to receive data in the specified encoding (as to why it is not valid I do not understand), the default is to use the Iso8859-1 character encoding to receive data, the client to UTF-8 encoding to transmit data to the server side, The server-side Request object uses the Iso8859-1 character encoding to receive the data, the server and client communication encoding inconsistent so it will produce garbled Chinese. Workaround: After receiving the data, get the request object to Iso8859-1 character encoding to receive the original data byte array, and then through the byte array with the specified encoding to build a string, to solve the garbled problem. the code is as follows:

1 public void doget (HttpServletRequest request, httpservletresponse response) 2             throws Servletexception, IOException {3         /** 4  * 5  * For data transmitted in a Get mode, the request is invalid even if it is set to receive data in the specified encoding, and the default is to use the Iso8859-1 character encoding to connect Data received 6          *         /7 String name = Request.getparameter ("name");// receive data 8         name =new string (Name.getbytes (" Iso8859-1 ")," UTF-8 ");// Gets a byte array of the original data received by the request object in Iso8859-1 character encoding, and then constructs a string with the specified encoding through a byte array to solve garbled problems  9             System.out.println ("Name:" +name); 10}

The results of the operation are as follows:

3.5, in the form of hyperlinks to pass the Chinese parameter garbled problem

The client wants to transfer the data to the server, either through form submission or by adding parameters to the hyperlink, for example:

1 <a href= "${pagecontext.request.contextpath}/servlet/requestdemo05username=gacl&name= 徐达沛" > Click </a>

Click the hyperlink, the data is transferred to the server in a get, so the reception of Chinese data will also produce Chinese garbled problem, and the way to solve the Chinese garbled problem with the above to submit form Chinese data garbled processing problems in the same way, as follows:

1 String name = Request.getparameter ("name"), 2 name =new String (name.getbytes ("iso8859-1"), "UTF-8");

In addition, it is necessary to mention that the URL after the address if the Chinese data, then the Chinese parameter is best to use URL encoding for processing , as follows:

1 <a href= "${pagecontext.request.contextpath}/servlet/requestdemo05?username=gacl&name=<%= Urlencoder.encode (" Xu Da", "UTF-8")%> "> Click </a>
3.6, the submission of Chinese data garbled problem summary

1, if the submission method is post, want to not garbled, only need to set the Request object encoding on the server side, the client is submitted by which encoding, the server-side Request object is received by the corresponding code, such as the client is submitted by UTF-8 encoding, Then the server-side Request object is received in UTF-8 encoding (request.setcharacterencoding ("UTF-8"))

2, if the submission method is get, set the encoding of the request object is not valid, the request object or the default iso8859-1 encoding to receive data, so to not garbled, only after receiving data and then manually converted, the steps are as follows:

1). Get the data from the client submission, get the garbled string, data= "??? È????? "

String data = Request.getparameter ("paramname");

2). Find the Iso8859-1 Code table and get a byte array of raw data submitted by the client

byte[] Source = data.getbytes ("iso8859-1");

3). Build a string with the specified encoding through a byte array to resolve garbled characters

data = new String (source, "UTF-8");

Constructs a string with the specified encoding through a byte array, where the encoding specified is based on the character encoding used when the client submits the data, and if it is GB2312, it is set to data = new string (Source, " GB2312 "), if it is UTF-8, then set to data = new String (source," UTF-8 ")

Javaweb---Summary (10) HttpServletRequest object (i)

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.