0% found this document useful (0 votes)
30 views

Unit Iv JSP

Uploaded by

Nasapu Priya
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views

Unit Iv JSP

Uploaded by

Nasapu Priya
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 38

UNIT IV JSP

JSP Introduction
JSP technology is used to create web application just like Servlet technology. It can be
thought of as an extension to Servlet because it provides more functionality than servlet such
as expression language, JSTL, etc.

A JSP page consists of HTML tags and JSP tags. The JSP pages are easier to maintain than
Servlet because we can separate designing and development. It provides some additional
features such as Expression Language, Custom Tags, etc.

Advantages of JSP over Servlet


There are many advantages of JSP over the Servlet. They are as follows:

1) Extension to Servlet

JSP technology is the extension to Servlet technology. We can use all the features of the
Servlet in JSP. In addition to, we can use implicit objects, predefined tags, expression
language and Custom tags in JSP, that makes JSP development easy.

2) Easy to maintain

JSP can be easily managed because we can easily separate our business logic with
presentation logic. In Servlet technology, we mix our business logic with the presentation
logic.

3) Fast Development: No need to recompile and redeploy

If JSP page is modified, we don't need to recompile and redeploy the project. The Servlet
code needs to be updated and recompiled if we have to change the look and feel of the
application.

4) Less code than Servlet

In JSP, we can use many tags such as action tags, JSTL, custom tags, etc. that reduces the
code. Moreover, we can use EL, implicit objects, etc.
The Lifecycle of a JSP Page
The JSP pages follow these phases:

o Translation of JSP Page


o Compilation of JSP Page
o Classloading (the classloader loads class file)
o Instantiation (Object of the Generated Servlet is created).
o Initialization ( the container invokes jspInit() method).
o Request processing ( the container invokes _jspService() method).
o Destroy ( the container invokes jspDestroy() method).

Note: jspInit(), _jspService() and jspDestroy() are the life cycle methods of JSP.
As depicted in the above diagram, JSP page is translated into Servlet by the help of JSP
translator. The JSP translator is a part of the web server which is responsible for translating
the JSP page into Servlet. After that, Servlet page is compiled by the compiler and gets
converted into the class file. Moreover, all the processes that happen in Servlet are performed
on JSP later like initialization, committing response to the browser and destroy.

Creating a simple JSP Page

To create the first JSP page, write some HTML code as given below, and save it by .jsp
extension. We have saved this file as index.jsp. Put it in a folder and paste the folder in the
web-apps directory in apache tomcat to run the JSP page.

index.jsp

Let's see the simple example of JSP where we are using the scriptlet tag to put Java code in
the JSP page. We will learn scriptlet tag later.

1. <html>

2. <body>

3. <% out.print(2*5); %>

4. </body>

5. </html>

Output

It will print 10 on the browser.

How to run a simple JSP Page?

Follow the following steps to execute this JSP page:

o Start the server

o Put the JSP file in a folder and deploy on the server

o Visit the browser by the URL http://localhost:portno/contextRoot/jspfile, for example,


http://localhost:8888/myapplication/index.jsp
Do I need to follow the directory structure to run a simple JSP?

No, there is no need of directory structure if you don't have class files or TLD files. For
example, put JSP files in a folder directly and deploy that folder. It will be running fine.
However, if you are using Bean class, Servlet or TLD file, the directory structure is required.

The Directory structure of JSP

The directory structure of JSP page is same as Servlet. We contain the JSP page outside the
WEB-INF folder or in any directory.
The JSP API

The JSP API consists of two packages:

1. javax.servlet.jsp

2. javax.servlet.jsp.tagext

javax.servlet.jsp package

The javax.servlet.jsp package has two interfaces and classes.The two interfaces are as
follows:

1. JspPage

2. HttpJspPage

The classes are as follows:

o JspWriter

o PageContext

o JspFactory

o JspEngineInfo

o JspException

o JspError
The JspPage interface

