JSP nine large built-in objects __jsp

Source: Internet
Author: User
Tags int size locale session id unique id
Built-in objects:
Request,response,out,session,application,cookie,config,page,exception.

1. Request Object

This object encapsulates the information submitted by the user, and it is possible to obtain the encapsulated information by calling the object's corresponding method, that is, using the object to
Gets the information submitted by the user.
When the request object gets the characters submitted by the customer, there will be garbled problems and special treatment must be done. First, you will get the
The string is encoded with iso-8859-1 and encodes the island into a byte array, then converts the array to a string object
Can. As follows:

String textcontent=request.getparameter ("Boy");
Byte b[]=textcontent.getbytes ("Iso-8859-1");
Textcontent=new String (b);

Common methods to request:
1.01 getparameter (String strtextname) Gets the information submitted by the form.

String strname=request.getparameter ("name");

1.02 Getprotocol () Gets the protocol used by the customer.

String Strprotocol=request.getprotocol ();

1.03 Getservletpath () Gets the page where the customer submits the information.

String Strservlet=request.getservletpath ();

1.04 GetMethod () to obtain the customer submits the information the way, Get|post.

String strmethod = Request.getmethod ();

1.05 Getheade () Gets the values of accept, accept-encoding, and host in the HTTP header file.

String Strheader = Request.getheader ("accept");

1.06 getrermoteaddr () Gets the client's IP address.

String StrIP = Request.getremoteaddr ();

1.07 Getremotehost () Gets the name of the client.

String clientname = Request.getremotehost ();

1.08 getServerName () gets the server name.

String serverName = Request.getservername ();

1.09 Getserverport () Gets the port number of the server.

int serverport = Request.getserverport ();

1.10 Getparameternames () Gets the name of all the parameters submitted by the client.

enumeration enum = Request.getparameternames ();
while (Enum.hasmoreelements ()) {
String s= (String) enum.nextelement ();
Out.println (s);
}

2, Response object

Respond dynamically to customer requests and send data to the client.
2.1 Dynamic Response ContentType Properties
When a user accesses a JSP page, the JSP engine responds according to the property value if the page is text/html with the page instruction to set the ContentType property. If you want to dynamically change this property value to respond to the customer, you need to use the Response object's setContentType (String s) method to change the ContentType property value.
Format: Response.setcontenttype (String s);
Parameter s are preferable to text/html,application/x-msexcel,application/msword and so on.
2.2 Response redirect
In some cases, when responding to a customer, you need to reboot the customer to another page, and you can use the response Sendredirect (URL) method to achieve customer redirection. For example:

Response.sendredirect ("index.jsp");

3. Session Object


(1) What is the Session object
The session object is a JSP built-in object that is automatically created when the first JSP page is loaded, and is completed for conversation management. From a customer to open the browser and connect to the server to start, to the customer close the browser to leave the server end, is called a session. When a client accesses a server, it may switch between several pages of the server, and the server should somehow know that this is a customer and requires a session object.
(2) The ID of the Session object
When a customer first accesses a JSP page on a server, the JSP engine produces a session object and assigns a string ID number, which the JSP engine sends to the client at the same time, stored in a cookie, so that the session object, The client's session object is canceled on the server side until the client closes the browser, and the conversation relationship with the customer disappears. When the client reopened the browser and then connected to the server, the server creates a new session object for the client.
(3) Common methods of Session object
Public String getId (): Gets the Session object number.
public void setattribute (String key,object obj): Adds the object obj specified by the parameter object to the session object and assigns an index keyword to the added object.
public Object GetAttribute (String key): Gets the object that contains the keyword in the session object.
Public Boolean isnew (): Determine if it is a new customer.


4, Application Object


(1) What is the Application object
This Application object is generated when the server is started, and the Application object is all the same until the server shuts down when the customer browses through the pages of the site visited. However, when different from the session object, all customers have the same application object, that is, all customers share the built-in Application object.
(2) Common methods of application objects
SetAttribute (String key,object obj): Adds the object obj specified by the parameter object to the Application object and assigns an index keyword to the added object.
GetAttribute (String key): Gets the object that contains the keyword in the Application object.


5. Out Objects


