Httpservletrequest
The httpservletrequest object represents the client's request. When the client accesses the server through the HTTP protocol, all information in the HTTP request header is encapsulated in this object. The developer uses this object method, obtain the customer's information.
Common Request Methods
LObtain client information
•The getrequesturl method returns the complete URL when the client sends a request.
•The getrequesturi method returns the resource name in the request line.
•The getquerystring method returns the parameters in the request line.
•The getremoteaddr method returns the IP address of the client sending the request.
•The getremotehost method returns the complete host name of the client sending 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.
•Getmethod
Relationship between URL and Uri: URI is the URL parent class. Uri describes resources and URL describes Internet resources.
String url = request. getrequesturl (). tostring ();
System.Out. Println (URL );
System.Out. Println (request. getrequesturi ());
System.Out. Println (request. getquerystring ());
System.Out. Println (request. getremoteaddr ());
System.Out. Println (request. getremotehost ());
System.Out. Println (request. getremoteport ());
System.Out. Println (request. getmethod ());
Common Request Methods
LObtain the client request header
•Gethead (name) Method
• Getheaders (string name) Method
• Getheadernames Method
L obtain the client request parameters (data submitted by the client)
• Getparameter (name) Method
• Getparametervalues (string name) Method
• Getparameternames Method
• Getparametermap method //
• Getinputstream
Obtain data from the client
String username = request. getparameter ("username ");
System.Out. Println (username );
System.Out. Println ("----------------------");
EnumerationE = request. getparameternames ();
While(E. hasmoreelements ()){
String name = (string) E. nextelement ();
String value = request. getparameter (name );
System.Out. Println (name + "=" + value );
}
System.Out. Println ("----------------------");
String values [] = request. getparametervalues ("username ");
For(IntI = 0; values! =Null& I <values. length; I ++ ){
System.Out. Println (Values [I]);
}
System.Out. Println ("----------------------");
// Http: // localhost: 8080/day05/servlet/requestdemo3? Username = aaa & username = BBB & Password = 123
Map <string, string []> map =Request. getparametermap ();
Set <map. Entry <string, string []> set = map. entryset ();
For(Map. Entry <string, string []> entry: Set ){
Username = entry. getkey ();
Values = entry. getvalue ();
For(IntI = 0; values! =Null& I <values. length; I ++ ){
System.Out. Println (username + "=" + values [I]);
}
}
Common Request applications 1
LAnti-leech
String Referer = request. getheader ("Referer ");
If(Referer =Null|! Referer. startswith ("http: // localhost ")){
Response. sendredirect ("/day05/index.html ");
Return;
}
String data = "Fengjie Diary ";
Response. setcharacterencoding ("UTF-8 ");
Response. setheader ("Content-Type", "text/html; charset = UTF-8 ");
Response. getwriter (). Write (data );
L data acquisition of various form input items
• Text, password, radio, checkbox,
• File, select, textarea, hidden,
• Image and button for JS Programming
Package CN. itcast. request;
Import java. Io. ioexception;
Import java. util. arrays;
Import javax. servlet. servletexception;
Import javax. servlet. http. httpservlet;
Import javax. servlet. http. httpservletrequest;
Import javax. servlet. http. httpservletresponse;
// Obtain data of different forms (obtain data submitted by client forms)
Public class requestdemo5 extends httpservlet {
Publicvoid doget (httpservletrequest request, httpservletresponse response)
Throws servletexception, ioexception {
System. Out. println (request. getparameter ("username "));
System. Out. println (request. getparameter ("password "));
System. Out. println (request. getparameter ("gender "));
System. Out. println (arrays. aslist (request. getparametervalues ("like") = NULL? Newstring [] {}: request. getparametervalues ("like ")));
System. Out. println (request. getparameter ("city "));
System. Out. println (request. getparameter ("resume "));
System. Out. println (request. getparameter ("XX "));
String username = request. getparameter ("username"); // "" null
If (username = NULL | username. Trim (). Equals ("")){
System. Out. println ("You have not submitted data ");
}
Request. getparameter ("gender"); // null
Request. getparametervalues ("like"); // null
}
Publicvoid dopost (httpservletrequest request, httpservletresponse response)
Throws servletexception, ioexception {
Doget (request, response );
}
}
Form:
<! Doctype HTML public "-// W3C // dtdhtml 4.01 transitional // en">
<HTML>
<Head>
<Title> form.html </title>
<Meta http-equiv ="Keywords"Content ="Keyword1, keyword2, keyword3">
<Meta http-equiv ="Description"Content ="This is my page">
<Meta http-equiv ="Content-Type"Content ="Text/html; charset = UTF-8">
<! -- <LinkREL="Stylesheet"Type =" text/CSS"
Href= "./Styles.css"> -->
</Head>
<Body>
<Form action ="/Day05/servlet/requestdemo5"Method ="Post">
Username: <input type ="Text"Name ="Username"> <Br/>
Password: <input type ="Password"Name ="Password"> <Br/>
Gender: <input type ="Radio"Name ="Gender"Value ="Male"> Male
<Input type ="Radio"Name ="Gender"Value ="Female"> Female
<Br/>
Hobbies: <input type ="Checkbox"Name ="Like"Value ="Basketball"> Blue ball
<Input type ="Checkbox"Name ="Like"Value ="Football"> Football
<Input type ="Checkbox"Name ="Like"Value ="Java"> JAVA
<Input type ="Checkbox"Name ="Like"Value =". Net">. Net
<Br/>
Location: <select name ="City">
<Option value ="BJ"> Beijing </option>
<Option value ="Sh"> Shanghai </option>
<Option value ="CS"> Changsha </option>
</SELECT> <br/>
Resume: <textarea rows ="5"Cols ="60"Name ="Resume"> </Textarea> <br/>
Big photo: <input type ="File"Name ="Image"> <Br/>
<Input type ="Hidden"Name ="XX"Value ="Yyy">
<Input type ="Submit"Value ="Submit">
</Form>
<Form action ="/Day05/servlet/requestdemo6"Method ="Get">
Username: <input type ="Text"Name ="Username"> <Br/>
<Input type ="Submit"Value ="Submit">
</Form>
<Form action ="/Day05/servlet/requestdemo7"Method ="Post">
Username: <input type ="Text"Name ="Username"> <Br/>
<Input type ="Submit"Value ="Submit">
</Form>
<! -- The link must be followed by Chinese DataURLEncoding -->
<A href ="/Day05/servlet/requestdemo8? Name = Fang lixun"> Point </a>
</Body>
</Html>
If none of them are added or selected, the input item defaults to an empty string "", and the selection item is null.
Therefore, we recommend that you use this method for comparison and determination: If (username = NULL | username. Trim (). Equals ("")){
LChinese garbled characters in Request Parameters
Importjava. Io. ioexception;
Importjavax. servlet. servletexception;
Importjavax. servlet. http. httpservlet;
Importjavax. servlet. http. httpservletrequest;
Importjavax. servlet. http. httpservletresponse;
// Request garbled: Get \ post
Public classrequestdemo6 extends httpservlet {
Public void doget (httpservletrequest request, httpservletresponseresponse)
Throwsservletexception, ioexception {
// The following code solves the garbled characters in post submission.
Request. setcharacterencoding ("UTF-8"); // valid only for post Mode
// String username1 = request. getparameter ("username ");
// System. Out. println (username1 );
// The following code may solve the garbled characters submitted by get.
String username2 = request. getparameter ("username ");
// Username2 = newstring (username2.getbytes ("iso8859-1"), "UTF-8 ");
System. Out. println (username2 );
}
Public void dopost (httpservletrequest request, httpservletresponse response)
Throwsservletexception, ioexception {
Doget (request, response );
}
}
Importjava. Io. ioexception;
Importjavax. servlet. servletexception;
Importjavax. servlet. http. httpservlet;
Importjavax. servlet. http. httpservletrequest;
Importjavax. servlet. http. httpservletresponse;
// Thinking question: is there any garbled Code in the following program ????
Public classrequestdemo7 extends httpservlet {
Public void doget (httpservletrequest request, httpservletresponseresponse)
Throwsservletexception, ioexception {
Request. setcharacterencoding ("UTF-8 ");
String username = request. getparameter ("username"); // Fang Li
Response. setcharacterencoding ("gb2312 ");
Response. setcontenttype ("text/html; charset = gb2312 ");
Response. getwriter (). Write (username );
}
Public void dopost (httpservletrequest request, httpservletresponse response)
Throwsservletexception, ioexception {
Doget (request, response );
}
}
LURL address Encoding
Import java. Io. ioexception;
Import javax. servlet. servletexception;
Import javax. servlet. http. httpservlet;
Importjavax. servlet. http. httpservletrequest;
Import javax. servlet. http. httpservletresponse;
// The hyperlink submits the code obtained from the server for Chinese data.
/*
* <! -- URL encoding is required for the link containing Chinese data. -->
<A href = "/day05/servlet/requestdemo8? Name = Fang lixun "> point </a>
*
*/
Public class requestdemo8 extendshttpservlet {
Publicvoid doget (httpservletrequest request, httpservletresponse response)
Throws servletexception, ioexception {
Stringname = request. getparameter ("name ");
Name = new string (name. getbytes ("iso8859-1"), "UTF-8 ");
System. Out. println (name );
}
Publicvoid dopost (httpservletrequest request, httpservletresponse response)
Throws servletexception, ioexception {
Doget (request, response );
}
}
Common Request applications 2
Lrequest object implements request forwarding: A web resource notifies the server to call another web resource for processing after receiving a client request.
L Application Scenario of request forwarding: MVC design mode
The lrequest object provides a getrequestdispatcher method, which returns a requestdispatcher object. The forward method of this object can be called to forward requests.
The lrequest object is also a domain object. When the request object is forwarded, the developer sends the data through the request object to other web resources for processing.
Setattribute Method
Getattribute Method
Removeattribute Method
Getattributenames Method
* Request forwarding features:
* 1. Request forwarding only sends one request to the browser, and the address bar of the browser will not change.
* 2. Under request forwarding, the server will only create one request response
*
* Application scenarios of request forwardingMVCDesign Mode
* InMVCIn the design modeServletProcess the request. After processing the data generated by the request,ServletThe data is stored in the request domain and then forwardedJSPDisplay
*
String data = "aaaa ";
Request. setattribute ("data", data );
Request. setattribute ("data", data );
Requestdispatcher RD = request. getrequestdispatcher ("/view. jsp ");
Rd. Forward (request, response );
Request forwarding details
The lforward method is used to forward requests to resources encapsulated by the requestdispatcher object.
L if part of the content written in the servlet program has been actually transmitted to the client before the forward method is called, the forward method will throw an illegalstateexception.
L if the content written to the Servlet Engine Buffer (response) before the forward method is called, as long as the content written to the buffer is not actually output to the client, the forward method can be executed normally. The content originally written to the output buffer is cleared, but the response header field information written to the httpservletresponse object remains valid.
String data = "AAA ";
Response. getwriter (). Write (data); // the browser will not see the output of this data
Request. getrequestdispatcher ("/index. jsp"). Forward (request, response );
String data2 = "BBB ";
Response. getwriter (). Write (data2); // the browser will not see the output of this data
Difference between request redirection and request forwarding
L after a Web Resource receives a request from the client, it notifies the server to call another web resource for processing, which is called request forwarding.
L after a Web Resource receives a request from the client, it notifies the browser to access another web resource, which is called request redirection.
Lrequestdispatcher. the forward method can only forward requests to components in the same web application, while httpservletresponse. the sendredirect method can also redirect resources from other applications on the same site, or even resources from other sites using absolute URLs.
L if it is passed to httpservletresponse. the relative URL of the sendredirect method starts with "/", which is the root directory relative to the entire web site. If the relative URL specified when the requestdispatcher object is created starts, it is relative to the root directory of the current web application.
L call httpservletresponse. after the access process of sendredirect method redirection ends, the URL displayed in the address bar of the browser changes from the initial URL address to the destination URL of the redirection. Call requestdispatcher. after the request forwarding process of the forward method is completed, the initial URL address remains unchanged in the browser address bar.
Lhttpservletresponse. the sendredirect method directly responds to browser requests. The response result is to tell the browser to re-send an access request to another URL; requestdispatcher. the forward method forwards the request to another resource on the server. The browser only knows that the request is sent and the response result is returned, but does not know that the forwarding behavior occurs in the server program.
Lrequestdispatcher. the callers and callers of the forward method share the same request object and response object. They belong to the same access request and response process, while httpservletresponse. the sendredirect method callers and callers use their respective request objects and response objects. They belong to two independent access requests and response processes.
Requestdispatcher
LInclude method:
• The requestdispatcher. Include method is used to include the resource content encapsulated by the requestdispatcher object as part of the current response content to implement programmable server-side inclusion.
• The contained servlet program cannot change the status code and response header of the Response Message. If such a statement exists in it, the execution results of these statements will be ignored.
// Dynamic inclusion
Request. getrequestdispatcher ("/servlet/headservlet"). Include (request, response );
String data = "AAA <br/> ";
Response. getwriter (). Write (data );
Request. getrequestdispatcher ("/servlet/footservlet"). Include (request, response );
"\" Usage in the project:
The "\" on the server represents the web application, and the client represents the entire website.
This. Getservletcontext (). getrealpath ("/download/ .jpg ");
This. Getservletcontext (). getresourceasstream ("/download/ .jpg ");
Request. getrequestdispatcher ("/login.html ");
Response. sendredirect ("/day05/index. jsp ");
/*
<Href= "/Day05/message. jsp"> point </a>
<Form action = "/day05/Servlet/Footservlet ">
</Form>
SRC= "/Day05/Download/Japanese New Zealand.JPG">
*/
}