According to the JSP specification, all the generated servlet classes must implement the
JspPage interface. It extends the Servlet interface. It provides two life cycle methods.

Methods of JspPage interface

1. public void jspInit(): It is invoked only once during the life cycle of the JSP when
JSP page is requested firstly. It is used to perform initialization. It is same as the init()
method of Servlet interface.

2. public void jspDestroy(): It is invoked only once during the life cycle of the JSP
before the JSP page is destroyed. It can be used to perform some clean up operation.
The HttpJspPage interface

The HttpJspPage interface provides the one life cycle method of JSP. It extends the JspPage
interface.

Method of HttpJspPage interface:

1. public void _jspService(): It is invoked each time when request for the JSP page
comes to the container. It is used to process the request. The underscore _ signifies
that you cannot override this method.

We will learn all other classes and interfaces later.

JSP Scriptlet tag (Scripting elements)

In JSP, java code can be written inside the jsp page using the scriptlet tag. Let's see what are
the scripting elements first.

JSP Scripting elements

The scripting element provides the ability to insert java code inside the jsp. There are three
types of scripting elements:

1. scriptlet tag

2. expression tag

3. declaration tag

1. JSP scriptlet tag

A scriptlet tag is used to execute java source code in JSP. Syntax is as follows:

<% java source code %>


Example of JSP scriptlet tag

In this example, we are displaying a welcome message.

<html>

<body>

<% out.print("welcome to jsp"); %>

</body>

</html>

Example of JSP scriptlet tag that prints the user name

In this example, we have created two files index.html and welcome.jsp. The index.html file
gets the username from the user and the welcome.jsp file prints the username with the
welcome message.

File: index.html

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

<html>

<body>

<%

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

out.print("welcome "+name);

%>

</form>

</body>

</html>

2. JSP expression tag

The code placed within JSP expression tag is written to the output stream of the response.
So you need not write out.print() to write data. It is mainly used to print the values of variable
or method.

Syntax of JSP expression tag

<%= statement %>

Example of JSP expression tag

In this example of jsp expression tag, we are simply displaying a welcome message.

<html>
<body>
<%= "welcome to jsp" %>
</body>
</html>

Note: Do not end your statement with semicolon in case of expression tag.
Example of JSP expression tag that prints current time

To display the current time, we have used the getTime() method of Calendar class. The
getTime() is an instance method of Calendar class, so we have called it after getting the
instance of Calendar class by the getInstance() method.

index.jsp

<html>
<body>
Current Time: <%= java.util.Calendar.getInstance().getTime() %>
</body>
</html>

Example of JSP expression tag that prints the user name

In this example, we are printing the username using the expression tag.
The index.html file gets the username and sends the request to the
welcome.jsp file, which displays the username.

File: index.jsp

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

File: welcome.jsp

<html>
<body>
<%= "Welcome "+request.getParameter("uname") %>
</body>
</html>
3. JSP Declaration Tag

The JSP declaration tag is used to declare fields and methods.

The code written inside the jsp declaration tag is placed outside the
service() method of auto generated servlet.

So it doesn't get memory at each request.

Syntax of JSP declaration tag

The syntax of the declaration tag is as follows:

<%! field or method declaration %>

Difference between JSP Scriptlet tag and Declaration tag

Jsp Scriptlet Tag Jsp Declaration Tag

The jsp scriptlet tag can only The jsp declaration tag can
declare variables not methods. declare variables as well as
methods.

The declaration of scriptlet tag The declaration of jsp declaration


is placed inside the tag is placed outside the
_jspService() method. _jspService() method.

Example of JSP declaration tag that declares field

In this example of JSP declaration tag, we are declaring the field and
printing the value of the declared field using the jsp expression tag.

index.jsp

<html>
<body>
<%! int data=50; %>
<%= "Value of the variable is:"+data %>
</body>
</html>
Example of JSP declaration tag that declares method

In this example of JSP declaration tag, we are defining the method which
returns the cube of given number and calling this method from the jsp
expression tag. But we can also use jsp scriptlet tag to call the declared
method.

