JSP Implicit Objects – Syntax and Examples
Placement-ready Online Courses: Your Passport to Excellence - Start Now
Welcome to DataFlair JSP Implicit Objects Tutorial. This article discusses the implicit objects and all the methods related to them. It discusses in detail about their functioning, usage etc. So let’s begin!!!
JSP Implicit Objects
Web containers create these implicit objects when they translate JSP pages to servlet. They are available to all JSP pages. They are written in scriptlet tags except declaration. It is due the fact that everything that is in the scriptlet tag goes to _jspSevice() method where processing of requests occurs, whereas declaration goes to source file generated outside _jspService() method. They get called directly and need not to be declared. They are also called in-built objects.
There are 9 implicit objects available in the web container. Out of these 9, 7 are objects while 2 are passed as parameters to the _jspService(). All the objects are:
1. out
2. request
3. response
4. config
5. session
6. application
7. page
8. pageContext
9. exception
Let’s see each one in detail:
1. out
It is the most used implicit object that comes from java.servlet.jsp.JspWriter. It’s work is to write data into a buffer which would be sent to the client as output. It possesses the access to servlet output stream.
Servlet uses PrintWriter but JspWriter has some additional features to it. Jsp Writer has options for buffer and I/O Exceptions which are not available in PrintWriter.
Syntax: out.methodName();
Out uses various methods such as:
a. void print(): It prints the data to the output. One can specify the data type too.
out.print(datatype d);
b. void println(): It prints the data type and terminates the line.
out.println(datatype d);
c. void flush(): The contents in the buffer(if present) gets written to the output and the stream is flushed.
out.flush();
d. void clear(): It clears the buffer. Even if something is present in the buffer, it doesn’t get written to output. It will throw an exception, if this method is called on a buffer that is already flushed.
out.clear();
e. void clear buffer(): It is similar to clear but it doesn’t give an exception if called on a flushed buffer.
out.clear buffer();
f. boolean isAutoFlush(): This method checks that the buffer is set to flush automatically or not.
out.isAutoFlush();
g. int getBufferSize(): This method returns the size of the buffer in bytes.
out.getBufferSize();
h. int getRemaining(): This method returns the remaining bytes of buffer that are empty before the buffer overflows.
out.getRemaining();
Example:
Out2.jsp <html> <head> <title>IMPLICIT OBJECT</title> </head> <body> <% out.println("first statement"); out.println("second"); out.println("third"); %> </body> </html>
Explanation: Using the method out.println(), this example shows the use of out implicit object. Output gets shown on the screen.
Output:
2. request
This is an in-built implicit object of javax.servlet.http.HttpServletRequest. It is passed as a parameter to jspService method. This instance is created each time a request is generated. Using this object we can request for a parameter session, cookies, header information, server name, server port, contentType, character encoding etc. It has following methods:
Syntax: request.methodname(“value”);
Methods under request parameter are:
a. getParameter(): This method is used so that the value of request can be got.
String obj=request.getParameter(“name”);
b. getParameterNames(): It gives the Enumeration of requested values.
c. getParameterValues(String name): It returns a whole array of parameters.
d. getAttribute(String name): This method gets the value of the attributes present.
request.getAttribute(“value”);
e. getAttributeNames(): This method is used to generate all the attributes that are present in that session.
f. setAttribute(String, Object): This method sets the value of an attribute according to user requirements. For example, If we want to set password value as admin then,
str=admin
String str=request.setattribute(“Password”, str)
This will set admin as password.
g. removeAttribute(str): This method will remove the mentioned attribute from that JSP page.
request.removeAttribute(“value”);
h. getCookies(): This method of request will give an array of cookie objects used under cookie handling.
i. getHeader(String name): This method will get the information regarding the header of the request.
j. getHeaderNames(): This method will return an enumeration of all the header names available.
k. getRequestURI(): This method will return the Current JSP page’s URL to the user.
l. getMethod(): This method will return the method used for the request. For example, GET for getMethod(), POST for postMethod().
m. getQueryString(): This method will return the string in the url after the question mark for the associated page.
Example:
form.html <html> <head><title>My login</title> </head> <body> <form action="user.jsp"> <a>Username:</a><input type="text" name="username"> <br/> <a>Password:</a><input type="text" name="password"> <input type="submit" value="go"><br/> </form> </body> </html> user.jsp <html> <head><title>login</title></head><body> <% String name=request.getParameter("username"); String pass=request.getParameter("password"); out.print("Welcome user, you entered your name as "+name); %> </body> </html>
Explanation: This example gets the Parameter value from the user in the form of username and password using getParameter() and shows a welcome message to the user.
Output:
3. response
This is an object from HttpServletResponse. This object rather gets passed as a parameter to jspService() like request. It is the response given to the user. One can redirect, get header information, add cookies, send error messages using this object.
Syntax: response.nethodName();
Methods used with response object are:
a. void setContentType(String type): This method sets the contempt type of browser and browser interprets according to it.
response.setContentType(“text/html”);
response.setContentType(“image/gif”);
b. void sendRedirect(String address): This method will redirect users to other destinations.
response.sendRedirect(“http://www.google.com”);
c. void addHeader(String name, String value): This method adds header to the response
response.addHeader(“Address”, “Google.com”);
d. void setHeader(String name, String value): This method will set the header value
response.setHeader(“Address”, “G.com”);
e. boolean containsHeader(String name): It checks that if header is present or not. It can have 2 values either true/false
response.containsHeader(“Address”);
f. void addCookie(Cookie value): Response will contain cookie using this method.
response.addCookie(Cookie kk);
g. void sendError(int status_code, String message): Error response is sent using this method.
response.sendError(404, “error: Page was not found “);
For Example:
redirect.html <html> <head><title>My login</title> </head> <body> <form action="user2.jsp"> <a>Username:</a><input type="text" name="username"> <br/> <a>Password:</a><input type="text" name="password"> <input type="submit" value="go"><br/> </form> </body> </html> user2.jsp <html> <head><title>login</title></head> <body> <% response.sendRedirect("http://www.google.com"); %> </body> </html>
Explanation: In this example use of response and its method sendRedirect has been shown. When a user enters username and password they get redirected to http://www.google.com.
Output:
4. config
It is an object of javax.servlet.ServletConfig. It is used to get the information regarding configuration of JSP pages. For example get Servlet Name etc. It gives out the parameters related to servlet mapping initialization.
Syntax: config.methodName();
Methods used with config object are:
1. String getInitParameter(String name) – This method gets the parameter name.
2. Enumeration getInitParameterNames( ) – This method will return an enumeration of initialization params.
3. getServletContext( ) – It will return reference to Servlet context.
4. String getServletName() – It returns the name of the servlet which was defined in the web.xml file used for mapping.
String s = config.getServletName();
For Example:
<html> <head><title>Config</title> </head> <body> <form action=.jsp"> <a>Username:</a><input type="text" name="username"> <br/> <input type="submit" value="go"><br/> </form> </body> </html> web.xml <web-app> <servlet> <servlet-name>kajalmoryani</servlet-name> <jsp-file>/one.jsp</jsp-file> <init-param> <param-name>drivername</param-name> <param-value>abc.JdbcOdbcDriver</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>kajalmoryani</servlet-name> <url-pattern>/one</url-pattern> </servlet-mapping> </web-app> one.jsp <html> <head><title>Config2</title></head> <body> <% out.print("Welcome "+request.getParameter("username")); String driver=config.getInitParameter("drivername"); out.print("driver name is="+driver); %> </body> </html>
Explanation: In this example the servlet mapping is done by web.xml and the driver name gets printed in the output.
Output:
5. session
session object is the implicit object under javax.servlet.http.HttpSession . It is used to get session information as it tracks sessions between client requests. It can be used to get, set as well as remove under scope of session. As session creation and management is a cumbersome project so if you don’t want a session to be created we can set the session in page directive as false.
Syntax: session.getAttribute()
Methods used with session object are:
a. setAttribute(String, object) – This method will assign a string to the object and save it in session.
b. getAttribute(String name) – This method gets the object that is set by setAttribute.
c. removeAttribute(String name) – Objects that are in the session can be removed using this method.
d. getAttributeNames – It returns enumeration of the objects in session.
e. getCreationTime – This method returns time when the session was in active mode.
f. getId –This method gives out the unique id of the session.
g. isNew – This method checks if a session is new or not. It would return true if cookies are not there.
h. getMaxInactiveInterval – Returns time span, the session was inactive.
i. getLastAccessedTime – This method gives the last accessed time of a session.
For Example:
<html> <head><title>Config</title></head> <body> <form action="first.jsp"> <input type="text" name="username"> <input type="submit" value="go"><br/> </form> </body> </html> First.jsp <html> <head><title>Config</head></title> <body> <% String myname=request.getParameter("username"); out.print("Welcome "+myname); session.setAttribute("user",myname); %> <a href="second.jsp">second jsp page</a> </body> </html> second.jsp <html> <body> <% String name=(String)session.getAttribute("user"); out.print("Hello "+myname); %> </body> </html>
Explanation: This code will generate a session. The form takes in the username and is reverted to first.jsp which is a session page on clicking the second jsp page link, we get to the final page i.e. second.jsp that says Hello message.
Output:
6. application
It is an implicit object of ServletContext from javax.servlet.ServletContext implementation. This object is created by the web container only when an application is deployed. It is generated one per application. As the name suggests, it interacts with servlet.
It can get set or even remove the attributes under application scope. It can exclusively be used to get the object Request Dispatcher. Using Request Dispatcher, it forwards the request to other pages.
Syntax: application.methodName(“value”);
Methods available under application scope are:
a. Object getAttribute(String attributeName): This method gets the object available in the attribute and returns it.
String a = (String)application.getAttribute(“Name”);
b. void setAttribute(String attributeName, Object object): This method will set the value of attribute.
application.setAttribute(“Address”, “Value of Address”)
c. void removeAttribute(String objectName): This method will remove an attribute from application.
application.removeAttribute(“Name”);
d. String getRealPath(String value): This method will return the absolute path of the file.
String abspath = application.getRealPath(“/form.html”);
e. void log(String message): This method stores logs to default log file of JSP Endine
application.log(“ error 404 page not found”);
f. String getServerInfo(): Returns name and version of web container
application.getServerInfo();
For Example:
<html> <head> <title>Application object</title> </head> <body> <a>This is an example for application implicit object</a> <% application.getRealPath(“/form.html”); %> </body> </html>
Explanation: The object used in the example is application along with the method getContextPath method. It gives the Context Path of the related JSP page.
Output:
7. PageContext
It is the implicit object from javax.servlet.jsp.PageContext implementation where PageContext is an abstract implementation. This object has the capability to get, set and remove attributes that fall under 4 scopes–page, request, session and application scopes.
This object has references to other implicit objects. It contains information of directives, buffer information, error page URL. It holds reference to request and response as well. This can support over 40 methods that are inherited from ContextClass. It is even used to get info of a complete JSP page.
Syntax: pageContext.methodName(“parameter”);
Some useful methods used with pageContext:
a. Object getAttribute (String AttributeName, int Scope): This method finds/gets the attribute from the suggested scope
- Object obj1 = pageContext.getAttribute(“name”, PageContext.SESSION_CONTEXT);
- Object obj2 = pageContext.getAttribute(“address”, PageContext. REQUEST_CONTEXT);
- Object obj3= pageContext.getAttribute(“number”, PageContext. PAGE_CONT EXT);
- Object obj4 = pageContext.getAttribute(“data”, PageContext. APPLICATION_CONTEXT);
b. void setAttribute(String AttributeName, Object AttributeValue, int Scope): This method will set the attribute in the scope along with its value.
Object obj1 = pageContext.setAttribute(“name”, “Kajal”, PageContext.SESSION_CONTEXT);
c. void removeAttribute(String AttributeName, int Scope):This method will remove the attribute mentioned from referred scope.
Object obj1 = pageContext.removeAttribute(“name”, PageContext.SESSION_CONTEXT);
d. Object findAttribute (String AttributeName): This method will find the attribute in all the four scopes and when found none, return null value. The difference between get and find is that scope is defined in the get method.
Object obj2 = pageContext.findAttribute(“address”);
For Example:
myindex.html <html> <head><title>PageContext</title> </head> <body> <form action="PageContext1.jsp"> <input type="text" name="username"> <input type="submit" value="go"><br/> </form> </body> </html> PageContext1.jsp <html> <head><title>PageContext</title></head> <body> <% String myname=request.getParameter("username"); out.print("Welcome "+myname); pageContext.setAttribute("client",myname,PageContext.SESSION_SCOPE); %> <a href="PageContext2.jsp"> go to second jsp page</a> </body> </html> PageContext2.jsp <html> <body> <% String myname=(String)pageContext.getAttribute("client",PageContext.SESSION_SCOPE); out.print("Here you will see your name "+myname); %> </body> </html>
Explanation: In this example pageContext1 sets attribute client in Session scope and forwards to PageContext2 where it gets the attribute and shows the result.
Output:
8. page
This implicit object comes under java.lang.Object class. Its work is to provide reference to the servlet class generated. Type casting is thus required to access this object as shown below.
<% (HttpServlet)page.log(“message”); %>
We use this rarely. Instead, we use it as:
Syntax:
Object page=this;
<% this.log(“message”); %>
For Example:
<html> <head><title>Object page</title> </head> <body> <% this.log("message"); %> </body> </html>
Explanation: A reference page is generated over successful compilation.
Output:
9. Exception
Exception is an implicit built-in object of java.lang.Throwable. This is useful for handling exceptions in JSP. As these pages handle errors, they can only be used for JSP error pages. This implies that if <%@ page isErrorPage=”true”%>, then only you can use this object.
Syntax is as follows:
<%=exception%>
For Example:
form2.html <html> <head> <title>Enter two Integers to divide</title> </head> <body> <form action="divide.jsp"> Enter First Integer:<input type="text" name="number1" /><br/> Enter Second Integer:<input type="text" name="mumber2" /> <input type="submit" value="Result"/> </form> </body> </html> divide.jsp <%@ page errorPage="exception.jsp" %> <html> <body> <% String num1=request.getParameter("number1"); String num2=request.getParameter("number2"); int n1= Integer.parseInt(num1); int n2= Integer.parseInt(num2); int result= n1/n2; out.print("Output is: "+ result); %> </body> </html> exception.jsp <%@ page isErrorPage="true" %> <html> <head> <title>Exception</title></head> <body> <a href: Hey,Got this Exception: </a><%= exception %> <br/> <a>Check the data entered.</a> </body> </html>
Explanation: In this example html page opens and asks for input. These entered numbers are forwarded to divide.jsp that does calculation and if the page creates an exception, then exception.jsp is called and it throws java.langNumberFormatException and Check the data entered.
Output:
Conclusion
In reference to this article, we came to know about different implicit objects. We discussed the methods associated with them and how they are used in JSP.
Did you like our efforts? If Yes, please give DataFlair 5 Stars on Google