JSP nine large built-in objects

Source: Internet
Author: User
Tags map class stack trace

Although the Java Web is now basically developed using SPRINGMVC+AJAX, it is necessary to understand the nine built-in objects of JSP. Objects such as request, response, and session are often used even with other frameworks. So there is a great need to understand.

These objects can be called in the JSP page without prior definition, which makes JSP programming more convenient and fast. In fact, these built-in objects correspond to a servlet class, and after the JSP is translated into a servlet, the built-in objects are converted into corresponding class instances.

Built-in object features:

1. Provided by the JSP specification, without being instantiated by the creator.

2. Implementing and managing through the Web container

3. All JSP pages can be used

4. Available only in expressions or snippets of script elements (<%= using built-in object%> or <% using built-in objects%>)

Common built-in objects:

1. Output input object: Request object, Response object, out object

2. Communication Control object: PageContext object, Session object, Application object

3. Servlet object: Page object, config object

4. Error Handling object: Exception object

1. Request Object Javax.servlet.http.HttpServletRequest

The request built-in object is one of the most commonly used objects, and it represents an object of the Java.servlet.HttpServletRequest class. The request built-in object contains information about browser requests and provides several methods for obtaining cookies, headers, and data within the session.

The Requeset object is a request from the client to the server, which can be used to understand the client information


IsUserInRole (String role) determines whether the authenticated user is a member of a logical role
getattribute (String name) returns the property value specified by name. Null if not present
getattributes () returns a collection of names for all the properties of the request object, with the result being an instance of an enumeration.
getcookies () returns all cookie objects for the client, and the result is an array of cookies.
getcharacterencoding () returns the character encoding in the request.
Getcontentlength () returns the length of the requested body, if the length is not determined, returns-1
GetHeader (String name) gets the file header information defined by the HTTP protocol
getheaders (String name) returns all values of the request header for the specified name, the result of which is an enumerated
Getheadernames () returns the name of all request headers, and the result is an enumeration instance.
getInputStream () returns the requested input stream for obtaining the data in the request
GetMethod () obtains the method that the client transmits data to the server side, such as Get,post,header,trace.
getparameter (String name) obtains the parameter values that the client sends to the server side.
Getparameternames () obtains all the parameter names that the client sends to the server side, and the result is an instance of the enumeration
getparametervalues (String name) gets all the values for the specified parameter.
Getprotocol () Gets the protocol name on which the client transmits data to the server
getquerystring () Gets the query string, which is sent by the client to the server side in a get way
Getrequesturi () Gets the client address that issued the request string
getremoteaddr () Get the client IP address
Getremotehost () Gets the client name
getsession ([Boolean Create]) returns and requests the associated session. The Create parameter is optional. When a parameter is created and the value of this parameter is true, a new session is created if the client does not yet create a session.
getServerName () Gets the name of the server
Getservletpath () Gets the file path of the script file requested by the client
Getserverport () Gets the port number of the server
removeattribute (String name) deletes a property in the request
SetAttribute (String name, Java.lang.Object obj) sets the parameter value of the request


2. Response Object Javax.servlet.http.HttpServletResponse


The response object, in contrast to the request object, contains the response information that the server makes to the client. The response is packaged as a httpservletresponse interface during implementation, and it contains the response that is generated by the JSP. It is then sent to the client in response to the client's request


Addcookie (Cookie Cook) adds a cookie object that holds user information for the client
AddHeader (String name,string value) adds HTTP file header information. The header information is communicated to the client, and if it already exists the same name overwrites
Containsheader (String name) determines whether the header of the specified sentence already exists and returns TRUE or false
Encodeurl () uses SessionID to encapsulate the URL. Return the original value if no URL is encapsulated
Flushbuffer () forces the contents of the current buffer to be sent to the client
getbuffersize () returns the size of the buffer
Getoutputstream () returns the output stream to the client
senderror (int) sends an error message to the client. If 404 refers to the page does not exist
Sendredirect (String location) sends a response to another position for processing that is requesting redirection
setcontent (String contentType) sets the MIME type of the response
getwriter () This method returns a PrintWriter object
getcharacterencoding () This method obtains the corresponding character encoding type at this time
Setdateheader (String name,heaername,long date) sets the specified header name and date to the response header information whose value is the number of milliseconds from the epoch
SetHeader (String name,string value) sets the value of the header of the HTTP file for the specified name, overwriting if it exists.