An Out object is an output stream that is used to output data to the client. The Out object is used for the output of various data. The usual methods are as follows.
Out.print (): Output various types of data.
Out.newline (): Output a newline character.
Out.close (): Closes the stream.


6. Cookie Object


    (1) What is a cookie
    cookie is a piece of text that the Web server holds on the user's hard disk. Cookies allow a Web site to save information on a user's computer and then retrieve it later.
    For example, a Web site might produce a unique ID for each visitor, and then save it in the form of a cookie file on each user's machine.
    If users use IE to access the Web, users will see all cookies saved on their hard disk. The most common places they store are: c:/windows/cookies. Cookies are saved in the format "keyword key= value".
    (2) Create a Cookie object
    invoke the constructor of a cookie object to create a cookie object. The constructor for the cookie object has two string parameters: the cookie name and the cookie value.
    For example: cookie c = new Cookie ("username", "John");
    (3) Sending a cookie object to the client
    in JSP, if you want to transfer the encapsulated cookie object to the client, You can use the Addcookie () method of the Response object.
    For example: Response.addcookie (c).
    (4) reads cookies saved to the client
    uses the GetCookie () method of the Request object. When executed, the cookie objects from all clients are arranged in an array, and if you want to remove the cookie object that matches your needs, you need to iterate through the keywords for each object in the array.
    For example:

cookie[] C = request.getcookies ();
if (c!= null)
 for (int i = 0;i < c.length;i++) {
       if ("username"). Equals (C.getname ()))
           out.println (C.getvalue ());
   }

(5) Set the valid time of the cookie object
You can set the valid time for a cookie object by calling the Setmaxage () method of the Cookie object.
For example: cookie c = new Cookie ("username", "John");
C.setmaxage (3600);
(6) Cookie Application
A typical application of a cookie object is used to count the number of visitors to the site. Because of the use of proxy servers, caching, and so on, the only way to help the site to accurately count the number of visitors is to create a unique ID for each visitor. With cookies, the site can do the job.
Determine how many people have visited.
Determine how many visitors are new (ie first visits) and how many are old users.
Determine how often a user accesses a Web site
When a user first accesses, the Web site creates a new ID in the database and transmits the ID to the user through a cookie. When the user visits again, the website adds 1 to the counter corresponding to the user ID, and gets the number of visits by the user.

7. config Object


Configuration Object


8, Page Object

The Page object.

PageContext objects

Page Context Object
JSP introduces a fame PageContext class that can access many of the page's properties.
The PageContext class has getrequest,getresponse,getout,getsession and other methods.
The PageContext variable stores the value of the PageContext object associated with the current page.
Fill
If the method needs to access multiple page-related objects,
Passing PageContext is easier than passing independent references such as Request,response,out. (Although both ways can achieve the same goal)

9, Exception object

Exception implicit objects can be accessed directly in a Web page that handles exceptions.

-----------------------------------Supplementary Part--------------------------------

①out-javax.servlet.jsp.jspwriter
The Out object is used to output the results to the Web page.

Method:
1. void clear ();
Clears the contents of the output buffer, but does not output to the client.

2. void Clearbuffer ();
Clears the contents of the output buffer and outputs it to the client.

3. void Close ();
Closes the output stream and clears all content.

4. void Flush ();
The data inside the output buffer.

5. int getbuffersize ();
Gets the current buffer size in kilobytes.

6. int getremaining ();
Gets the amount of space that is not occupied in a buffer in kilobytes.

7. Boolean Isautoflush ();
Whether the buffer is automatically refreshed.

8. void newline ();
Output a newline character.

9. Void Print (Boolean B);
void print (char c);
void print (char[] s);
void print (double d);
void print (float f);
void print (int i);
void print (long L);
void print (Object obj);
void print (String s);
Outputs the specified type of data to the HTTP stream without wrapping.

void println (Boolean B);
void println (char c);
void println (char[] s);
void println (double D);
void println (float f);
void println (int i);
void println (long L);
void println (Object obj);
void println (String s);
Outputs the specified type of data to the HTTP stream and outputs a newline character.

Appendable append (char c);
Appendable Append (charsequence cxq, int start, int end);
Appendable Append (charsequence cxq);
Adds a character or an object that implements the Charsequence interface to the back of the output stream.

