JSP Implicit Objects by R4R Team

JSP Implicit Objects
These objects are created by JSP container while translating the JSP page to Servlet. These objects are present inside service methods so we can directly use them without declaration.

a)Introduction to implicit objects
b)out implicit object
c)request implicit object
d)response implicit object
e)session implicit object
f)application implicit object
g)exception implicit object
h)pageContext implicit object
i)config implicit object

a)Introduction to implicit objects:

Implicit Objects and their corresponding classes:

out javax.servlet.jsp.JspWriter
request javax.servlet.http.HttpServletRequest
response javax.servlet.http.HttpServletResponse
session javax.servlet.http.HttpSession
application  javax.servlet.ServletContext
exception javax.servlet.jsp.JspException
page java.lang.Object
pageContext  avax.servlet.jsp.PageContext
config javax.servlet.ServletConfig

Out: This is used for writing content to the client (browser). It has several methods which can be used for properly formatting output message to the browser and for dealing with the buffer.
Request: The main purpose of request implicit object is to get the data on a JSP page which has been entered by user on the previous JSP page. While dealing with login and signup forms in JSP we often prompts user to fill in those details, this object is then used to get those entered details on an another JSP page (action page) for validation and other purposes.
Response: It is basically used for modfying or delaing with the response which is being sent to the client(browser) after processing the request.
Session: It is most frequently used implicit object, which is used for storing the user’s data to make it available on other JSP pages till the user session is active.
Application: This is used for getting application-wide initialization parameters and to maintain useful data across whole JSP application.
Exception: Exception implicit object is used in exception handling for displaying the error messages. This object is only available to the JSP pages, which has isErrorPage set to true.
Page: Page implicit object is a reference to the current Servlet instance (Converted Servlet, generated during translation phase from a JSP page). We can simply use this in place of it. I’m not covering it in detail as it is rarely used and not a useful implicit object while building a JSP application.
pageContext: It is used for accessing page, request, application and session attributes.
Config: This is a Servlet configuration object and mainly used for accessing getting configuration information such as servlet context, servlet name, configuration parameters etc.


b)OUT Implicit Object in JSP with examples
It’s an instance of javax.servlet.jsp.JspWriter. This allows us to access Servlet output stream. The output which needs to be sent to the client (browser) is passed through this object. In simple words out implicit object is used to write content to the client.

Methods of OUT Implicit Object:
void print()
void println()
void newLine()
void clear()
void clearBuffer()
void flush()
boolean isAutoFlush()
int getBufferSize()
int getRemaining()


Let’s here see each of the out’s method in detail:

void print(): This method writes the value which has been passed to it. For e.g. the below statement would display a sentence Out Implicit Object in jSP
out.print(“Out Implicit Object in jSP ycd”);
void println(): This method is similar to the print() method, the only difference between print and println is that the println() method adds a new line character at the end. Let’s have a look at the difference with the help of an example.

print:

out.print(“hi”);

out.print(" ");

out.print(“hello”);

println:

out.println(“hi”);

out.println(“hello”);
void newLine(): This method adds a new line to the output. Example –
out.print(“This will write content without a new line”);
out.newLine();
out.print(“I’m just an another print statement”);

As you know print statement doesn’t add a new line. We have added a new line between two out.print statements using newLine() method.

void clear(): It clears the output buffer without even letting it write the buffer content to the client. This is how it can be called –
out.clear();
void clearBuffer(): This method is similar to the clear() method. The only difference between them is that when we invoke out.clear() on an already flushed buffer it throws an exception, however out.clearBuffer() doesn’t.
void flush() : This method also clears the buffer just like clear() method but it forces it to write the content to the output before flushing it, which means whatever is there in buffer would be written to the client screen before clearing the buffer.
boolean isAutoFlush() : It returns a Boolean value true/false. It is used to check whether the buffer is automatically flushed or not.
int getBufferSize(): This method returns the size of output buffer in bytes.
int getRemaining(): It returns the number of bytes remaining before hitting the buffer overflow condition.

OUT Implicit Object Example

In this example we are using print and println methods of OUT for displaying few message to the client.

index.jsp

<HTML>

<HEAD>

