Professional Documents
Culture Documents
JSP
Application Development
Outline of Presentation
• JSP scripting elements
– Expressions, Scriptlets and declarations
• Implicit JSP Objects
• Conditional Processing
– Displaying Values, Declaring variables & Methods ..
• Error handling and Debugging
• Sharing Data Between JSP Pages, Requests, and Users
• Sharing Session and Application Data
• Memory usage Considerations
JSP Scripting Elements
• You can insert code into the servlet that will be
generated from the JSP page.
• Expressions: <%= expression %>
– Evaluated and inserted into the servlet’s output. i.e.,
results in something like out.println(expression)
• Scriptlets: <% code %>
– Inserted verbatim into the servlet’s _jspService method
(called by service)
• Declarations: <%! code %>
– Inserted verbatim into the body of the servlet class,
outside of any existing methods
JSP Implicit Objects
JSP Implicit objects are created automatically when a web server processes a
JSP page.
• request: The HttpServletRequest (1st arg to doGet)
• response: The HttpServletResponse (2nd arg to doGet)
• session
– The HttpSession associated with the request (unless disabled with the
session attribute of the page directive)
• out
– The stream (of type JspWriter) used to send output to the client
• application
– The ServletContext (for sharing data) as obtained via
getServletConfig().getContext().
• page, pageContext, config, exception
Implicit objects – Class files
• application: javax.servlet.ServletContext
• config: javax.servlet.ServletConfig
• exception: java.lang.Throwable
• out: javax.servlet.jsp.JspWriter
• page: java.lang.Object
• pageContext: javax.servlet.jsp.PageContext
• request: javax.servlet.ServletRequest
• response: javax.servlet.ServletResponse
• session: javax.servlet.http.HttpSession
JSP Expressions
• Format
– <%= Java Expression %>
• Result
– Expression evaluated, converted to String, and placed into HTML page
at the place it occurred in JSP page
– That is, expression placed in _jspService inside out.print
• Examples
– Current time: <%= new java.util.Date() %>
– Your hostname: <%= request.getRemoteHost() %>
• XML-compatible syntax
– <jsp:expression>Java Expression</jsp:expression>
– XML version not supported by Tomcat 3. Until JSP 1.2, servers are not
required to support it.
Example:
<HTML><HEAD>
<TITLE>JSP Expressions</TITLE>
<META NAME="author" CONTENT="Marty Hall">
<META NAME="keywords"
CONTENT="JSP,expressions,JavaServer,Pages,servlets">
<META NAME="description"
CONTENT="A quick example of JSP expressions.">
<LINK REL=STYLESHEET HREF="JSP-Styles.css" TYPE="text/css">
</HEAD>
<BODY>
<H2>JSP Expressions</H2>
Example
<UL>
<LI>Current time: <%= new java.util.Date() %>
<LI>Your hostname: <%= request.getRemoteHost() %>
<LI>Your session ID: <%= session.getId() %>
<LI>The <CODE>testParam</CODE> form parameter:
<%= request.getParameter("testParam") %>
</UL></BODY></HTML>
Example Result
• With default setup, if location was
– C:\<tomcatHome>\webapps\ROOT\Expressions.jsp
• URL would be
– http://localhost/Expressions.jsp
11
JSP Declarations
• Format
– <%! Java Code %>
• Result
– Code is inserted verbatim into servlet's class definition,
outside of any existing methods
• Examples
– <%! private int someField = 5; %>
– <%! private void someMethod(...) {...} %>
• XML-compatible syntax
– <jsp:declaration>Java Code</jsp:declaration>
Example Using JSP Declarations
…
<body>
<h1>JSP Declarations</h1>
<%! private int accessCount = 0; %>
<h2>Accesses to page since server reboot:
<%= ++accessCount %></h2>
</body></html>
After 15 total
visits by an
arbitrary number
of different clients
13
Scriptlets vs. Declarations
<%! int count=100; %> <% int count=100; %>
<%= ++count %> <%= ++count %>
Out Put
java.lang.RuntimeException: Error condition!!! ...... Opps... Sorry, an
error
occurred. Here is the exception stack trace:
Sharing Data Between JSP Pages,
Requests, and Users
• Any real application consists of more than a single page, and multiple
pages often need access to the same information and server-side resources.
• When multiple pages are used to process the same request, for instance one
page that retrieves the data the user asked for and another that displays it,
there must be a way to pass data from one page to another.
• In an application in which the user is asked to provide information in
multiple steps, such as an online shopping application, there must be a way
to collect the information received with each request and get access to the
complete set when the user is ready.
• Other information and resources need to be shared among multiple pages,
requests, and all users. Examples are information about currently logged-in
users, database connection pool objects, and cache objects to avoid
frequent database lookups
To share Data
• Need to know how to
• Various ways that JSP pages for collection of payment details can be
structured. Can even have everything on a single JSP page (messy for
anything but simplest apps)
infovalidate.jsp
Userinput.jsp confirmed.jsp
Validates the info
Displays a form displays a message
provided in
into which to user to confirm
userinput.jsp
user enters their payment made.
and passes back to
details userinput.jsp
if there’s an error, or
confirmed.jsp
if info is valid.
Presentation Request Presentation
processing and
business logic
Passing control from one page to
another
•Separating presentation pages from request
processing/business logic - more than one page used to
process client request
•When a JSP page needs to save data for its processing, it must specify the
scope of the data
•The scope of a data object defines how long the data is available for (I.e. ‘how
long it lasts’).
userinput.jsp: displays a payment form.
If an entry error is made, the infovalidate.jsp page forwards back to this with
the error.
Note: v. simple example for illustration. Details are not saved to a database
or file.
confirmed.jsp: displays the confirmation.
<html>
<head> Need to know whether this is the
<title>Payment Form</title> first time form is displayed
</head>
<body bgcolor="white">
<html>
<head>
<title>User Info Validated</title>
</head>
<body bgcolor="white">
<font color="green" size="+3">
Your payment details are correct - thank you
</font>
</body>
</html>
Note: This page is just template text (apart from comment) so could be created
as a regular HTML file. Making it a JSP page allows dynamic content later
without changing the referring page
Sharing Session & application Data
• HTTP is a stateless, request-response protocol. This means that the browser sends
a request for a web resource, and the web server processes the request and returns a
response. The server then forgets this transaction ever happened.
• So when the same browser sends a new request, the web server has no idea that this
request is related to the previous one.
•This is fine if you're dealing with static files, but it's a problem in an interactive web
application.
• In a travel agency application, for instance, it's important to remember the dates and
destination entered to book the flight so the customer doesn't have to enter the same
information again when it's time to make hotel and rental car reservations.
•The way to solve this problem is to let the server send a piece of information to the
browser that the browser then includes in all subsequent requests.
•This piece of information, called a session ID, is used by the server to recognize a
set of requests from the same browser as related: in other words, as part of the same
session.
•A session starts when the browser makes the first request for a JSP page in a
particular application. The session can be ended explicitly by the application, or the
JSP container can end it after a period of user inactivity (the default value is typically
30 minutes after the last request).
Sharing Session..(cont..)
Examples of session tracking information:
Shopping website: Items in a shopping cart:
-> Item1, “Gone with the Wind”)
->Item2, “BeatlesCD”)
- Select these on one web page, check-out in a different part of the
website. Web site “remembers” what you ordered by using session
tracking
Web banking application:
Bank employee selects the branch they are a member of. Session
stores this info in some way:
-> branch, “931012”
Application “remembers” the branch number so that employee does
not have to re-enter. Only customers relevant to the branch are
shown throughout.
Sharing Session..(cont..)
There are a number of different techniques available to web applications
to enable session tracking, including cookies (next course).
<html>
<head> header details etc </html>
<body bgcolor="white">
will last for the user’s session only
<%-- Increment counters --%>
<c:set var="sessionCounter" scope="session"
value="${sessionCounter + 1}" />
<c:set var="applCounter" scope="application"
value="${applCounter + 1}" />
<html><head>
<title>Session Values</title>
</head><body>
<%
session.setMaxInactiveInterval(10);
String name = (String)
session.getAttribute("username");
out.print("Welcome to my site " + name + "<br>");
%>
INE2720 – Web Application All copyrights reserved by C.C. Cheung
</body></html>
Software Development 2003.
38
Memory Usage Considerations
• You should be aware that all objects you save in the application and session
scopes take up memory in the server process. It's easy to calculate how
much memory is used for the application scope because you have full
control over the number of objects you place there. But the total number of
objects in the session scope depends on the number of concurrent sessions,
so in addition to the size of each object, you also need to know how many
concurrent users you have and how long a session lasts.
Example :
• Consider a CartBean class , It stores only references to ProductBean
instances, not copies of the beans. An object reference in Java is 8 bytes, so
with three products in the cart we need 24 bytes.
• The java.util.Vector object used to hold the references adds some overhead,
say 32 bytes. All in all, we need 56 bytes per shopping cart bean with three
products.
Important Questions
1. Explain Implicit Objects in JSP
2. Explain Error Handling and Debugging in JSP
3. Explain Memory usage considerations in JSP
Application development
4. Explain the dynamic content generation with an example
using JSP
5. Explain Sharing Session and an application with an
example
6. Explain Data sharing between JSP pages with an
example