Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 27

JSP Implicit Objects

JSP Implicit Objects are the Java objects that the JSP Container makes available to
developers in each page and developer can call them directly without being explicitly
declared. JSP Implicit Objects are also called pre-defined variables.

JSP supports nine Implicit Objects which are listed below:

Object Description

It refers HttpServletRequest object associated with


Request
the request.

It refers HttpServletResponse object associated
Response
with the response to the client.

It refers PrintWriter object used to send output to


Out
the client.

It refers HttpSession object associated with the


Session
request.

It refers ServletContext object associated with


Application
application context.

It refers ServletConfig object associated with the


Config
page.

It encapsulates use of server-specific features like


pageContext
higher performance JspWriters.

It is used to call the methods defined by the


Page
translated servlet class.
The Exception object make use of exception data in
Exception
JSP Page

The request Object:

1. The request object is an instance of a javax.servlet.http.HttpServletRequest

object.

2. Whenever client makes a requests to the JSP page, JSP engine creates a new

object to represent the request.

3. The request object have methods by which we can get HTTP header information.

4. HTTP header information includes form data, cookies, HTTP methods etc.

<%
String name = request.getParameter("name");
out.println("Hello " + name);
%>
For the URL http://127.0.0.1:8080/net/getParameterDemo.jsp?name=Monali, it displays the following:

1. Hello Monali

The response Object:

1. The response object is an instance of a javax.servlet.http.HttpServletResponse

object.

2. Server creates an object to represent the response to the client.

3. The response object also defines the interfaces that deal with creating new HTTP

headers.

4. Through this object the JSP programmer can add new cookies or date stamps,

HTTP status codes etc.

The out Object:


1. The out implicit object is an instance of a javax.servlet.jsp.JspWriter object and is

used to send content in a response.

2. The initial JspWriter object is instantiated differently depending on whether the

page is buffered or not.

3. Buffering can be easily turned off by using the buffered=’false’ attribute of the

page directive.

4. The JspWriter object contains most of the same methods as the

java.io.PrintWriter class. However, JspWriter has some additional methods

designed to deal with buffering. Unlike the PrintWriter object, JspWriter throws

IOExceptions.

Following are the important methods which we would use to write boolean char, int,
double, object, String etc.

Method Description

out.print(dataType dt) Print a data type value

Print a data type value then terminate the


out.println(dataType dt)
line with new line character.

out.flush() Flush the stream.

The session Object:

The session object is an instance of javax.servlet.http.HttpSession and behaves exactly


the same way that session objects behave under Java Servlets.

The session object is used to track client session between client requests. We would
see complete usage of session object in coming chapter: JSP – Session Tracking.

The application Object:


The application object is direct wrapper around the ServletContext object for the
generated Servlet and in reality an instance of a javax.servlet.ServletContext object.

This object is a representation of the JSP page through its entire lifecycle. This object is
created when the JSP page is initialized and will be removed when the JSP page is
removed by the jspDestroy() method.

By adding an attribute to application, you can ensure that all JSP files that make up
your web application have access to it.

You can check a simple use of Application Object in chapter: JSP – Hits Counter

The config Object:

The config object is an instantiation of javax.servlet.ServletConfig and is a direct


wrapper around the ServletConfig object for the generated servlet.

This object allows the JSP programmer access to the Servlet or JSP engine initialization
parameters such as the paths or file locations etc.

The following config method is the only one you might ever use, and its usage is trivial:

config.getServletName();

This returns the servlet name, which is the string contained in the <servlet-name>
element defined in the WEB-INF\web.xml file

The pageContext Object:

The pageContext object is an instance of a javax.servlet.jsp.PageContext object. The


pageContext object is used to represent the entire JSP page.

This object is intended as a means to access information about the page while avoiding
most of the implementation details.

This object stores references to the request and response objects for each request. The
application, config, session, and out objects are derived by accessing attributes of this
object.

The pageContext object also contains information about the directives issued to the JSP
page, including the buffering information, the errorPageURL, and page scope.
The PageContext class defines several fields, including PAGE_SCOPE, REQUEST_SCOPE,
SESSION_SCOPE, and APPLICATION_SCOPE, which identify the four scopes. It also
supports more than 40 methods, about half of which are inherited from the
javax.servlet.jsp.
JspContext class.

One of the important methods is removeAttribute, which accepts either one or two
arguments. For example, pageContext.removeAttribute (“attrName”) removes the
attribute from all scopes, while the following code only removes it from the page scope:

pageContext.removeAttribute("attrName", PAGE_SCOPE);

You can check a very good usage of pageContext in coming chapter: JSP – File
Uploading.

The page Object:

This object is an actual reference to the instance of the page. It can be thought of as an
object that represents the entire JSP page.

The page object is really a direct synonym for the this object.

The exception Object:

The exception object is a wrapper containing the exception thrown from the previous
page. It is typically used to generate an appropriate response to the error condition.

We would see complete usage of this object in coming chapter: JSP – Exception


Handling.

JSP Client Request

Browser sends lot of information along with the request. Information sent by browser
is stored in the request header of the HTTP request made by browser or any client side
program.

Header information sent by Browser :


Header Description Example

Header specifies the MIME types that image/png


Accept the browser or other clients can or
handle. image/jpeg

Header specifies the character set


Accept-Charset used by the browser to display the ISO-8859-1.
information.

Header specifies the type of encodings gzip or


Accept-Encoding
handled by browser. compress

Header specifies the client’s preferred


Accept-Language languages if servlet produces result in en, en-us
more than one language.

In case of Password Protected web-


Authorization pages, this header is useful for clients –
to identify themselves

This header indicates whether the


client can handle persistent HTTP
Connection connections. Using persistent Keep-Alive
connections browser can retrieve
multiple files with a single request.

This header is applicable to POST


Content-Length requests. It gives the size of the POST –
data in bytes.

Cookie Header returns cookies to servers. –

Host Header specifies the host and port –


given in the original URL.

Header indicates that the client need


If-Modified-Since the page only if it has been changed or –
modified after the specified date.

This header is the reverse of If-


If-Unmodified-Since –
Modified-Since

Header indicates the URL of the


Referer
referring Web page.

Header identifies the browser or other


User-Agent
client making the request

The HttpServletRequest Object:

1. The request object is an instance of a javax.servlet.http.HttpServletRequest

object.

2. Whenever client makes a requests to the JSP page, JSP engine creates a new

object to represent the request.

3. The request object have methods by which we can get HTTP header information.

4. HTTP header information includes form data, cookies, HTTP methods etc.

HTTP Header Request Example:

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


<html>
<head>
<title>HTTP Header Request Example</title>
</head>
<body>
<h2>HTTP Header Request Example</h2>

<table border="1">
<tr>
<th>Header Name</th><th>Header Value(s)</th>
</tr>
<%
Enumeration headerNames = request.getHeaderNames();
while(headerNames.hasMoreElements()) {
String paramName = (String)headerNames.nextElement();
out.print("<tr><td>" + paramName + "</td>\n");

String paramValue = request.getHeader(paramName);


out.println("<td> " + paramValue + "</td></tr>\n");
}
%>
</table>

</body>
</html>

Output :

Header
Header Value(s)
Name

host localhost:8080

connectio
keep-alive
n

text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.
accept
8
user- Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like
agent Gecko) Chrome/36.0.1985.125 Safari/537.36

accept-
gzip,deflate,sdch
encoding

accept-
en-US,en;q=0.8,hi;q=0.6,mr;q=0.4
language

Explanation :

1. In the above example, getHeaderNames() method of HttpServletRequest is used

to read the HTTP header information.

2. This method returns an Enumeration that contains the header information

associated with the current HTTP request.

3. We need to iterate through the loop using hasMoreElements() method.

4. To determine when to stop iterating Enumeration nextElement() method is used

JSP Auto Refresh

JSP Auto Refresh :

1. Suppose we need to refresh the web page automatically after some time then

we can use JSP setIntHeader() method.

2. We need auto refresh of page while displaying the Cricket Score or Stock Market

Status

3. setIntHeader() method is used to set the value of the specified header.


4. “Refresh” is a predefined response header name which is a proprietary non-

standard header extension, instruct the browser to update/refresh the page in

seconds.

5. Below is the Syntax of JSP setIntHeader() method –

Syntax :

public void setIntHeader(String header, int headerValue)

Above method is used to send header “Refresh” to the browser. Integer value indicates
time interval in seconds.

Auto Page Refresh Example:

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


<html>

<head>
<title>Auto Refresh Header Example</title>
</head>

<body>
<h2>Auto Refresh Header Example</h2>
<%
// Page will be auto refresh after 1 seconds
response.setIntHeader("Refresh", 1);

// Get Current Time


DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
out.println(dateFormat.format(cal.getTime()));
%>
</body>
</html>

Output :

JSP Cookies Concept

Concept of Cookies :

1. Cookies are basically text files stored on the client computer.

2. Cookies are used for tracking purpose.

3. JSP supports HTTP cookies using underlying technology using servlet.

4. Cookies are created when you use your browser to visit a website that uses

cookies to keep track of your movements within the site

Types of Cookies :

Type of
Explanation
cookie

Session cookies are created temporarily in your browser's sub-folder


Session
when you visit the website for first time , once you leave the site these
cookies
cookies will be destroyed automatically.

Persistent cookies remain in the browser's sub-folder and activated


Persistent
when you re-visit the website. These cookies will be destroyed after
cookies
the period set within the cookie's file
Steps to identify whether user is returning or not ?