index.jsp

<html>
<body>
<%!
int cube(int n){
return n*n*n*;
}
%>
<%= "Cube of 3 is:"+cube(3) %>
</body>
</html>
JSP Implicit Objects

There are 9 jsp implicit objects. These objects are created by the web
container that are available to all the jsp pages.

The available implicit objects are out, request, config, session, application
etc.

A list of the 9 implicit objects is given below:

Object Type

out JspWriter

request HttpServletRequest

response HttpServletResponse

config ServletConfig

application ServletContext

session HttpSession

pageContext PageContext

page Object

exception Throwable
1) JSP out implicit object

For writing any data to the buffer, JSP provides an implicit object named
out. It is the object of JspWriter. In case of servlet you need to write:

PrintWriter out=response.getWriter();

But in JSP, you don't need to write this code.

Example of out implicit object

In this example we are simply displaying date and time.

index.jsp

<html>
<body>
<% out.print("Today is:
"+java.util.Calendar.getInstance().getTime()); %>
</body>
</html>

Output
2) JSP 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.

Let's see the simple 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

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

welcome.jsp

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

Output
3) JSP 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.

Let's see the example of response implicit object where we are redirecting
the response to the Google.

Example of response implicit object


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

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

Output

4) JSP config implicit object

In JSP, config is an implicit object of type ServletConfig. This object can


be used to get initialization parameter for a particular JSP page. The
config object is created by the web container for each jsp page.

Generally, it is used to get initialization parameter from the web.xml file.


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>sonoojaiswal</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>sonoojaiswal</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);
%>

Output
5) JSP application implicit object

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

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 configuaration


file (web.xml). It can also be used to get, set or remove attribute from
the application scope.

This initialization parameter can be used by all jsp pages.

Example of application implicit object:

index.html

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

web.xml file

<web-app>

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

<servlet-mapping>
<servlet-name>sonoojaiswal</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>

welcome.jsp

<%

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

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

%>

Output
6) session implicit object

In JSP, session is an implicit object of type HttpSession.The Java


developer can use this object to set,get or remove attribute or to get
session information.

Example of session implicit object


index.html

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

welcome.jsp

<html>
<body>
<%

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

session.setAttribute("user",name);

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

%>
</body>
</html>

second.jsp

<html>
<body>
<%

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

%>
</body>
</html>

Output
7) 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:
o page
o request
o session
o application

In JSP, page scope is the default scope.

Example of pageContext implicit object

index.html

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

welcome.jsp

<html>
<body>
<%

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

pageContext.setAttribute("user",name,PageContext.SESSION_SCOP
E);

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

%>
</body>
</html>

second.jsp

<html>
<body>
<%

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

%>
</body>
</html>

Output
8) page implicit object:

In JSP, page is an implicit object of type Object class.This object is


assigned to the reference of auto generated servlet class. It is written as:
Object page=this;
For using this object it must be cast to Servlet type.For 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:
<% this.log("message"); %>

9) exception implicit object


In 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.It is better to learn it after page directive. Let's see
a simple example:

Example of exception implicit object:

error.jsp

<%@ page isErrorPage="true" %>


<html>
<body>

Sorry following exception occured:<%= exception %>

</body>
</html>

JSP directives

The jsp directives are messages that tells the web container how to
translate a JSP page into the corresponding servlet.

There are three types of directives:

o page directive
o include directive
o taglib directive

Syntax of JSP Directive

<%@ directive attribute="value" %>

A. JSP page directive


The page directive defines attributes that apply to an entire JSP page.

Syntax of JSP page directive

<%@ page attribute="value" %>

Attributes of JSP page directive

 import
 contentType
 extends
 info
 buffer
 language
 isELIgnored
 isThreadSafe
 autoFlush
 session
 pageEncoding
 errorPage
 isErrorPage

1)import

The import attribute is used to import class,interface or all the


members of a package.It is similar to import keyword in java class or
interface.

