Tuesday, April 12, 2011

Chapter 36: JSP - Implicit Objects

In any JSP Page, there are a bunch of implicit objects that are available for the programmer to use. It contains a variety of information that can be used to display stuff on the page. In this chapter, we are going to look at the following JSP Implicit Objects that are available for a programmer.

• request
• response
• out
• session
• config
• application
• page
• pageContext

So, Lets get Started!!!

JSP Implicit Objects

The JSP Implicit objects mentioned in the list in the previous paragraph are available by means of automatically defined variables. These variables have the same name and case as the list above. In the forthcoming paragraphs we will be looking at them one by one.


This is the HttpServletRequest instance associated with the client request. As you know, the data between the Servlet and the JSP flows by using the HttpServletRequest and the HttpServletResponse objects. The page receives a request and sends a response. The data sent by a JSP page is available in the request in the Servlet and similarly the data sent by the servlet is available in the JSP again in the request object. There is a surprising amount of information stored in it. For example, you can get the request type (whether it is GET, POST, or HEAD) and the associated cookies. You can extract information from the request object and act on that data.

Let us take a look at a small piece of code that would help us understand how to read data from the request object.
< html >
< body >
< h1 > Inspecting the Request Object < / h1 >
< font size="4" >
Request Method: < % = request.getMethod() % >

Request URI: < % = request.getRequestURI() % >

Request Protocol: < % = request.getProtocol() % >

Servlet path: < % = request.getServletPath() % >

Path info: < % = request.getPathInfo() % >

Path translated: < % = request.getPathTranslated() % >

Query string: < % = request.getQueryString() % >

Content length: < % = request.getContentLength() % >

Content type: < % = request.getContentType() % >

Server name: < % = request.getServerName() % >

Server port: < % = request.getServerPort() % >

Remote user: < % = request.getRemoteUser() % >

Remote address: < % = request.getRemoteAddr() % >

Remote host: < % = request.getRemoteHost() % >

Authorization type: < % = request.getAuthType() % >

Browser type: < % = request.getHeader("User-Agent") % >
< / font >
< / body >
< / html >

If you deploy this JSP on your TomCat server and run it, you will see the details of the request on your web page. This is how the page would look if you run your local instance.


This is the HttpServletResponse class that manages the response to the client. You use this object to send data back to the client. For example, among other things, you can add cookies (addCookie), add a specified header (addHeader), and return an error that includes a status and a default message (sendError). You can redirect a browser to another URL with sendRedirect. You can set the content type and the HTTP status (setStatus) as well. For ex: you can set the content type on the response using the below line of code.


The response object doesn't do much. It doesn't have any elaborate functionality like the HttpServletRequest but at the same time, it is not trivial. It still can do a lot of things that would affect the whole J2EE application as such.

Besides manipulating the output buffer (such as, setBufferSize(), flushBuffer(), and getBufferSize()), Sun's public interface ServletResponse defines only the following methods: getLocale(), getOutputStream(), getWriter(), isCommitted(), setContentLength(), setContentType(), and setLocale().


This is the HttpSession object associated with the request. We have taken a detailed look at the Session Management in the previous few chapters which are as follows:

1. Introduction to Sessions
2. Storing & Retrieving Session Objects
3. Session Event Listeners
4. Invalidating Sessions
5. Session Tracking Through URL Rewriting

The JSP container handles (creates, tracks, and destroys) sessions automatically. You can use the session attribute of the page directive to turn sessions off. When they are explicitly set to - off, there is no session state available for a JSP page, and any reference to the session variable causes a fatal error.

The primary use of the session variable is to store state information between pages for a given user. A session applies to a single user where you can share information across JSP pages. This differs from the application object, which shares information across all users. The session is on by default, so you don't have to set the "session=true" attribute in the JSP page directive, but it is good practice to make your intentions clear.

The exam objectives only address your understanding of what a session is and how to turn on session tracking for a JSP page. Still, you should at least review the methods and properties of the session object, as they might appear in a test question. They are as follows:

• getAttribute
• getAttributeNames
• getCreationTime
• getId
• getLastAccessedTime
• getMaxInactiveInterval
• invalidate
• isNew
• putValue
• removeAttribute
• setAttribute
• setMaxInactiveInterval

I repeat, the Session Management has been covered in great depth as part of this SCWCD series and you can visit those article to understand the HttpSession, if you havent done already…

Exam Trivia:
Each new session gets its own unique id number. That is how the JSP container keeps track of browsers. The number has to be long enough to eliminate the possibility of session id collision