<TITLE> OUT IMPLICIT OBJECT EXAMPLE </TITLE>

</HEAD>

<BODY>

<%

out.print( "print statement " );

out.println( "println" );

out.print("Another print statement");

%>

</BODY>

</HTML>


c)Request Implicit Object in JSP with examples:

Here we will discuss request implicit object in JSP. It is mainly used to get the data on a JSP page which has been entered by user on the previous JSP page.

Methods of request Implicit Object:


getParameter(String name) - This method is used to get the value of a request’s parameter. For example at login page user enters user-id and password and once the credentials are verified the login page gets redirected to user information page, then using request.getParameter we can get the value of user-id and password which user has input at the login page.

String Uid= request.getParameter("user-id");

String Pass= request.getParameter("password");
getParameterNames() - It returns enumeration of all the parameter names associated to the request.

Enumeration e= request.getParameterNames();
getParameterValues(String name) – It returns the array of parameter values.

String[] allpasswords = request.getParameterValues("password");
getAttribute(String name) – Used to get the attribute value. request.getAttribute(“admin”) would give you the value of attribute admin.
getAttributeNames() – It is generally used to get the attribute names associated to the current session. It returns the enumeration of attribute names present in session.
Enumerator e = request.getAttributeNames();
setAttribute(String,Object) – It assigns an object’s value to the attribute. For example I have an attribute password and a String object str which has a value “admin” then calling request.setAttribute(“password”, str) would assign a value admin to the attribute password.
removeAttribute(String) – By using this method a attribute can be removed and cannot be used further. For e.g. If you have a statement request.removeAttribute(“userid”) on a JSP page then the userid attribute would be completely removed and request.getAttribute(“userid”) would return NULL if used after the removeAttribute method.
getCookies() – It returns an array of cookie objects received from the client. This method is mainly used when dealing with cookies in JSP.
getHeader(String name) – This method is used to get the header information of the request.
getHeaderNames() – Returns enumerator of all header names. Below code snippet would display all the header names associated with the request.

Enumeration e = request.getHeaderNames();

while (enumeration.hasMoreElements()) {

String str = (String)e.nextElement();

out.println(str);

}
getRequestURI() – This method (request.getRequestURI()) returns the URL of current JSP page.
getMethod() - It returns HTTP request method. request.getMethod(). For example it will return GET for a Get request and POST for a Post Request.
getQueryString() – Used for getting the query string associated to the JSP page URL. It is the string associted to the URL after question mark sign (?).

Request Implicit Object Example:

In the below example we are receiving the input from user in index.html page and displaying the same information in userinfo.jsp page using request implicit object.

index.html

<html>

<head>

<title>Enter UserName and Password</title>

</head>

<body>

<form action="userinfo.jsp">

Enter User Name: <input type="text" name="uname" /> <br><br>

Enter Password: <input type="text" name="pass" /> <br><br>

<input type="submit" value="Submit Details"/>

</form>

</body>

</html>

userinfo.jsp:

<%@ page import = " java.util.* " %>

<html>

<body>

<%

String username=request.getParameter("uname");

String password=request.getParameter("pass");

out.print("Name: "+username+" Password: "+password);

%>

</body>

</html>

d)Response Implicit Object in JSP with examples

In this post we are going to discuss about response implicit object in JSP. It is an instance of javax.servlet.http.HttpServletRequest and mainly used for modifying the response which is being sent to the browser after processing the client’s request.

Methods of response Implicit Object:

void setContentType(String type)
void sendRedirect(String address)
void addHeader(String name, String value)
void setHeader(String name, String value)
boolean containsHeader(String name)
void addCookie(Cookie value)
void sendError(int status_code, String message)
boolean isCommitted()
void setStatus(int statuscode)


Let’s see each method in detail :-

void setContentType(String type) – This method tells browser, the type of response data by setting up the MIME type and character encoding. The information sets by this method helps browser to interpret the response.

Example:

response.setContentType("text/html");

response.setContentType("image/gif");

response.setContentType("image/png");

response.setContentType("application/pdf");

void sendRedirect(String address) – It redirects the control to a new JSP page. For e.g. When the browser would detect the below statement, it would be redirected to the beginnersbook.com from the current JSP page.

