Wt Unit5 Jsp

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 63

JSP Tutorial

• Java Server Pages (JSP) is a server-side programming


technology that enables the creation of dynamic,
platform-independent method for building Web-
based applications.
• JSP have access to the entire family of Java APIs,
including the JDBC API to access enterprise
databases.
• JSP tags can be used for a variety of purposes, such
as retrieving information from a database or
registering user preferences, accessing JavaBeans
components, passing control between pages and
sharing information between requests, pages etc.
Advantages of JSP:
• vs. Active Server Pages (ASP): The advantages of JSP
are twofold. First, the dynamic part is written in Java,
not Visual Basic or other MS specific language, so it is
more powerful and easier to use. Second, it is
portable to other operating systems and non-
Microsoft Web servers.
• vs. Pure Servlets: It is more convenient to write (and
to modify!) regular HTML than to have plenty of
println statements that generate the HTML.
• vs. JavaScript: JavaScript can generate HTML
dynamically on the client but can hardly interact with
the web server to perform complex tasks like
database access and image processing etc.
• vs. Static HTML: Regular HTML, of course, cannot
contain dynamic information.
JSP - Architecture
• JSP page is translated into servlet by the help
of JSP translator.
• The JSP translator is a part of webserver that
is responsible to translate the JSP page into
servlet.
• After that Servlet page is compiled by the
compiler and gets converted into the class file.
• All the processes that happens in servlet is
performed on JSP later like initialization,
committing response to the browser and
destroy.
Life cycle of a JSP Page
• The JSP pages follows these phases:
• Translation of JSP Page
• Compilation of JSP Page
• Classloading (class file is loaded by the classloader)
• Instantiation (Object of the Generated Servlet is created).
• Initialization ( jspInit() method is invoked by the container).
• Reqeust processing ( _jspService() method is invoked by the
container).
• Destroy ( jspDestroy() method is invoked by the container).
• Note: jspInit(), jspService() and jspDestroy() are the life
cycle methods of JSP.
Directory structure of JSP
• The directory structure of JSP page is same as servlet.
We contains the jsp page outside the WEB-INF folder
or in any directory.
JSP API
The JSP API consists of two packages:
• javax.servlet.jsp
• javax.servlet.jsp.tagext
javax.servlet.jsp package
The javax.servlet.jsp package has two interfaces and classes.
The two interfaces are as follows:
• JspPage
• HttpJspPage
The classes are as follows:
• JspWriter
• PageContext
• JspFactory
• JspEngineInfo
• JspException
• 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
• 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.
• 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:
• 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.
JSP Scriptlet tag (Scripting elements)

In JSP, java code can be written inside the jsp


page using the scriptlet tag.
JSP Scripting elements
The scripting elements provides the ability to
insert java code inside the jsp.
There are three types of scripting elements:
• scriptlet tag
• expression tag
• declaration tag
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
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>
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
<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

index.jsp
<html>
<body>
Current Time:
<%= java.util.Calendar.getInstance().getTime() %>
</body>
</html>
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 %>
Example of JSP declaration tag that declares field
index.jsp
<html>
<body>
<%! int data=50; %>
<%= "Value of the variable is:"+data %>
</body>
</html>
Example of JSP declaration tag that declares 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
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.
In this example we are simply displaying time.
index.jsp
<html>
<body>
<
% out.print("Today is:"+java.util.Calendar.getInstance().getTime())
; %>
</body>
</html>
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.
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);
%>
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.
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">
<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);
%>
5) JSP application implicit object
• In JSP, application is an implicit object of
type ServletContext.
• 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.
welcome.jsp
<%
out.print("Welcome "+request.getParameter
("uname"));
String driver=application.getInitParameter("dna
me");
out.print("driver name is="+driver);

%>
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.
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>
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>
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:
• page
• request
• session
• application
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.SESSIO
N_SCOPE);
<a href="second.jsp">second jsp page</a>
%>
</body>
</html>
second.jsp
<html>
<body>
<%

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

%>
</body>
</html>
8) page implicit object:
In JSP, page is an implicit object of type Object
class.
his object is assigned to the reference of auto
generated servlet class. It is written as:
Object page=this;
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.
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:
• page directive
• include directive
• taglib directive
Syntax of JSP Directive
<%@ directive attribute="value" %>
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
• Language
• isThreadSafe
• session
• pageEncoding
• errorPage
• isErrorPage
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>
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>
language
• The language attribute specifies the scripting
language used in the JSP page.
• The default value is "java".
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>
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.
//myerrorpage.jsp
<html>
<body>
<%@ page isErrorPage="true" %>
Sorry an exception occured!<br/>
The exception is: <%= exception %>
</body>
</html>
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).
Syntax of include directive
<%@ include file="resourceName" %>
Example of include directive
In this example, we are including the content of the
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.
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
Syntax JSP Taglib directive
<
%@ taglib uri="uriofthetaglibrary" prefix="prefix
oftaglibrary" %>
<html>
<body>
<%@ taglib uri="http://www.javatpoint.com/
tags" prefix="mytag" %>
<mytag:currentDate/>
</body>
</html>
JSP Action Tags
• There are many JSP action tags or elements.
• Each JSP action tag is used to perform some
specific tasks.
• The action tags are used to control the flow
between pages and to use Java Bean.
jsp:forward action tag
The jsp:forward action tag is used to forward the
request to another resource it may be jsp, html or
another resource.
Syntax of jsp:forward action tag without parameter
<jsp:forward page="relativeURL | <%= expression %>" />
Syntax of jsp:forward action tag with parameter
<jsp:forward page="relativeURL | <%= expression %>">
<jsp:param name="parametername" value="paramet
ervalue | <%=expression%>" />
</jsp:forward>
Example of jsp:forward action tag without
parameter
index.jsp
<html>
<body>
<h2>this is index page</h2>
<jsp:forward page="printdate.jsp" />
</body>
</html>
Example of jsp:forward action tag with parameter

<html>
<body>
<h2>this is index page</h2>

<jsp:forward page="printdate.jsp" >


<jsp:param name="name" value="javatpoint.com" />
</jsp:forward>

</body>
</html>
printdate.jsp
<html>
<body>
<
% out.print("Today is:"+java.util.Calendar.getInsta
nce().getTime()); %>
<%= request.getParameter("name") %>

</body>
</html>
jsp:include action tag
• The jsp:include action tag is used to include the
content of another resource it may be jsp, html
or servlet.
• The jsp include action tag includes the resource
at request time so it is better for dynamic
pages because there might be changes in future.
• The jsp:include tag can be used to include static
as well as dynamic pages.
Syntax of jsp:include action tag without
parameter
<jsp:include page="relativeURL | <%= expression %>" />
Syntax of jsp:include action tag with parameter
<jsp:include page="relativeURL | <%= expression %>">
<jsp:param name="parametername" value="parameterval
ue | <%=expression%>" />
</jsp:include>
File: index.jsp
<h2>this is index page</h2>
<jsp:include page="printdate.jsp" />
<h2>end section of index page</h2>
File: printdate.jsp
<
% out.print("Today is:"+java.util.Calendar.getInsta
nce().getTime()); %>

You might also like