The config implicit object is an instance of the class javax.servlet.ServletConfig. It is usually used in servlets rather than JSP pages. The methods of this object return initialization parameters for the page which are declared in the web.xml file. You define initialization parameters by setting the property when you register a servlet in the web.xml file, the deployment descriptor. The most used methods of this object are getInitParameter and getInitParameterNames.

Though it is used predominantly in servlets, the config object is available in the JSP page as well. Let us take a look at a sample piece of code and see how to use the config object.
< % String DFLT_PARAM_ONE = "first parameter"; String DFLT_PARAM_TWO = "second parameter"; String param_one = config.getInitParameter("first_parameter"); if (param_one == null) { param_one = DFLT_PARAM_ONE; } String param_two = config.getInitParameter("second_parameter"); if (param_two == null) { param_two = DFLT_PARAM_TWO; } % >
< % = "param_one: " + param_one % >
< % = "

" % >
< % = "param_two: " + param_two % >
< % = "< P >" % >

I will leave you to execute this in your JSP page to ponder the output. It would be a good exercise for you to understand these implicit objects…


While a session object shares information between JSP pages for a given user, an application object shares information among all users of a currently active J2EE Web application. You can also use this object to communicate with the Servlet Container running the current JSP page. Normally, there is one application object per Java Virtual Machine. So, every JSP page on a Web server shares the same application object (irrespective of how many sessions are running currently).

When we need to store information to be available throughout a web application, we can store it in the Servlet context, which is used to store the state for an entire Web application. This is sometimes referred to as the application object. In JavaServer pages, the implicit application object represents the Servlet context. Unlike a session object, the Servlet context is not invalidated by any updates or recompiling of a given JSP page, or servlet for that matter. Whatever information you store in the Servlet context will remain until the Web application itself is invalidated.

Beyond sharing information among client requests, the application object provides information about the environment of the JSP page. It also has methods for writing messages to the server log which would prove very useful when you want to debug an application that is throwing out errors during the development phase or even for production support.

A few of the methods and properties for the application are very similar to those of the session object. The primary difference is scope, whether the objects are shared only between pages being viewed by a single user (session) or all users (application). The methods and properties include the following:
• getAttribute
• getAttributeNames
• getMajorVersion/getMinorVersion
• getMimeType
• getRealPath
• getResource
• getServerInfo
• log
• removeAttribute
• setAttribute


JSP has an object of the class pageContext. This is used mainly in servlets to encapsulate server-specific features. That being said, the object is available in the JSP as well.
HttpSession session = pageContext.getSession();
JspWriter out = pageContext.getOut();

The main goal of the pageContext is to encapsulate the complete state of a single request-execution of a single JSP page. This object is passed to custom actions so that these Java objects have access to anything that the JSP page has access to.


In standard Java programs, the “this” keyword is a reference to the object for which the instance method was invoked, or to the object being constructed. The page is JSP's equivalent of Java's this, but it isn't so very useful in JSP. The JSP designers created it to address JSP's support for other scripting languages beside Java. Usually it is recommended to use the Java’s this keyword than JSPs page.


This is what the PrintWriter uses to send output to the client. There is also a buffered version of PrintWriter called JspWriter. You can adjust the buffer size, or even turn buffering off, through use of the buffer attribute of the page directive. Also note that out is used almost exclusively in scriptlets, since JSP expressions automatically get placed in the output stream, and thus we rarely need to refer to out explicitly.

Exam Trivia:
The clear method deletes all the content of the current buffer. You need to be very cautious when using this method. Once the buffer has been flushed, automatically or through code, calling clear throws an IOException error. Once data is written to the client response stream, it is illegal to call the clear method.
The out variable is a Java PrintWriter you can use to write HTML to the browser page from inside JSP tags. Let us take a look at an example before we wrap up the chapter.
<% out.clear(); //clears all output to the browser out.print(out.getBufferSize()); //bytes available in Buffer out.print("Hello There!!!"); out.print( out.getRemaining() ); //bytes left in Buffer out.newLine(); //prints a line return out.flush(); //flushes the buffer %>

Previous Chapter: Chapter 35 - JSP Lifecycle

Next Chapter: Chapter 37 - JSP Scriptlets


  1. exception is also a JSP Implicit Object.
    I think you forgot to include it.

  2. I blog often and I truly appreciate your content.

    Your article has truly peaked my interest. I am going to
    take a note of your site and keep checking for new
    information about once a week. I subscribed to your Feed too.
    Also see my webpage: baby girl headbands


© 2013 by www.inheritingjava.blogspot.com. All rights reserved. No part of this blog or its contents may be reproduced or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, or otherwise, without prior written permission of the Author.