There are three steps involved in identifying returning users:

1. Server script sends a set of cookies to the browser when user visits site for first

time. Cookies contain name,identification number etc

2. Cookies will stored in the browser’s folder

3. When user re-visit the website next time, browser sends those cookies

information to the server and server uses that information to identify the user

Example of the Cookie File :

HTTP/1.1 200 OK
Date: Fri, 04 Feb 2014 11:01:38 GMT
Server: Apache/1.3.9 (UNIX) PHP/4.0b3
Set-Cookie: name=pritesh; expires=Tuesday, 07-Oct-14 12:33:31 GMT;
path=/; domain=c4learn.com
Connection: close
Content-Type: text/html

You can see the name-value pair in the cookie file.Cookie file contain GMT date, a path
and a domain and expiration date.

Below is the example of the HTTP header that we send when user revisit the website.

GET / HTTP/1.0
Connection: Keep-Alive
User-Agent: Mozilla/4.6 (X11; I; Linux 2.2.6-15apmac ppc)
Host: zink.demon.co.uk:1126
Accept: image/gif, */*
Accept-Encoding: gzip
Accept-Language: en
Accept-Charset: iso-8859-1,*,utf-8
Cookie: name=xyz
JSP Implicit Objects

JSP provides standard or predefined implicit objects, which can use directly in JSP page

usingJSP Scriptlet. The implicit objects are Servlet API class type and created by JSP

containers

There are 9 jsp implicit objects. These objects are created by the web container (JSP

containers) that are available to all the jsp pages.

The available implicit objects are out, request, response, page, pageContext, exception,

config, session and application.

List of all 9 implicit object are;

Class type Object

1 HttpServletRequest request

2 HttpServletResponse response

3 ServletConfig config

4 ServletContex application

5 HttpSession session

6 JspWriter/PrintWriter out

7 Exception exception

8 PageContext pagecontext

9 Object page

All implicit objects of jsp are accessible with in the expression and scriptlet of the jsp, but not

accessible in the declaration tags of the jsp.


In a jsp session and exception object are not available always. Because session object

depends on session attribute of the page directive and exception depends on isErrorPage

attribute of the page directive.

In a jsp, session object is available, if session equals to true in page directive.

In a jsp an exception object is available, if isErrorPage is equal to true in page directive.

Request Implicit Object

The JSP request is an implicit object of type HttpServletRequest i.e. created for each jsp

request by the web container. It can be used to get request information such as parameter,

header information, remote address, server name, server port, content type, character

encoding etc.

It can also be used to set, get and remove attributes from the jsp request scope.

Example of request implicit object where we are printing the name of the user with welcome

message.

Example of JSP request implicit object

index.html

Example

<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>

welcome.jsp

Example
<%
String name=request.getParameter("uname");
out.print("welcome "+name);
%>

Response Implicit Object

In JSP, response is an implicit object of type HttpServletResponse. The instance of

HttpServletResponse is created by the web container for each jsp request.

It can be used to add or manipulate response such as redirect response to another

resource, send error etc.

Example of response implicit object where we are redirecting the response to the Google.

Example of response implicit object

index.html

Example

<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>

welcome.jsp

Example

<%
response.sendRedirect("http://www.google.com");
%>

Config Implicit Object


config object is an implicit object of type ServletConfig and it is created by the container,

whenever servlet object is created. This object can be used to get initialization parameter for

a particular JSP page.

config object is created by the web container for every jsp page. It means if a web

application has three jsp pages then three config object are created.

In jsp, it is not mandatory to configure in web.xml. If we configure a jsp in web.xml then the

logical name and init parameter given in web.xml file are stored into config object by the

container.

config object is accessible, only if the request is given to the jsp by using its url pattern, but

not with name of the jsp.

config object is accessible, only if the request is given to the jsp by using its url pattern, but

not with name of the jsp.

Example of config implicit object


index.html

<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>

web.xml file

<web-app>

<servlet>
<servlet-name>Home</servlet-name>
<jsp-file>/welcome.jsp</jsp-file>

<init-param>
<param-name>dname</param-name>
<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
</init-param>

</servlet>

<servlet-mapping>
<servlet-name>Home</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>

</web-app>

welcome.jsp

<%
out.print("Welcome "+request.getParameter("uname"));

String driver=config.getInitParameter("dname");
out.print("driver name is="+driver);
%>

Page Implicit Object

In JSP, page is an implicit object of type Object class. When a jsp is translated to an internal

Servlet, we can find the following statement in the service() method of servlet.

Object page=this;

For using this object it must be cast to Servlet type.For example:

Example

<% (HttpServlet)page.log("message"); %>


Since, it is of type Object it is less used because you can use this object directly in jsp.For

example:

Example

<% this.log("message"); %>

Session Implicit Object

In JSP, session is an implicit object of type HttpSession.This object used to set,get or remove

attribute or to get session information.

Example of Session implicit object

index.html

Example

<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>

welcome.jsp

Example

<%
String name=request.getParameter("uname");
out.print("Welcome "+name);

session.setAttribute("user",name);

<a href="second.jsp">second jsp page</a>

%>
One.jsp

Example

<%

String name=(String)session.getAttribute("user");
out.print("Hello "+name);

%>

Exception Implicit Object

JSP, exception is an implicit object of type java.lang.Throwable class. This object can be used

to print the exception. But it can only be used in error pages.

Example of Exception implicit object

index.html

Example

<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>

welcome.jsp

Example

<%
response.sendRedirect("http://www.google.com");
%>

Application Implicit Object


In JSP, application is an implicit object of type ServletContext. this application object in the

Servlet programming is ServletContext.

For all jsp in a web application, there must be a single application object with application

object we can share the data from one JSP to any other JSP in the web application.

The instance of ServletContext is created only once by the web container when application

or project is deployed on the server.

This object can be used to get initialization parameter from configuration file (web.xml). It

can also be used to get, set or remove attribute from the application scope.

Example of Application implicit object


index.html

<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>

welcome.jsp

<%
out.print("Welcome "+request.getParameter("uname"));

String driver=application.getInitParameter("dname");
out.print("driver name is="+driver);
%>

web.xml

<web-app>

<servlet>
<servlet-name>One</servlet-name>
<jsp-file>/welcome.jsp</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>One</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>

<context-param>
<param-name>dname</param-name>
<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
</context-param>

</web-app>

PageContext Implicit Object

In JSP, pageContext is an implicit object of type PageContext class.The pageContext object

can be used to set,get or remove attribute from one of the following scopes.

 page

 request

 session

 application

In JSP, page scope is the default scope.

Example of pageContext implicit object

index.html

Example

<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>

welcome.jsp
Example

<%
<%

String name=request.getParameter("uname");
out.print("Welcome "+name);

pageContext.setAttribute("user",name,PageContext.SESSION_SCOPE);

<a href="One.jsp">One jsp page</a>

%>

One.jsp
Example

String name=(String)pageContext.getAttribute("user",PageContext.SESSION_SCOPE);
out.print("Hello "+name);

JSP Directive Elements

The directive elements are used to do page related operation during page translation time.

JSP supports 3 types of directive elements, they are;.

 Page directive

 Include directive

 Taglib directive
Syntax of directive elements

Syntax

<@ directive attribute="value" %>

Page Directive

The page directive defines attributes that apply to an entire JSP page. This element is used to

define default of explicit operation to the jsp.

Syntax of page directive elements


Syntax

<@ page attribute="value" %>

Attributes of JSP page directive

 import

 contentType

 extends

 language

 buffer

 info

 isELIgnored

 isThreadSafe

 autoFlush

 session

 pageEncoding

 errorPage
 isErrorPage

JSP Include Directive

It is used to include some other pages into the JSP document, It may be JSP file, html file or

text file. This is known as static include because the target page is located and included at

the time of page compilation.

The jsp page is translated only once so it will be better to include static resource.

Advantage of Include directive

Code Re-usability

Syntax of Include directive elements

Syntax

<%@ include file="resourceName"%>

Example

<html>
<body>

<%@ include file="footer.html" %>

</body>
</html>

Taglib Directive

This is used to use custom tags in JSP page, here the custom tag may be user defined ot JSTL

tag or strust, JSF,..... etc.

Syntax
<@ taglib uri="uriofthetaglibrary" prefix="prefixoftaglibrary" %>

Attributes of taglib directive

 uri

Example of JSP Taglib directive


Example

<html>
<body>

<%@ taglib uri="http://www.tutorial4us.com/customtag/tags" prefix="mytag" %>

<mytag:currentDate/>

</body>
</html>

JSP Action Element

Action elements are used to performs specific operation using JSP container, like setting

values into java class, getting values from java class. The JSP action elements classified into

two types are;

 JSP Standard Action Element

 JSP Custom Action Element

Standard Action Element

Standard Action are given in JSP to separate the presentation logic and the business logic of

the JSP but partial.


The name is given as a standard Action, because each action as a pre-defined meaning and

as a programmer it is not possible to change the meaning of the tag.

Each Standard Action follows xml syntax, we do not have any equivalent html syntax.

The standard action element followed by "JSP" prifix.

Syntax of Standard Action Element

<jsp: standard action name>

Standard Action are given by JSP are;

 <jsp: include>

 <jsp: forward>

 <jsp: param>

 <jsp: params>

 <jsp: plugin>

 <jsp: useBean>

 <jsp: setProperty>

 <jsp: getProperty>

 <jsp: fallback>

You might also like