Members:
int default_buffer = 0-Default buffer size
int no_buffer = -1-writer is in buffered output state
int unbounded_buffer =-2-Limit buffer size


②request-javax.servlet.http.httpservletrequest
The Request object contains all the requested information, such as the source of the request, headers, cookies, and request-related parameter values.

Method:
1. Object getattribute (String name);
Returns the value of the property specified by name, which returns null if the property does not exist.

2. Enumeration Getattributenames ();
Returns a collection of all the property names for the request object.

3. String Getauthtype ();
Returns the name of the authentication method used to protect the servlet and returns NULL when unprotected.

4. String getcharacterencoding ();
Returns the character encoding method in the request, which can be set in the response object.

5. int getcontentlength ();
Returns the length of the requested body, not 1 when the length is not determined. Can be set in response.

6. String getContentType ();
Returns the type of content defined in response.

7. String Getcontentpath ();
Returns the path of the request.

8. cookie[] GetCookies ();
Returns an array of all cookies for the client.

9. Enumeration Getheadernames ();
Returns a collection of the names of all HTTP headers.

Enumeration Getheaders (String name);
Returns a collection of all values for the specified HTTP header.

A. String GetHeader (string name);
Returns information about the HTTP header for the specified name.

Long Getdateheader (String name);
Returns information for the HTTP header of the data type of the specified name.

Getintheader Int (String name);
Returns information for the HTTP header of the type int of the specified name.

ServletInputStream getInputStream ();
Returns the input stream for the request.

Locale GetLocale ();
Returns the locale object for the current page, which can be set in response.

Enumeration Getlocales ();
Returns a collection of all the locale objects in the request.

String Getlocalname ();
Gets the server-side host name of the response request.

A. String getlocaladdr ();
Gets the server-side address of the response request.

Getlocalport Int ();
Get the server-side port that responds to the request

String GetMethod ();
Gets the method (get, POST) that the client sends the request to the server side.

String GetParameter (string name);
Gets the parameter values that the client sends to the server side.

Map Getparametermap ();
This method returns a Map object that contains all the parameters in the request.

Enumeration Getparameternames ();
Returns a collection of all the parameters in the request.

String[] Getparametervalues (String name);
Gets all the values for the specified parameter in the request.

String getquerystring ();
Returns the string of arguments passed by the Get method, which does not break out individual parameters.

A. String getpathinfo ();
Remove additional information between Servletpath and QueryString in the request.

A. String getpathtranslated ();
Returns the actual path of the path information obtained using the GetPathInfo () method.

String Getprotocol ();
Returns the protocol used by the request. It can be HTTP1.1 or HTTP1.0.

BufferedReader Getreader ();
Returns the reader object for the requested input stream, which can only be invoked on one page for a getInputStream () method.

String getremoteaddr ();
Gets the client IP address that issued the request.

String Getremotehost ();
Gets the client host name that issued the request

String Getremoteuser ();
Returns a client-authenticated user name that returns null without validation.

Getremoteport Int ();
Returns the client host port on which the request was made.

Getrealpath string (string path);
Returns the physical path of the given virtual path.

RequestDispatcher getrequestdispatcher (String path);
Generates a resource by the given path to process the adapter object.

A. String Getrequestedsessionid ();
Returns the identity of the requested session.

RequestUri String ();
Returns the client address that issued the request, but does not include the requested parameter string.

StringBuffer Getrequesturi ();
Returns the server-side address of the response request

Getscheme String ();
Gets the protocol name, which defaults to the HTTP protocol.

getServerName String ();
Returns the name of the server that responded to the request.

A. String Getservletpath ();
Gets the file path of the script file requested by the client.

Getserverport Int ();
Gets the server-side host port number in response to the request.

removeattribute void (String name);
Deletes the property of the specified name in the list of properties.

void SetAttribute (String name, Object value);
Adds/deletes the specified property to the list of properties.

setcharacterencoding void (String name);
Sets the character encoding format of the request.

HttpSession getsession ();
HttpSession getsession (Boolean create);
Gets the session, if Create is true, and creates one without a session.

