2. Servlet Drawbacks
Web page designer will need to know
servlets to design the page.
Servlet will have to be compiled for
every change in presentation.
Servlet with too many embedded HTML
tags become very difficult to read.
Servlet programmer will have to be a
page designer also.
3. JSP advantage
JSPs allow web pages to be created
dynamically.
JSPs are basically files that combine
standard HTML and new scripting tags.
JSP specification is to simplify the creation
and management of dynamic web pages, by
separating logic and presentation.
JSPs are important part of J2EE specification.
4. Deciding between Servlet and
JSP
MVC architecture
JSP is mostly used as View
Servlet is Controller
Models are Java beans or entity beans.
5. Most common scenario
HTML/JSP
Form submitted
Page Servlet
Form data validated
and passed
Java Bean
Form data stored
7. More…
It takes longer time for the first JSP
page to load.
Time taken to load any subsequent
requests for the same page is same as
that of a servlet.
JSP documents are written in plain text
and have a .jsp file extension.
9. Scripting element
JSP elements embedded with HTML tags.
Scriplets are small pieces of java code added
to a JSP page to provide logical functionality.
Scriplets are enclose within <% ... %>.
Expressions are use to evaluate a single
code expression then add the result to the
JSP page as text String. <%= ... %>.
Comments : (Inside scriptlets ): //, /* */.
10. Example 1: Displays current
date and time
<html>
<head>
<title> Example 1 </title>
</head>
<body>
<% java.util.Date now=new java.util.Date();%>
<h2> Server date and time is <%=now %></h2>
</body>
</html>
11. Local Variables
The JSP turns into a servlet class and all the
scriptlets are placed inside a single method of
this class (called _jspservice() method
equivalent to the service() method of the
HttpServlet).
So, all the variables that is declared inside the
scriptlet is local to that method.
Therefore, local variables are available locally to
all the other code in that page. Example in 1 has
a local variable 'now' declared.
12. <html>
<head>
<title> Example 1
</title>
</head>
<body>
<% java.util.Date now=new
java.util.Date();%>
<h2> Server date and time
is <%=now %></h2>
</body>
</html>
public class XJSP extends HttpJspPage {
public void jspInit(){..}
public void jspDestroy(){..}
public void _jspService(){
//scriptlet code converted
}
•jspInit(), jspDestroy() and _jspService() are similar to init(),
destroy() and service() method of HttpServlet.
•While implementations for jspInit() and jspDestroy() methods
can be provided in the JSP, implementation for _jspService()
should never be provided. This method will be generaeted by
the container.
13. JSP Declarations
In order to make declarations such that
variable is not only available locally to all
the other code in that page but also
available globally to other parallel requests
for that page, we have to use – <%! .. %>
Methods also can be declared here.
14. Example 2: Global page
counter
<html>
<head>
<title> Example 1 </title>
jsp/1.pageCounter
</head>
<body>Date and Time:<%=getDate()%>
<%! int counter=0;
java.util.Date getDate(){
return new java.util.Date()
}%>
Thank you for visiting this page <BR>
You are vistor number <%= ++counter %>.
</body>
</html>
15. 9 Implicit JSP objects:
1. request object
request object : This object can be used
to access lots of information contained
in the HTTP request header sent from a
browser when requesting a JSP page.
The request object is analogous to
request object in servlet.
Common Examples:
<%=request.getParameter("name");%>
16. Implicit JSP objects:
2. response object
response object: This object is used in
response header that are sent to the
browser from the server along with the
current page.
The request object is analogous to
request object in servlet.
Common Examples:
<% response.setContentType("text/html"); %>
<%
response.sendRedirect("http://localhost:8080/an
other.html") %>
17. Implicit JSP objects:
3. application object
application object: This object is used to
hold references to other objects that may be
accessed by multiple users. One such object
is database connectivity.
Represents the ServletContext object in
servlet.
Methods: getAttribute(), setAttribute().
Common Examples:
<% application.setAttribute("applName",
"CollegePortal"); %>
<%= application.getAttribute("applName")%>
18. Implicit JSP objects:
4.session object
When a JSP page is opened in a
browser a unique session identity is
allocated for each user accessing that
application.
Represents HttpSession object in
Servlet
Methods: getAttribute(),
setAttribute(), invalidate(),getId().
19. Example 3: session object
<html>
<body>Session ID :<%=session.getId() %>
<% session.invalidate();
if (session.getId() !=null) %>
Session ID :<%=session.getId() %>
<% else %>
Session has ended
</body>
</html>
20. Implicit JSP objects:
5.out object
This object handles text output to browser
from the JSP page.
An instance of javax.servlet.jsp.JspWriter..
Example:
<% out.println("<h1>" +
application.getAttribute("application
Name") + "</h1>"); %>
21. 6. exception
exception object: The exception object
is available only to pages which are
defined as error pages by setting the
value for the attribute isErrorPage in the
page directive.
More about this later
23. 8. pageContext
Used to organize references to all of the
objects involved in creating a jsp page.
JSP engine writes the code that obtains
the implicit objects from this object.
getException()
getPage()
getOut()
getRequest()
getResponse
getSession()
getResponse()
getServletConfig()
getServletContext()
26. JSP Directives
JSP directive are messages that are
sent to JSP processor from JSP.
These are used to set global values for
the jsp page and do not produce any
output.
<%@ directivename attribute=“value”
%>
The page directive
The include directive
27. Page directive
A page can contain any no. of page
directives, anywhere in the jsp.
However, there can be only one
occurrence of any attribute/value
pair defined by the page directive in
a given jsp. Only exception is the
import attributes.
28. page directive attributes
contentType: Specifies the MIME type to be
used for JSP page that is going to be
generated. (default: text/html)
errorPage: Defines a URL to another JSP
page, which is invoked if an unchecked
runtime exception is thrown.
isErrorPage: If true, then current jsp page is an
error page for another jsp page. Gives access
to a JSP implicit exception variable when true
to allow an error to be examined and handled.
29. import: similar to import statement in java class
Classes within the following packages are available by
default: java.lang.*, javax.servlet.*, javax.servlet.jsp.*,
javax.servlet.http.*
Example:
<%@ page import=“java.sql.*, java.util.*,javax.naming.*”>
session: If true, the implicit object variable session will
refer to a session object either already existing for the
requesting user, or explicitly created for the page
invocation. If false, then any reference to the session
implicit object within the JSP page results in a
translation-time error. The default is true.
If your JSP page is not intended to interact with
session objects then creation of session object could
be an overhead. If this is the case, then you should
ensure that the <%@ page session=”false” %>
directive tag is included within your JSP.
30. Example: using ‘import’
<%@ page language=“Java” import=“java.util.*”>
<html>
<head>
<title> Example 1 </title>
</head>
<body>
<% Date now=new Date();%>
<h2> Server date and time is <%=now %></h2>
</body>
</html>
32. Result: <input type="text" name="result"
value="
<% String num1=request.getParameter("num1");
String num2=request.getParameter("num2");
if (num1!=null && num2!=null){
int n1=Integer.parseInt(num1);
int n2=Integer.parseInt(num2);
int r= n1/n2;
out.print( r);
} }
%>">
</form></body></html>
33. error.jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0
Transitional//EN">
<%@ page contentType="text/html" %>
<%@ page isErrorPage="true" %>
<html>
<head><title>Error Handling</title></head>
<body>
Error: <%= exception.getMessage() %>
</body>
</html>
34. Include directive
This tag is useful to merge the content of
an external static file with the contents of a
JSP page.
<%@ include file=“filename” %>
Example:
<%@ include file=“agreement.txt” %>
<%@ include file=“date.jsp” %>
35. JSP tag included
The included file may contain any valid JSP tags.
These tags will be translated to Java source and
included in the JSP page compilation class.
One consequence of the fact that the file
referenced within the include directive is included
during the translation phase is that subsequent
changes to the included file will not be picked up
by the Web container on subsequent invocations
of the JSP. The changes will only be visible when
the JSP containing the include directive is itself
updated, or its JSP page compilation class is
deleted, forcing the translation phase to be carried
out. If this behavior is not desirable you can use
the include action tag instead.
37. Java Beans
A java bean is simply a java class that
meet the following criteria:
1. The class must be public.
2. The class must have a no-arguments
constructor.
3. The class must provide set and get
methods to access variables.
38. Standard Action Tags
These tags translate into to certain predefined
java code.
They are used so that the JSP file doesn't have
to many embedded java code.
<jsp:useBean>
<jsp:setProperty>
<jsp:getProperty>
<jsp:param>
<jsp:forward>
<jsp:include>
39. <jsp:useBean>
This action tag is used to instantiate or
create a reference to a Java Class (Bean)
inside a JSP page.
<jsp:useBean id=“name” class=“className”
type=“typeToBeCreated” scope=“scope”>
id: variable name for the Java Class that is
going to be used in the JSP.
class: Fully qualified class name
scope: page, request, session and application.
Default is page.
type:This is optional. Indicates the type of
object to be created.
<jsp:useBean id=“s” class=“Student” scope=“page”>
Student s=new Student() ;
40. Scope
page scope means that the object available only to this
page.
request scope means that the object is now associated
with the request. If the request is forwarded (using
<jsp:forward> or <jsp:include> tag ) to another JSP, the
object is available. This object can be accessed by
invoking getAttribute() method on request object.
session scope means that object will be available to all
JSPs in the current session.
application scope means that the object will be
available in any JSP page in the same web application.
This object can be accessed by invoking getAttribute()
method on request object.
41. <jsp:setProperty> and
<jsp:getProperty>
<jsp:setProperty> tag is used along with
<jsp:useBean> tag, to set values of the bean
property.
<jsp:setProperty name=“beanName”
property=“property”
value=“propertyValue”/>
<jsp:getProperty> tag is used along with
<jsp:useBean> tag, to get values of the bean
property.
<jsp:getProperty name=“beanName”
property=“property”/>
42. Attributes Values
beanName is the name of the bean instance which
has been created using the <jsp:useBean> tag.
property: name of the bean property. It can also be
’*’. If so, if request parameters have the same name
as the bean property, then the value of the request
parameter is automatically set to the bean property.
value: Value to be set to the property.
param:The name of the request parameter whose
value the bean property will be set to.
property=“property” value=”value”
property=“property”
property=“property” param =”param”
property=“*”
43. Student.java
sr.Student
-name
-reg
+String getName()
+String getReg()
+void setReg(String reg)
+void setName(String nm)
JSP page implementation
class will attempt to assign the
value of
request.getParameter(“name”)
to the bean property.
<jsp:useBean id=“stud” class=“sr.Student”>
<jsp:setProperty name=“stud” property=“name”/>
<jsp:setProperty name=“stud” property=“name” param=“nm” />
<jsp:setProperty name=“stud” property=“reg” value=“1234”/>
</jsp:useBean>
..
<jsp:getProperty name=“stud” property=“reg”/>
Displays value of reg
request.
getParameter(“n
m”)
44. Student.java
sr.Student
-name
-reg
+String getName()
+String getReg()
<jsp:useBean id=“stud”
class=“sr.Student”>
<jsp:setProperty name=“stud”
property=“*”/>
</jsp:useBean>
…..
<FORM ACTION=“stud.jsp”
METHOD=“post”>
<INPUT TYPE=“text”
NAME=“name”>
<INPUT TYPE=“text” NAME=“reg”>
…
stud.jsp
stud.html
On submitting the form the name
and reg property of the stud bean
is automatically set to the values
entered by the user.
If there is no matching request parameter
for a bean property then it remains unset.
You should always make sure that your
bean’s default constructor sets appropriate
default values.
+void setName(String nm)
+void setReg(String reg)
45. The Web container will automatically attempt to convert the
String into the type of the bean parameter. This conversion
will work for the following types:
Boolean or boolean
Byte or byte
Character or char
Double or double
Integer or int
Float or float
Long or long
46. <jsp:param>
The <jsp:param> action is used to
provide other tags with additional
information in the form of the name-value
pairs.
It is used in conjunction with the
<jsp:include> & <jsp:forward>
<jsp:param name=“p1” value=“pv”>
47. <jsp:include>
This tag allows static or dynamic
resource to be included in the
current JSP page at the request
processing time.
Similar to RequestDispatcher’s
include() method.
<jsp:include page=“URL”>
<jsp:include page=“first.jsp”>
48. Example
<jsp:include page=“x.jsp”>
<jsp:param name=“p1” value=“pv1”/>
<jsp:param name=“p2” value=“pv2”/>
</jsp:include>
The argument can be extracted by using
request.getParameter(“p1”) in servlet/jsp.
49. <jsp:include> and <%@
include>
<jsp:include> <%@ include>
1. <jsp: include page=“filename” /> 1. <%@ include file=“filename” %>
2. Done at the request processing
time
2. Done at the translation time.(That is, the
contents of the included file will be included
in the JSP source at the point where the
tag is defined and therefore processed by
the JSP page compilation procedure.
3. Both static and dynamic
content can be included.
3. The included file may contain both
static content and other JSP tags.
50. <jsp:forward>
This tag allows the JSP to transfer the control
to another JSP, servlet or static HTML page.
The jsp that forwards the request should not
use the output stream that is used to
communicate to the client prior to forwarding
the request.
<jsp:forward page=“URL”/>
51. Example:
forward.html
<html>
<head>
jsp/4.forward
<title>Forward action test
page</title>
</head><body>
<h1>Forward action test page</h1>
<form method=“post”
action=‘forward.jsp”>
<p>Please enter your username:
<input type=“text” name=“userName”>