3. Session Object Javax.servlet.http.HttpSession

The session object is a JSP built-in object that is created automatically when the first JSP page is loaded, and completes conversation-period management. Open a browser from a client and connect to the server to start, to the client close the browser to leave the end of this server, known as a session. When a client accesses a server, it may switch between several pages of the server, and the server should know by some means that it is a client and needs a session object.


When a client accesses a JSP page on the server for the first time, the JSP engine generates a session object, assigning a string ID number, and the JSP engine sends the change ID number to the client, which is stored in a cookie so that the Session object Until the client closes the browser, the server side of the client's session object is canceled, and the conversation correspondence with the customer disappears. When the customer re-opens the browser and then connects to the server, the server creates a new session object for the customer.


The Session object is an object that is automatically created by the server that is related to the user request. The server generates a Session object for each user that holds the user's information and tracks the user's operational status.


The session object uses the map class internally to hold the data, so the format of the saved data is "Key/value". The value of the session object can make complex object types, not just string types.

getattribute () Gets the property associated with the specified name

getcreatetime () Returns the creation time of the session, the minimum unit of this 1 per thousand seconds
getid () returns a unique identity, the ID of each session is different
Span style= "font-size:16px" >getlastaccessedtime () returns the last requested time of the client associated with the current session object
setmaxinactiveinterval (int number) This method sets the time at which the session data is saved, and the parameter numbers is in seconds
getmaxinactiveinterval () returns a time, negative value indicating that the session will never expire. Its value is the lifetime of the session
invalidate () destroys this object,
isnew () if the client does not accept the session, a session object will be generated in each request.
removeattribute (String name) deletes the property associated with the specified name
setattribute (String name,java.langobject obj) sets the property value of the specified name and stores it in the session.

4. Application Object Javax.servlet.ServletContext

The Application object saves information in the server until the server shuts down, otherwise the information saved in the Application object will be valid throughout the application. The Application object has a longer life cycle than the session object, similar to the system's global variables.


The Application object is generated when the server is started, and the Application object is the same until the server shuts down when the client browses through the pages of the Web site visited. However, unlike the session object, all customer application objects are the same, that is, all customers share this built-in Application object.

getattribute (String name) returns the value of the property of the Application object of the specified name
Getattributenames () returns the name of the property of all application-level objects, with the result of an instance of the enumeration
Getinitparameter (String name) returns the initial value of a property of the application object specified by the name
Getservletinfo () returns information about the current version of the servlet compiler
setAttribute (String name,object obj) sets the value of the property of the Application object of the specified name
removeattribute (string key) deletes information for an object by keyword
Getrealpath (String path) returns the true path of the virtual path
GetContext (String urlpath) returns the Application object that executes the web App
getmajorversion () returns the maximum version number of the Servlet API supported by the server
getminorversion () returns the minimum version number of the Servlet API supported by the server
getmimetype (String file) returns the MIME type of the specified file
getresource (String path) returns the input stream for the specified resource
Getresourcedispathcher (String urlpath) returns the requestdispathcher of the specified resource
Getservlet (String name) returns the servlet for the specified name
getservlets () returns all Servlets with a return type of enum type
Getservletnames () returns all the servlet names, the return type is enumerated type
log (String msg) writes the specified information to the servlet's log file
Log (String msg,throwable throwable) writes the trace and the given Throwable exception description information to the servlet's log file

5, Out Object Javax.servlet.jsp.jspWriter