Boolean Isrequestedsessionidfromcookie ();
Check that the requested session ID is passed through a cookie.

Boolean Isrequestedsessionidfromurl ();
Checks whether the requested session ID is passed in by URL.

Boolean isrequestedsessionidvalid ();
Check that the requested session ID is still valid.

Boolean issecure ();
Check whether the request uses a secure link, if HTTPS, and so on.

A Boolean isuserinrole (String role);
Check to see if the user who has passed the validation is in the role specified by roles.

Principal Getuserprincipal ();
Returns a Java.security.Principal object that contains the user login name.

Members:
String Basic_Auth = "BASIC"-
String Client_cert_auth = "Client_cert"-
String Digest_auth = "DIGEST"-
String Form_auth = "FORM"-


③response-javax.servlet.http.httpservletresponse
The response object mainly passes the results of the JSP container processing back to the client.

Method:
1. Void Addcookie (cookie cookie);
Add a Cookie object to save the client information.

2. void Adddateheader (String name, Long value);
Adds HTTP header information for a date type, overwriting HTTP header information with the same name.

3. void AddHeader (string name, string value);
Add an HTTP header that overwrites the old HTTP header with the same name.

4. void Addintheader (String name, int value);
Adds an integer HTTP header that overwrites an old HTTP header with the same name.

5. Boolean Containsheader (String name);
Determines whether the specified HTTP header exists.

6. String encoderedirecturl (string url);
Encodes the URL used by the Sendredirect () method.

7. String encodeurl (string url);
Encodes the URL to return the URL that contains the session ID.

8. void Flushbuffer ();
Forces the contents of the current buffer to be sent to the client.

9. int getbuffersize ();
Gets the size of the buffer in kilobytes.

String getcharacterencoding ();
Gets the character encoding format of the response.

A. String getcontenttype ();
Gets the type of the response.

Locale GetLocale ();
Gets the locale object for the response.

Servletoutputstream Getoutputstream ();
Returns the output stream object for the client.

PrintWriter getwriter ();
Gets the writer object that corresponds to the output stream.

Boolean iscommitted ();
Determine if the server side has output data to the client.

void Reset ();
Clears all content in the buffer.

void Resetbuffer ();
All content in buffer, but preserves HTTP headers and state information.

void Senderror (int xc, String msg);
void Senderror (int xc);
Send errors, including status codes and error messages.

(a) void Sendredirect (String locationg);
Send the response to another location for processing.

void setbuffersize (int size);
Sets the size of the buffer in kilobytes.

void Setcharacterencoding (String charset);
Sets the character encoding format used by the response.

void setcontentlength (int length);
Sets the body length of the response.

setContentType void (String type);
Sets the type of response.

void Setdateheader (String name, Long value);
Sets the value of the HTTP header for the data type of the specified name.

SetHeader void (string name, string value);
Sets the value of the HTTP header for the specified name.

Setintheader void (String name, int value);
Sets the value of the HTTP header for the type int of the specified name.

(a) void setstatus (int xc);
Sets the response status code, and the new value overrides the current value.

Member (HTTP status code):
int sc_continue = int Sc_switching_protocols = 101
int SC_OK = int sc_non_authoritative_information = 203
int sc_accepted = sc_created int = 201
int sc_no_content = 204 int sc_reset_content = 205
int sc_partial_content = 206 int sc_multiple_choices = 300
int sc_moved_permanently = sc_moved_temporarily int = 302
int sc_found = 302 int sc_see_other = 303
int sc_not_modified = 304 int sc_use_proxy = 305
int sc_temporary_redirect = 307 int sc_bad_request = 400
int sc_unauthorized = 401 int sc_payment_required = 402
int sc_forbidden = 403 int sc_not_found = 404
int sc_method_not_allowed = 405 int sc_not_acceptable = 406
int sc_proxy_authentication_required = 407 int sc_request_timeout = 408
int sc_conflict = 409 int sc_gone = 410
int sc_length_required = 411 int sc_precondition_failed = 412
int sc_request_entity_too_large = 413 int Sc_request_uri_too_long = 414
int sc_unsupported_media_type = 415 int sc_requested_range_not_satisfiable = 416

Related Article

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.