You are on page 1of 40

Web Technologies

B.Tech. IT III Year II Semester


UNIT VII

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

All copyrights reserved by C.C. Cheung


2003.
JSP Scriptlets

• Format: <% Java Code %>


• Result
– Code is inserted verbatim into servlet's _jspService
• Example
– <%
String queryData = request.getQueryString();
out.println("Attached GET data: " + queryData);
%>
– <% response.setContentType("text/plain"); %>
• XML-compatible syntax
– <jsp:scriptlet>Java Code</jsp:scriptlet>
<%
for (int i=100; i>=0; i--)
{ JSP Scriptlets
%>
<%= i %> bottles of beer on the
wall.<br>
Example
<%
}
%>
Example Using JSP Scriptlets
<HTML>
<HEAD>
<TITLE>Color Testing</TITLE>
</HEAD>
<%
String bgColor =
request.getParameter("bgColor");
boolean hasExplicitColor;
if (bgColor != null) {
hasExplicitColor = true;
} else {
hasExplicitColor = false;
bgColor = "WHITE";
}
%>
<BODY BGCOLOR="<%= bgColor %>">

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 %>

public final class public final class


_scopeExpermnt1_xjsp _scopeExpermnt2_xjsp
{ {
int count=100; public void _jspService
(HttpServletRequest request,
public void _jspService HttpServletResponse response)
(HttpServletRequest request, throws java.io.IOException
HttpServletResponse response) {
throws java.io.IOException JspWriter out =
{ pageContext.getOut();
JspWriter out =
pageContext.getOut(); int count=100;

out.print( "\r\n" ); out.print( "\r\n" );

out.print( String.valueOf( ++co out.print( String.valueOf( ++co


unt ) ); unt ) );
out.print( "\r\n" ); out.print( "\r\n" );
}
} }
14
}
JSP Tags + HTML Tags
<h2>Table of Square Roots</h2>
<table border=2>
<tr>
<td><b>Number</b></td>
<td><b>Square Root</b></td>
</tr>
<%
for (int n=0; n<=100; n++)
{
%>
<tr>
<td><%=n%></td>
<td><%=Math.sqrt(n)%></td>
</tr>
<%
}
%>
</table> 15
Error Handling & Debugging
When you are writing JSP code, a programmer may leave a coding errors which can
occur at any part of the code. You can have following type of errors in your JSP
code:
• Checked exceptions: Achecked exception is an exception that is typically a user
error or a problem that cannot be foreseen by the programmer. For example, if a file
is to be opened, but the file cannot be found, an exception occurs. These exceptions
cannot simply be ignored at the time of compilation.
• Runtime exceptions: A runtime exception is an exception that occurs that probably
could have been avoided by the programmer. As opposed to checked exceptions,
runtime exceptions are ignored at the time of compliation.
• Errors: These are not exceptions at all, but problems that arise beyond the control
of the user or the programmer. Errors are typically ignored in your code because
you can rarely do anything about an error. For example, if a stack overflow occurs,
an error will arise. They are also ignored at the time of compilation.
• This tutorial will give you few simple and elegant ways to handle run time
exception/error occuring in your JSP code.
Error Handling (cont..)
Using Exception Object:

• The exception object is an instance of a subclass of Throwable (e.g., java.lang.


NullPointerException) and is only available in error pages. Following is the list of important
medthods available in the Throwable class.
1 public String getMessage()
Returns a detailed message about the exception that has occurred. This message is initialized
in the Throwable constructor.
2 public Throwable getCause()
Returns the cause of the exception as represented by a Throwable object.
3 public String toString()
Returns the name of the class concatenated with the result of getMessage()
4 public void printStackTrace()
Prints the result of toString() along with the stack trace to System.err, the error output stream.
5 public StackTraceElement [] getStackTrace()
Returns an array containing each element on the stack trace. The element at index 0 represents
the top of the call stack, and the last element in the array represents the method at the bottom
of the call stack.
6 public Throwable fillInStackTrace()
Fills the stack trace of this Throwable object with the current stack trace, adding to any
previous information in the stack trace.
Error Handling (cont..)
• JSP gives you an option to specify Error Page for each JSP. Whenever the page
throws an exception, the JSP container automatically invokes the error page.

• Following is an example to specifiy an error page for a main.jsp. To set up an


error page, use the <%@ page errorPage="xxx" %> directive.

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


<html> <head> <title>Error Handling Example</title> </head>
<body>
<% // Throw an exception to invoke the error page
int x = 1;
if (x == 1)
{
throw new RuntimeException("Error condition!!!");
}
%>
</body> </html>
Error Handling (cont..)
• Now you would have to write one Error Handling JSP ShowError.jsp, which is given
below.
• Notice that the error-handling page includes the directive <%@ page isErrorPage="true"
%>. This directive causes the JSP compiler to generate the exception instance variable.

<%@ page isErrorPage="true" %>