The Out object is used to output information within a Web browser and to manage the output buffers on the application server. When you use an Out object to output data, you can manipulate the data buffers to clear the remaining data in the buffer and make buffer space for the other output. When the data output is complete, the output stream should be closed in time.


An output stream when an out object is used to output data to the client. The Out object is used for the output of various data.

Out.print ()//Output data
Out.newline ()//output a line break
Out.flush ()//data in the output buffer
Out.close ()//close output stream
Out.clearbuffer ()//clears the data in the buffer and outputs the data to the client
Out.clear ()//clears the data in the buffer, but does not output the data to the client
Out.getbuffersize ()//Get buffer size
Out.getremaining ()//Get the amount of space not occupied in the buffer
Out.isautoflush ()//Returns a Boolean value. Returns True if AutoFlush is true.

6. PageContext Object Javax.servlet.jsp.PageContext

The function of the PageContext object is to obtain any range of parameters, through which can get the JSP page out, request, reponse, session, application and other objects.


The creation and initialization of PageContext objects is done by the container, and the PageContext object can be used directly in the JSP page.


The Page object represents the JSP itself and is only legal within the JSP page. The page implied object essentially contains the variables referenced by the current servlet interface, similar to the this pointer in Java programming.

Forward (String Uripath) redirection
GetAttribute (String name,[int scope) scope is optional. Used to retrieve the scope of a particular named object, and you can also retrieve an enumeration of string names for each property of a particular range by calling the Getattributenamesinscope () method.
GetException () returns the current exception object
Getrequest () returns the current request object
GetResponse () returns the current response object
Getservletconfig () returns the ServletConfig object of the current page
Getservletcontext () returns the ServletContext object. This object is shared for all pages
GetSession () returns the current session object
Findattribute () can be used to search for a named property by page, request, session, and application-scoped order.
SetAttribute () can be used to set the default page range or a specific range of named objects. RemoveAttribute () can be used to delete named objects in the default scope or in a specific range

7. config Object javax.servlet.ServletConfig

The main purpose of the Config object is to obtain the server configuration information. A config object can be obtained by using the Getservletconfig () method of the Pageconext object. When a servlet initializes, the container passes some information through the Config object to the servlet. Developers can provide initialization parameters for servlet programs and JSP pages in the application environment in the Web. xml file

Getservletcontext () returns the servlet context of the performer
Getservletname () returns the name of the servlet
Getinitparameter (String name) returns the value of the initial parameter named name
Getinitparameternames () returns the name of all the initial parameters of this JSP

8 Page Object Java.lang.Object

The Page object is somewhat similar to the this pointer in Java programming, meaning the current JSP page itself. The page is an object of the Java.lang.Object class.

Page.getclass ()//Gets the class of the Page object
Page.hashcode ()//Get the hash code of the Page object
Page.tostring ()//Convert this Page object to a String class object
Page.notify ()//Wake up a waiting process
Page.notifyall ()//Wake up all waiting processes
Page.wait ()//causes a thread to wait until it wakes up
Page.wait (long Timeout)//causes a thread to wait until timeout or wake

9. Exception Object Java.lang.Throwable

The purpose of the exception object is to display exception information that can be used only on pages that contain iserrorpage= "true", which will not compile JSP files in a generic JSP page.

The Excepation object, like all objects in Java, has a system-provided inheritance structure.

The exception object almost defines all exception conditions. In Java programs, you can use the Try/catch keyword to handle exceptions, and if an exception is not caught in the JSP page, the exception object is generated and the exception object is routed to the error page set in the page directive. The corresponding exception object is then processed in the error page.

Exception objects can be used only on error pages (pages with iserrorpage=true in the page directive)
GetMessage ()//Get exception message string
Getlocalizemessage ()//Get exception errors for localized languages
Printstacktrace ()//show abnormal stack trace track
ToString ()//Returns a simple message description of the exception error
Fillinstacktrace ()//rewrite the stack execution trajectory of the exception error

JSP nine large built-in objects

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.