response.sendRedirect("http://ycd.com");
void addHeader(String name, String value) – addHeader method adds a header to the response, basically it includes a header name and it’s value. For example – The below statement will include a header “Site” in the response with value “ycd.com”.

response.addHeader("Site", "ycd.com");
void setHeader(String name, String value) – It sets the header value. This method overrides the current value of header with the new value. Let’s say I’m modifying the value of Header “Site“. The below statement would modify the current value ycd.com to a new value yc.com

response.setHeader("Site", "yc.com");
boolean containsHeader(String name) – It returns a Boolean value true/false. It basically checks the whether the header is present in the response or not. For example – Above, in the addHeader method example we have added a Site Header in response so the below statement would return true.

response.containsHeader("Site");
void addCookie(Cookie cookie) – This method adds a cookie to the response. The below statements would add 2 Cookies Author and Siteinfo to the response.

response.addCookie(Cookie Author);

response.addCookie(Cookie Siteinfo);
void sendError(int status_code, String message) – It is used to send error response with a code and an error message. For example –

response.sendError(404, "Page not found error");
boolean isCommitted() -It checks whether the Http Response has been sent to the client, if yes then it returns true else it gives false.

<% if(response.isCommited())

{

<%--do something --%>

}else

{

<%--do something else --%>

} %>
void setStatus(int statuscode) – This method is used to set the HTTP status to a given value. For e.g. the below statement would set HTTP response code to 404 (Page not found).

response.setStatus(404);
Response Implicit Object Example:

In the below example we are receiving id and password from login page and then we are matching them with hardcoded correct id/pass. If the credentials are correct the sign-in page redirects to success page else it redirects to sign-in fail JSP page.

index.html:

<html>

<head>

<title>Login Page</title>

</head>

<body>

<form action="checkdetails.jsp">

UserId: <input type="text" name="id" /> <br><br>

Password: <input type="text" name="pass" /> <br><br>

<input type="submit" value="Sign In!!"/>

</form>

</body>

</html>

This JSP page verifies the input id/pass against hard-coded values.

checkdetails.jsp:

<html>

<head><title>Check Credentials</title>

</head>

<body>

<%

String uid=request.getParameter("id");

String password=request.getParameter("pass");

session.setAttribute("session-uid", uid);

if(uid.equals("alok") && password.equals("ycd"))

{

response.sendRedirect("success.jsp");

}

else

{

response.sendRedirect("failed.jsp");

}

%>

</body>

</html>

This JSP page would execute if id/pass are matched to the hardcoded userid/password.

success.jsp:

<html>

<head><title>Success Page</title>

</head>

<body>

<%

String data=(String)session.getAttribute("session-uid");

out.println("Welcome "+ data+"!!");

%>

</body>

</html>

The control will be redirected to this page if the credentials entered by user are wrong.

failed.jsp

<html>

<head><title>Sign-in Failed Page</title>

</head>

<body>

<%

String data2=(String)session.getAttribute("session-uid");

out.println("Hi "+ data2+". Id/Password are wrong. Please try Again.");

%>

</body>

</html>

e)Session Implicit Object in JSP with examples:

Session is most frequently used implicit object in JSP. The main usage of it to gain access to all the user’s data till the user session is active.

Methods of session Implicit Object


setAttribute(String, object) – This method is used to save an object in session by assigning a unique string to the object. Later, the object can be accessed from the session by using the same String till the session is active. setAttribute and getAttribute are the two most frequently used methods while dealing with session in JSP.
getAttribute(String name) – The object stored by setAttribute method is fetched from session using getAttribute method. For example if we need to access userid on every jsp page till the session is active then we should store the user-id in session using setAttribute method and can be accessed using getAttribute method whenever needed.
removeAttribute(String name) – The objects which are stored in session can be removed from session using this method. Pass the unique string identifier as removeAttribute’s method.
getAttributeNames – It returns all the objects stored in session. Basically, it results in an enumeration of objects.
getCreationTime – This method returns the session creation time, the time when session got initiated (became active).
getId – Servlet container assigns a unique string identifier to session while creation of it. getId method returns that unique string identifier.
isNew() – Used to check whether the session is new. It returns Boolean value (true or false). Mostly used to track whether the cookies are enabled on client side. If cookies are disabled the session.isNew() method would always return true.
invalidate() – It kills a session and breaks the association of session with all the stored objects.
getMaxInactiveInterval – Returns session’s maximum inactivate time interval in seconds.
getLastAccessedTime – Generally used to know the last accessed time of a session.
Session Implicit Object Example:

The below html page would display a text box along with a submit button. The submit action would transfer the control to session.jsp page.

String[] allpasswords = request.g

index.html

<html>

<head>

<title>Welcome Page: Enter your name</title>

</head>

<body>

<form action="session.jsp">

<input type="text" name="inputname">

<input type="submit" value="click here!!"><br/>

</form>

</body>

</html>etParameterValues("password");


The session.jsp page displays the name which user has entered in the index page and it stores the the same variable in the session object so that it can be fetched on any page until the session becomes inactive.

session.jsp

<html>

<head>

<title>Passing the input value to a session variable</title>

</head>

<body>

<%

String uname=request.getParameter("inputname");

out.print("Welcome "+ uname);

session.setAttribute("sessname",uname);

%>

<a href="output.jsp">Check Output Page Here </a>

</body>

</html>


In this page we are fetching the variable’s value from session object and displaying it.

output.jsp

<html>

<head>

<title>Output page: Fetching the value from session</title>

</head>

<body>

<%

String name=(String)session.getAttribute("sessname");

out.print("Hello User: You have entered the name: "+name);

%>

</body>

</html>

f)Application Implicit Object in JSP with examples:

Application implicit object is an instance of javax.servlet.ServletContext. It is basically used for getting initialization parameters and for sharing the attributes & their values across the entire JSP application, which means any attribute set by application implicit object would be available to all the JSP pages

Methods:

Object getAttribute(String attributeName)
void setAttribute(String attributeName, Object object)
void removeAttribute(String objectName)
Enumeration getAttributeNames()
String getInitParameter(String paramname)
Enumeration getInitParameterNames()
String getRealPath(String value)
void log(String message)
URL getResource(String value)
InputStream getResourceAsStream(String path)
String getServerInfo()
String getMajorVersion()
String getMinorVersion()

Object getAttribute(String attributeName): It returns the object stored in a given attribute name. For example the below statement would return the object stored in attribute “MyAttr”.

String s = (String)application.getAttribute("MyAttr");
void setAttribute(String attributeName, Object object): It sets the value of an attribute or in other words it stores an attribute and its value in application context, which is available to use across JSP application. Example –

application.setAttribute(“MyAttribute”, “This is the value of Attribute”);
The above statement would have stored the attribute and its value. What would be the value of ‘s’ if we use the below statement in any of the JSP page?

String s= (String) application.getAttribute(“MyAttribute”);
String s value would be “This is the value of Attribute” since we have set it using setAttribute method.

void removeAttribute(String objectName): This method is used for removing the given attribute from the application. For e.g. – It would remove the Attribute “MyAttr” from the application. If we try to get the value of a removed attribute using getAttribute method, it would return Null.

application.removeAttribute(“MyAttr”);
Enumeration getAttributeNames(): This method returns the enumeration of all the attribute names stored in the application implicit object.

Enumeration e= application.getAttributeNames();
String getInitParameter(String paramname): It returns the value of Initialization parameter for a given parameter name. Example –web.xml
<web-app>

…

<context-param>

<param-name>parameter1</param-name>

<param-value>ValueOfParameter1</param-value>

</context-param>

</web-app>
Suppose above is my web.xml file:

String s=application.getInitParameter(“parameter1”);
The value of s will be “ValueOfParameter1”. Still confused where did it come from? See the param-value tag in web.xml file.

Enumeration getInitParameterNames(): It returns the enumeration of all the Initialization parameters.

Enumeration e= application.getinitParameterNames();
String getRealPath(String value): It converts a given path to an absolute path in the file system.

String abspath = application.getRealPath(“/index.html”);
The value of abspath would be a complete http URL based on the existing file system.