Example of import attribute

<html>
<body>

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


Today is: <%= new Date() %>

</body>
</html>
2)contentType

The contentType attribute defines the MIME(Multipurpose Internet Mail


Extension) type of the HTTP response.The default value is
"text/html;charset=ISO-8859-1".

Example of contentType attribute

<html>
<body>

<%@ page contentType=application/msword %>


Today is: <%= new java.util.Date() %>

</body>
</html>

3)extends

The extends attribute defines the parent class that will be inherited by the
generated servlet.It is rarely used.

4)info

This attribute simply sets the information of the JSP page which is
retrieved later by using getServletInfo() method of Servlet interface.

Example of info attribute


<html>
<body>

<%@ page info="composed by Sonoo Jaiswal" %>


Today is: <%= new java.util.Date() %>

</body>
</html>

The web container will create a method getServletInfo() in the resulting


servlet.For example:

public String getServletInfo() {


return "composed by Sonoo Jaiswal";
}

5)buffer

The buffer attribute sets the buffer size in kilobytes to handle output
generated by the JSP page.The default size of the buffer is 8Kb.

Example of buffer attribute

<html>
<body>

<%@ page buffer="16kb" %>


Today is: <%= new java.util.Date() %>

</body>
</html>

6)language
The language attribute specifies the scripting language used in the JSP
page. The default value is "java".

7)isELIgnored

We can ignore the Expression Language (EL) in jsp by the isELIgnored


attribute. By default its value is false i.e. Expression Language is enabled by
default. We see Expression Language later.

<%@ page isELIgnored="true" %>//Now EL will be ignored

8)isThreadSafe

Servlet and JSP both are multithreaded.If you want to control this
behaviour of JSP page, you can use isThreadSafe attribute of page
directive.The value of isThreadSafe value is true.If you make it false,
the web container will serialize the multiple requests, i.e. it will wait
until the JSP finishes responding to a request before passing another
request to it.If you make the value of isThreadSafe attribute like:

<%@ page isThreadSafe="false" %>

The web container in such a case, will generate the servlet as:

public class SimplePage_jsp extends HttpJspBase


implements SingleThreadModel{
.......
}

9)errorPage

The errorPage attribute is used to define the error page, if exception


occurs in the current page, it will be redirected to the error page.

Example of errorPage attribute


//index.jsp

<html>
<body>

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

<%= 100/0 %>

</body>
</html>

10)isErrorPage

The isErrorPage attribute is used to declare that the current page is the
error page.

Note: The exception object can only be used in the error page.

Example of isErrorPage attribute

//myerrorpage.jsp

<html>
<body>

<%@ page isErrorPage="true" %>

Sorry an exception occured!<br/>


The exception is: <%= exception %>

</body>
</html>
B. Jsp Include Directive

The include directive is used to include the contents of any resource it


may be jsp file, html file or text file. The include directive includes the
original content of the included resource at page translation time (the jsp
page is translated only once so it will be better to include static resource).

Advantage of Include directive

Code Reusability

Syntax of include directive

<%@ include file="resourceName" %>

Example of include directive


In this example, we are including the content of the header.html file. To
run this example you must create an header.html file.

<html>
<body>

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

Today is: <%= java.util.Calendar.getInstance().getTime() %>

</body>
</html>

Note: The include directive includes the original content, so the actual page size
grows at runtime.

C. JSP Taglib directive

The JSP taglib directive is used to define a tag library that defines many tags. We use the
TLD (Tag Library Descriptor) file to define the tags. In the custom tag section we will use
this tag so it will be better to learn it in custom tag.

Syntax JSP Taglib directive

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

Example of JSP Taglib directive

In this example, we are using our tag named currentDate. To use this tag we must specify the
taglib directive so the container may get information about the tag.

<html>
<body>
<%@ taglib uri="http://www.javatpoint.com/tags" prefix="mytag" %>

<mytag:currentDate/>

</body>
</html>

You might also like