<html> <head> <title>Show Error Page</title> </head>
<body> <h1>Opps...</h1>
<p>Sorry, an error occurred.</p> <p>Here is the exception stack trace: </p> <pre>
<% exception.printStackTrace(response.getWriter()); %>
</pre> </body> </html>

Now try to access main.jsp, it should generate something as follows:

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

1) structure a JSP application

2) pass control from one JSP page to another

3) pass data from one JSP to another


Example
• A shopping application that accepts a users payment details on a form,
validates the details and displays a confirmation page or error
depending upon user input

• 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)

• Have used 3 JSP pages:


- payment details on a form(userinput.jsp)
- validation of the details (validateinfo.jsp)
- display of a confirmation page (confirmed.jsp) or error
(userinput.jsp) depending upon user input
Structure of JSP pages: example

Userinput.jsp infovalidate.jsp confirmed.jsp

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

--- need to be able to pass control from one page to another


--- e.g. in the example, infovalidate.jsp need to be
able to forward to either userinput.jsp or confirmed.jsp
depending on validation result

Can use the <jsp:forward> standard action tag


Passing control from one page to
another(cont..)
For example:

A validation page (infovalidate.jsp) forward control to a page, userinput.jsp, in


order to display an error message. Need to include error message in the
the forwarding instruction.

<jsp:forward page = “userinput.jsp”>


<jsp:param name = “msg” value =Target page
“invalid
credit card
number”/>
</jsp:forward>

Name of parameter to be passed


Value of parameter
Passing control from one page to
another
<jsp:forward page = “userinput.jsp”>

The target page in this example is assumed to be in


the same directory on the web server as the current
JSP page

<jsp:forward page = “/somedir/userinput.jsp”>


The target page in this example is assumed to be in
the /somedir/ directory as a subset of the main application
directory (../webapps/myapp/)

Note: the <c:redirect> tag is similar to the


<jsp:forward> tag, but also allows redirection to a different
URL.
Sharing data across pages : Scope
•Previous example creates a variable called ‘errorMsg’, and sets its value to
‘Invalid entry’. The scope of the variable is ‘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.

when the user clicks button, infovalidate.jsp is called.

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.

called by the infovalidate.jsp page if no errors


Sample code – user input.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<html>
<head> Need to know whether this is the
<title>Payment Form</title> first time form is displayed
</head>
<body bgcolor="white">

<form action="userinfovalidate.jsp" method="post">


<table>
<input type="hidden" name="submitted" value="true">
<c:if test="${param.submitted && !empty msg}">
<tr>
<td colspan="2">
<font color="red">
<c:out value = "${msg}"/>
</font> Check if there are any error
</td> messages to display. The’msg’
</tr> variable is set in the validation page
</c:if>
Sample code – user input.jsp
(continued)
<tr>
<td>Name:</td>
<td>
<input type="text" name="userName" value = "<c:out value =
"${param.userName}"/>">
</td>
<td>Credit card number:</td>
<td>
<input type="text" name="creditCardNumber" value = "<c:out valu
= "${param.creditCardNumber}"/>">
</td>
</tr>
<tr>
<td colspan=2>
<input type="submit" value="Send Data">
</td>
<tr> Display any previously enter
</table> values of username/credit card
</form> number
</body>
html>
Sample code – infovalidate.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%-- tests whether username and credit card have been entered --%>
<%-- if there's an error, set a msg variable --%>
Username request parameter
<c:choose>
<c:when test="${empty param.userName}">
<c:set var = "msg" value = "You must enter your username"
scope = "request"/>
<jsp:forward page="userinfoinput.jsp" />
</c:when>
<c:when test="${empty param.creditCardNumber}">
<c:set var = "msg" value = "You must enter your credit card
number" scope = "request"/>
<jsp:forward page="userinfoinput.jsp" />
</c:when>
<c:otherwise>
<jsp:forward page="confirmed.jsp" />
</c:otherwise> Must set scope to request.
</c:choose> Otherwise, the message won’t be
available to userinputinfo.jsp
Sample code – confirmed.jsp

<%-- displays a confirmation screen to the user --%>

<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).

 In JSP, can be done by simply using the ‘scope’ attribute of whatever


needs to be tracked.
 Set the ‘scope’ to session, and the relevant attribute will be available
throughout the entire session of the client
 Example: a JSP page that displays two counters – a hit counter for the
session, and a hit counter for the application
Sharing Session..(cont..)
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>

<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}" />

<h1>Counter page</h1> will be updated by all users’


of the applicaton
This page has been visited <b>
<c:out value="${sessionCounter}" />
</b> times within the current session, and <b>
<c:out value="${applCounter}" />
</b> times by all users since the application was started.
</body>
</html>
Working with Session object
• The session object has many useful methods that can
alter or obtain information about the current session.
– setMaxInactiveInterval(second)

<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

You might also like