void log(String message): This method writes the given message to the JSP Engine’s (JSP container’s) default log file associated to the application.

application.log(“This is error 404 Page not found”);
The above call would write the message “This is error 404 Page not found” to the default log file.

String getServerInfo(): This method returns the name and version of JSP container (JSP Engine).
application.getServerInfo();
Application Implicit object Example:

A JSP page to capture number of hits using application. In this example we are counting the number of hits to a JSP page using application implicit object.

counter.jsp:

<%@ page import="java.io.*,java.util.*" %>

<html>

<head>

<title>Application Implicit Object Example</title>

</head>

<body>

<%

//Comment: This would return null for the first time

Integer counter= (Integer)application.getAttribute("numberOfVisits");

if( counter ==null || counter == 0 ){

//Comment: For the very first Visitor

counter = 1;

}else{

//Comment: For Others

counter = counter+ 1;

}

application.setAttribute("numberOfVisits", counter);

%>

<h3>Total number of hits to this Page is: <%= counter%></h3>

</body>

</html>

g)Exception Implicit Object in JSP with examples:

In this tutorial, we will discuss exception implicit object of JSP. It’s an instance of java.lang.Throwable and frequently used for exception handling in JSP. This object is only available for error pages, which means a JSP page should have isErrorPage to true in order to use exception implicit object. Let’s understand this with the help of below example :
Exception implicit Object Example:
In this example we are taking two integer inputs from user and then we are performing division between them. We have used exception implicit object to handle any kind of exception in the below example.

index.html

<html>

<head>

<title>Enter two Integers for Division</title>

</head>

<body>

<form action="division.jsp">

Input First Integer:<input type="text" name="firstnum" />

Input Second Integer:<input type="text" name="secondnum" />

<input type="submit" value="Get Results"/>

</form>

</body>

</html>


Here we have specified exception.jsp as errorPage which means if any exception occurs in this JSP page, the control will immediately transferred to the exception.jsp JSP page. Note: We have used errorPage attribute of Page Directive to specify the exception handling JSP page (<%@ page errorPage=”exception.jsp” %>).
division.jsp:

<%@ page errorPage="exception.jsp" %>

<%

String num1=request.getParameter("firstnum");

String num2=request.getParameter("secondnum");

int v1= Integer.parseInt(num1);

int v2= Integer.parseInt(num2);

int res= v1/v2;

out.print("Output is: "+ res);

%>
In the below JSP page we have set isErrorPage to true which is also an attribute of Page directive, used for making a page eligible for exception handling. Since this page is defined as a exception page in division.jsp, in case of any exception condition this page will be invoked. Here we are displaying the error message to the user using exception implicit object.

exception.jsp

<%@ page isErrorPage="true" %>

Got this Exception: <%= exception %>

h)pageContext Implicit Object in JSP with examples
It is an instance of javax.servlet.jsp.PageContext. Using this object you can find attribute, get attribute, set attribute and remove attribute at any of the below levels –

JSP Page – Scope: PAGE_CONTEXT
HTTP Request – Scope: REQUEST_CONTEXT
HTTP Session – Scope: SESSION_CONTEXT
Application Level – Scope: APPLICATION_CONTEXT


Methods of pageContext Implicit Object:

Object findAttribute (String AttributeName): This method searches for the specified attribute in all four levels in the following order – Page, Request, Session and Application. It returns NULL when no attribute found at any of the level.
Object getAttribute (String AttributeName, int Scope): It looks for an attribute in the specified scope. This method is similar to findAttribute method; the only difference is that findAttribute looks in all the four levels in a sequential order while getAttribute looks in a specified scope. For e.g. – In the below statement the getAttribute method would search for the attribute “ycd.com” in Session scope (or Session level/layer). If it finds the attribute it would assign it to Object obj else it would return Null.

Object obj = pageContext.getAttribute("ycd.com", PageContext.SESSION_CONTEXT);
Similarly the method can be used for other scopes too :

Object obj = pageContext.getAttribute("ycd", PageContext. REQUEST_CONTEXT);

Object obj = pageContext.getAttribute("ycd", PageContext. PAGE_CONTEXT);

