JSP Implicit Objects
JSP has a series of implicit objects and methods (obtained as APIs from HTTP) for performing such functions as accessing data from the client (browser) page, sending data back to it, controlling the buffering of the transmitted data, creating and accessing cookies, communicating and sharing information at the different scope levels of page, session and application, managing the scope, and obtaining various kinds of client/server environment information. In this sense, the objects can be classified into 2 categories:
Ø
Input/Output Objects
(control of dataflow between client (browser) and server)
q Request
q Response
q Out
Ø
Scope communication and
control
q Session
The use of each object is described in a 2 column table. The first column presents the methods of the object that perform particular functions. The second column describes the method’s use and gives an example, where needed. Only methods of major use are included. The others can be found in Appendix B of Bergsten or OnLine at http://java.sun.com/j2se/1.3/docs/api/index.html.
request Object (Complete
Interface)
|
Method |
Description |
|
|
getParameter(ParamName) |
Note that in ASP there are separate methods, Request.Form(“ParamName”) and Request.Querystring(“ParamName”) for the POST and Example: Value = request.getParameter(“ParamName”); |
|
|
getParameterValues(ParamName) |
Accesses all parameter values with name “ParamName”, whether from a POST or a Example: String Values[] = request.getParameterValues(“ParamName”) A_Value = Values[i] |
|
|
getParameterNames() |
Accesses all parameter names as an enumeration of string types. Example: enumeration Names = request.getParameterNames() |
|
|
getSession() |
Accesses a session Object. If one does not exist, it creates one. Another form of this method is getSession(Boolean create), where if create = true, a session object is created if one does not exist; if create = false, a session object is not created, if one does not exist, and null is returned. |
|
|
getCookies() |
A cookie is an object that contains a name/value pair plus administrative or auxiliary information, such as an expiration time. It is created on the server and sent to the browser machine through the response object. It is automatically identified by the server and application (e.g., c3081nn) that created it.
request.GetCookies() will access from the browser all unexpired cookies created by the server/application making the request. request.getCookies() is an array of Cookie objects. The Cookie object has a number of methods used to extract the name/value pair and the administrative information from the cookie Some of them are as follows: getName() returns the name as a string getValue() returns the value as a string getMaxAge returns the maximum age in seconds as an integer. A value of –1 means that the cookie will persist until the browser is closed. getComment returns a string containing a description of the cookie. When a cookie object is created, using the response object described in the next table, it is assigned its name/value pair via the statement Cookie MyCookie = new Cookie(name,value); The cookie object also has some methods that can be used to store information in a cookie object after it has been created. Some of them, corresponding to the get methods listed above, are: setValue() setMaxAge() setComment() Note that you can reset the value after the cookie is created, using setValue, but you can’t change its name.
Example: Get the value of a Cookie named
“Chip”. Cookie MyCookies[] = request.getCookies(); Cookie TheCookie = null; if (MyCookies != null) { for (int = 0; i<MyCookies.length; ++1) { if MyCookies[i].getName.equals(“Chip”)) { TheCookie = MyCookies[i]; break; } } } String value = TheCookie.getValue() Or, more succinctly, String value; Cookie MyCookies[] = request.getCookies(); if (MyCookies != null) { for (int = 0; i<MyCookies.length;++1) { if MyCookies[i].getName.equals(“Chip”)) { value = MyCookies[i].getValue(); break; } } } |
|
|
setAttribute(name,value) |
Assigns a value to a request attribute with name “name”. “name” is a string and value is an object. Example: String Initialized = “yes” ; request.setAttribute(“init”, Initialized); Notes: (1) String Initialized = “yes” is an allowed shorthand for String Initialized = new String(“yes”). String is the only object that allows this shorthand, as a convenience. (2) Any object can be stored in an attribute, including beans. (3) Storing data in a request attribute is one of the ways that data can be shared with another page that is still within the request scope, as a result of a forward action. Note that use of the redirect, rather than the forward, will cause the new page to leave the request scope. |
|
|
getAttribute(name) |
Accesses the value of the request attribute with name “name”. Example: String InitializedHere = (String) request.getAttribute(“init”); Note: the result of request.getAttribute must be cast to the object type of its value, and the receiving object name need not be the same as the one used to assign the attribute value in the setAttribute. |
|
|
getAttributeNames() |
Retrieves all attribute names in the request object, as an enumeration type. |
|
|
removeAttribute(name) |
Removes the request attribute with name “name”. |
|
|
getMethod() |
Returns the Request Method: Get, Post |
|
|
getRequestURI() |
Returns the part of the URL before the parameters (“?”) as a string. |
|
|
getQueryString() |
Returns the parameters of the URL (after the “?”) as a string. |
|
|
getRemoteHost() |
Returns the fully qualified name of the host that sent the request as a string. |
|
|
getRemoteAddr() |
Returns the network ip address of the host as a string |
|
|
getRemoteUser() |
Returns the name of the User that sent the request as a string. |
|
response Object (Complete Interface)
|
Method |
Description |
|
<%=textString%> (JSP text output) |
Writes text to the browser. Note that in ASP there is a Response.Write(text) method as well as the <%=text%> shorthand. In JSP there is only the shorthand. |
|
addCookie(cookie) |
Sends a cookie object to the browser in the header. T he cookie object has methods that can be used to store information in a cookie object after it has been created. Some of them, corresponding to the get methods listed above under the request object are: setValue() setMaxAge() setComment() Note that you can reset the value after the cookie is created, using setValue, but you can’t change its name. Example: Cookie MyCookie = new Cookie(“AccountNumber”, “1003456”); MyCookie.setMaxAge(60*60*24*7*26); response.addCookie(MyCookie); If a cookie already exists with a given name, then it is overwritten. |
|
sendRedirect(url) |
Sends a redirect to the browser. The browser will then display nothing, but immediately send a page request to the server in the “url”. This information is contained in a header, but there can be no other headers transmitted. Note that the request object of the current page is not available to the redirected target page. In contrast, the action <jsp:forward page=url /> does preserve the request object. Example: response.sendRedirect(“myserver.com/thePage.htm?ID=767”) |
Buffering |
Both the Response and Out objects have buffer control methods. Some of them overlap and some are different. Buffering means that the response data are not sent to the browser as they are generated within the jsp page, but rather are buffered. The buffer will automatically send the data when it is filled, if it is set to the autobuffer state. If buffering is turned off, then all data are transmitted as soon as they are generated. This generation may be by means of html, the jsp Response Object methods, or the shorthand write tag <%=…%>. Buffering is set by the page directive Buffer = “none” or “InitialBufferSize”, where “none” means no buffering, and InitiaBufferSize is the initial buffersize in bytes, if there is buffering, expressed, for example, as 8kb. The default is no buffering. If buffering is turned on, then another page directive “Autobuffer = true/false” determines the state of autobuffering. If set to true, then the buffer is automatically sent and cleared when full. If set to false, then the buffer must be sent or cleared by specific methods provided within the Response and Out objects within the page code at run time. If these commands are not issued, and the buffer fills, an exception will be thrown. The default is autobuffer, if buffering is on. There are also methods to control the size of the buffer and determine the remaining space at any time. |
|
flushBuffer() |
All data in the buffer are sent to the browser, and the buffer is cleared. |
|
reset() |
The buffer is cleared and nothing is sent to the browser. |
|
getBufferSize() |
Returns the buffer size in bytes as an integer. If buffering is off then 0 is returned. |
|
setBufferSize(size) |
Resets the buffer size in bytes, where “size” is an integer. Note that the buffersize was originally set in the page directive. |
|
getWriter (Servlet text output) |
Returns a PrintWriter TheOutput; TheOutput = response.getWriter(); TheOutput.println(textString); |
|
encodeURL(url) |
A rewritten url is returned that contains the Session ID in the form: mypage.jsp;jsessionid=6ab5674 ef78… This form of the url can be used in html tags that use a url (like <a href…>) This enables the server to keep track of the session. |
|
encodeRedirectURL |
A rewritten url is returned that can be used in the sendRedirect method. |
|
Method |
Description |
|
flush() |
The Response object has methods that enable the buffer to be flushed, with and without sending it to the browser. The Out object provides these same capabilities but gives additional control over the output stream being sent to the browser. flush() will transmit the data in the buffer to the browser and clear the buffer. |
|
clear() |
clear() does not transmit the buffer data and clears the buffer. If the buffer had previously been flushed (i.e., its content sent to browser) then an IOException error is thrown. |
|
clearBuffer() |
Same as clear, except that the IOException is not thrown. It clears the buffer and returns. |
|
close() |
Same as flush, but also closes the page. |
|
getBufferSize() |
Returns the buffer size in bytes as an integer. If buffering is off then 0 is returned. |
|
getRemaining() |
Returns the number of bytes remaining in the unused buffer. |
|
println(text) |
Transmits “Text” as a string, terminated with a carriage return-linefeed. |
|
print(text) |
Transmits “Text” as a string, without a carriage return-linefeed. |
session Object (complete
interface)
|
Method |
Description |
|
setAttribute(AttName,Value) |
Assigns (binds) an object (Value) to a session attribute with name “AttName”. “AttName” is a string and Value is an object. Example 1: String Initialized = “yes” ; session.setAttribute(“init”, Initialized); Notes: (1) String Initialized = “yes” is an allowed shorthand for String Initialized = new String(“yes”). String is the only object that allows this shorthand, as a convenience. (2) Any object can be stored in a session attribute, including beans. |
|
getAttribute(AttName) |
Accesses the value of session attribute with name “AttName”. Example: String
InitializedHere = (String) Session.getAttribute(“init”); Note: the result of Session.getAttribute must be cast to the object type of its value, and the receiving object name need not be the same as the one used to assign the attribute value in the setAttribute. |
|
getAttributeNames() |
Retrieves all attribute names in the session object, as an enumeration type. |
|
removeAttribute(Attname) |
Removes (unbinds) the object “Attname” from the session object. Example: <jsp:useBean id = "connect" class = "connectPack.ConnectionBean" scope = "session"/> removeAttribute ("connect") Note: The name of the bean object (connect in this case) is automatically made the name of the session attribute. |
|
|
Session ID The server will assign a unique number called the Session ID to each session. The following cycle is generated: 1. Client (browser) sends initial url request to server 2. Server generates Session ID and sends it back to client via response object. A method session.isnew() will return true at this time. 3. Client stores ID cookie 4. On subsequent requests the client also sends the ID cookie back. On the first such request, the server will set session.isnew() to false, where it remains until the session terminates. |
|
getId() |
Returns the Session ID. |
|
getCreationTime() |
Returns time of session creation |
|
getLastAccessedTime() |
Returns last time a request associated with this session was received |
|
setMaxInactiveInterval(t) |
Sets the maximum time (in seconds) between requests for which the session will be maintained |
|
getMaxInactiveInterval(t) |
Returns the maximum time (in seconds) between requests for which the session will be maintained |
|
isNew() |
Returns true if user’s browser has not yet confirmed the Session ID assignment (See Session ID description above) |
|
invalidate() |
Terminate the session and release all objects stored as attributes. |
|
Method |
Description |
|
setAttribute(name,value) |
Assigns a value to an application attribute with name “name”. “name” is a string and value is an object. Example: String Initialized = “yes” ; Application.setAttribute(“init”, Initialized); Notes: (1) String Initialized = “yes” is an allowed shorthand for String Initialized = new String(“yes”). String is the only object that allows this shorthand, as a convenience. (2) Any object can be stored in an application attribute, including beans. (See example on Pg 298 of Bergsten) |
|
getAttribute(name) |
Accesses the value of application attribute with name “name”. Example: String InitializedHere = (String) Application.getAttribute(“init”); Note: the result of Application.getAttribute must be cast to the object type of its value, and the receiving object name need not be the same as the one used to assign the attribute value in the setAttribute. |
|
getAttributeNames() |
Retrieves all attribute names in the application object, as an enumeration type. |
|
removeAttribute(name) |
Removes the application attribute with name “name”. |
pageContext Object (Complete Interface)
|
Method |
Description |
|
setAttribute(name,value,scope) setAttribute(name,value) default scope is PAGE_SCOPE |
Assigns a value to an attribute with name “name” in scope “scope”. “name” is a string and value is an object. There are 4 fixed values of “scope”: PAGE_SCOPE, REQUEST_SCOPE, SESSION_SCOPE, and APPLICATION_SCOPE. Thus, the PageContext object can manage attributes across all scopes. Example: String Initialized = “yes” ; PageContext.setAttribute(“init”, Initialized, APPLICATION_SCOPE); |
|
getAttribute(name, scope) |
Accesses the value of an attribute with name “name” and scope “scope”. Example: String InitializedHere = (String) Session.getAttribute(“init”, APPLICATION_SCOPE); |
|
getAttributeNamesInScope(scope) |
Retrieves all attribute names in the specified scope, as an enumeration type. |
|
removeAttribute(name, scope) |
Removes the attribute with name “name” and scope “scope”. |
|
getOut().print(text) getOut().println(text) |
Transmits the String text |