Object obj = pageContext.getAttribute("ycd", PageContext. APPLICATION_CONTEXT);
void removeAttribute(String AttributeName, int Scope): This method is used to remove an attribute from a given scope. For example – The below JSP statement would remove an Attribute “MyAttr” from page scope.
pageContext.removeAttribute(“MyAttr”, PageContext. PAGE_CONTEXT);
void setAttribute(String AttributeName, Object AttributeValue, int Scope): It writes an attribute in a given scope. Example – Below statement would store an Attribute “mydata” in application scope with the value “This is my data”.

pageContext.setAttribute(“mydata”, “This is my data”, PageContext. APPLICATION_CONTEXT);
Similarly this would create an attribute named attr1 in Request scope with value “Attr1 value”.
pageContext.setAttribute(“attr1”, “Attr1 value”, PageContext. REQUEST_CONTEXT);
pageContext Implicit Object Example:

index.html:

Here we are simply asking user to enter login details.

<html>

<head>

<title> User Login Page – Enter details</title>

</head>

<body>

<form action="validation.jsp">

Enter User-Id: <input type="text" name="uid"><br>

Enter Password: <input type="text" name="upass"><br>

<input type="submit" value="Login">

</form>

</body>

</html>


validation.jsp:

In this page we are storing user’s credentials using pageContext implicit object with the session scope, which means we will be able to access the details till the user’s session is active. We can also store the attribute using other scope parameters such as page, application and request.
<html>

<head> <title> Validation JSP Page</title>

</head>

<body>

<%

String id=request.getParameter("uid");

String pass=request.getParameter("upass");

out.println("hello "+id);

pageContext.setAttribute("UName", id, PageContext.SESSION_SCOPE);

pageContext.setAttribute("UPassword", pass, PageContext.SESSION_SCOPE);

%>

<a href="display.jsp">Click here to see what you have entered </a>

</body>

</html>


display.jsp

In this JSP page we are fetching the stored attributes using getAttribute method. The point to note here is that we have stored the attributes with session scope so we must need to specify scope as session in order to fetch those attribute’s value.

<html>

<head>

<title>Displaying User Details</title>

</head>

<body>

<%

String username= (String) pageContext.getAttribute("UName", PageContext.SESSION_SCOPE);

String userpassword= (String) pageContext.getAttribute("UPassword", PageContext.SESSION_SCOPE);

out.println("Hi "+username);

out.println("Your Password is: "+userpassword);

%>

</body>

</html>

i)Config Implicit Object in JSP with examples:
It is an instance of javax.servlet.ServletConfig. Config Implicit object is used for getting configuration information for a particular JSP page. Using application implicit object we can get application-wide initialization parameters, however using Config we can get initialization parameters of an individual servlet mapping.
Methods of Config Implicit Object:

String getInitParameter(String paramname) – Same what we discussed in application implicit object tutorial.
Enumeration getInitParameterNames() – Returns enumeration of Initialization parameters.
ServletContext getServletContext() – This method returns a reference to the Servlet context.
String getServletName() – It returns the name of the servlet which we define in the web.xml file inside <servlet-name> tag.
Config Implicit Object Example:

web.xml:

Let’s say below is my web.xml file. I’m just defining servlet name and servlet mapping in it. Later, I would fetch few details from this file using config implicit object.
<web-app>

<servlet>

<servlet-name>ycdServlet</servlet-name>

<jsp-file>/index.jsp</jsp-file>

</servlet>

<servlet-mapping>

<servlet-name>ycdServlet</servlet-name>

<url-pattern>/index</url-pattern>

</servlet-mapping>

</web-app>

index.jsp

In this JSP page we are calling getServletName() method of config object for fetching the servlet name from web.xml file.

<html>

<head> <title> Config Implicit Object</title>

</head>

<body>

<%

String sname=config.getServletName();

out.print("Servlet Name is: "+sname);

%>

</body>

</html>

Leave a Comment:
Search
Categories
R4R Team
R4Rin Top Tutorials are Core Java,Hibernate ,Spring,Sturts.The content on R4R.in website is done by expert team not only with the help of books but along with the strong professional knowledge in all context like coding,designing, marketing,etc!