Java Server Pages

bgjeecourse 4,964 views 49 slides Mar 22, 2011
Slide 1
Slide 1 of 49
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44
Slide 45
45
Slide 46
46
Slide 47
47
Slide 48
48
Slide 49
49

About This Presentation

Presentation about JavaServer Pages (JSP).


Slide Content

JavaServer Pages (JSP)
Svetlin Nakov
Borislava Spasova
Creating Dynamic Web Pages

Contents
1.Introduction to JSP Technology
2.JSP Expressions
3.Predefined JSP Variables
4.JSP Scriptlets
5.JSP Pages are Actually Servlets
6.JSP Declarations
7.JSP Directives
•The JSP @page Directive
•Static and Dynamic Include

Contents (2)
1.More About The JSP Predefined Variables
•Using The "application" Object
2.Client and Server Redirection
3.HTML Escaping Problems

Introduction to JSP
Technology

What is JSP?
•JavaServer Pages (JSP) is:
•Technology for generating dynamic Web
content
•Allows Java programming code to be
embedded in the HTML pages
•The Java code is executed on the server
during the rendering of the JSP page
•After execution of a JSP page a plain HTML is
produced and displayed in the client's Web
browser

JSP Technology
•JSP pages provide an easy way to develop
dynamic Web applications
•Operate in a request/response mode
•Like Java servlets
•Generate dynamic content with very little or
no coding (for non-programmers)
•Contain HTML text freely mixed with Java
code (for advanced programmers)
•Can use various XML tags that simplify
development

Date JSP Page – Example
•Sample JSP page that displays the current
date and time
<html> <html>
<head><title>Date JSP <head><title>Date JSP exampleexample</title></head> </title></head>
<body> <body>
The date is: The date is:
<% out.println(new java.util.Date()); %> <% out.println(new java.util.Date()); %>
</body> </body>
</html></html>
date.jspdate.jsp

JSP Expressions
•A JSP expression is used to insert the result of a
Java expression directly into the output
•It has the following form:
•Examples:
<%= Java<%= Java e expression %> xpression %>
The time isThe time is: <%= new java.util.Date() %>: <%= new java.util.Date() %>
The square root of 2 isThe square root of 2 is : <%= : <%= Math.sqrt(2)Math.sqrt(2) %> %>
The value of PI is: <%= Math.PI %>The value of PI is: <%= Math.PI %>

Predefined JSP Variables
•JSP pages support a number of predefined
variables that you can use
•request – current HttpServletRequest
•response – the HttpServletResponse
•session – current HttpSession associated
with the request (if any)
•out – the text stream for the result of the JSP
page (PrintWriter)
•These variables are always initialized and can be
used in any place in the JSP page

JSP Expressions –
More Examples
•The following example uses the predefined
variable request to show the remote host of
the client machine:
•Getting the default session timeout
•Getting the client's Web browser identification:
Your hostname: <%= request.getRemoteHost() %> Your hostname: <%= request.getRemoteHost() %>
Session timeoutSession timeout: :
<%= session.getMaxInactiveInterval() %> <%= session.getMaxInactiveInterval() %>
Browser: <%= Browser: <%= request.getHeader("User-Agent") request.getHeader("User-Agent") %>%>

JSP Scriptlets
•JSP scriptlets allow Java code to be inserted in
the JSP pages
•Scriptlets have access to the automatically
defined variables in the JSP pages (request,
response, session, ...)
<% Java <% Java ccode %>ode %>
<% <%
String queryData = request.getQueryString();String queryData = request.getQueryString();
out.println("Attached GET data: " + queryData);out.println("Attached GET data: " + queryData);
%>%>

JSP Scriptlets – Example
•Example of using Java code in a JSP page:
•Example of using loop:
<% if (Math.random() < 0.5) { %><% if (Math.random() < 0.5) { %>
Have a <B>nice</B> day!Have a <B>nice</B> day!
<% } else { %><% } else { %>
Have an <B>interesting</B> day!Have an <B>interesting</B> day!
<% } %><% } %>
<% for (int i=0; i<10; i++) { %><% for (int i=0; i<10; i++) { %>
<%= i %> * <%= i %> = <%= i*i %><%= i %> * <%= i %> = <%= i*i %>
<br><br>
<% } %><% } %>

JSP Internals
How JSP Pages Are Transformed to
Servlets?

JSP Technology Internals
•JSP pages are actually servlets!
•The Web container translates JSP pages into
Java servlet source code (.java)
•Then compiles that class into Java servlet
class
•JSP pages have the same life cycle like
servlets
JSP PageJSP Page
((datedate.jsp.jsp))
Java servletJava servlet
((datedate.java.java))
CompiledCompiled
Java servletJava servlet
((datedate..classclass))
JSPJSP
compilercompiler
javacjavac

JSP Technology Internals
•Tomcat stores the compiled JSP pages in the
directory CATALINA_HOME/work
<html> <html>
<head><title>Date JSP<head><title>Date JSP
example</title></head>example</title></head>
<body> <body>
The date is: <% The date is: <%
out.println(newout.println(new
java.util.Date()); %> java.util.Date()); %>
</body> </body>
</html></html>
date.jspdate.jsp
JSPJSP
compilationcompilation
packagepackage
org.apache.jsp;org.apache.jsp;
public final classpublic final class
date_jsp extendsdate_jsp extends
HttpJspBaseHttpJspBase
implementsimplements
JspSourceDependent JspSourceDependent
{{
......
}}
date_jsp.javadate_jsp.java
\webapps\JSP-Demos\\webapps\JSP-Demos\
date.jspdate.jsp
\work\Catalina\localhost\\work\Catalina\localhost\
JSP-Demos\org\apache\jspJSP-Demos\org\apache\jsp

JSP Declarations
and Directives

JSP Declarations
•A JSP declaration lets you define methods or
fields that get inserted into the main body of
the servlet class
•It has the following form:
•Example:
<%! Java <%! Java ccodeode (fields and methods) (fields and methods) %> %>
<%! <%!
long counter = 0; long counter = 0;
public void getCounter() { return counter; }public void getCounter() { return counter; }
%>%>

JSP Declarations
•Declarations do not generate any output
•Normally are used in conjunction with JSP
expressions or scriptlets
•Example:
•Printing how many times a page is displayed
since its loading on the server:
<%! private <%! private static static int accessCount = 0; %>int accessCount = 0; %>
This page has been accessedThis page has been accessed
<%= ++accessCount %><%= ++accessCount %> times. times.

JSP Directives
•A JSP directive affects the overall structure
of the servlet class
•Usually has the following form:
•Or have multiple attributes:
<%@ directive attribute="value" %><%@ directive attribute="value" %>
<%@ directive attribute1="value1" <%@ directive attribute1="value1"
attribute2="value2"attribute2="value2"
......
attributeN="valueN" %>attributeN="valueN" %>

The JSP @page Directive
•The page directive lets you define one or more
page attributes:
•Specifying what packages should be imported
•Example:
•The import attribute is the only one that is
allowed to appear multiple times
import="package.classimport="package.class " " oror
import="package.class1,import="package.class1, ...,..., package.classN" package.classN"
<%@ page import="java.util.*" %><%@ page import="java.util.*" %>

The JSP @page Directive (2)
•Specifying the MIME type of the output (the
default is "text/html")
•For example, the directive:
has the same effect as the scriptlet:
contentType="MIME-Type" or contentType="MIME-Type" or
contentType="MIME-Type; charset=Character-Set"contentType="MIME-Type; charset=Character-Set"
<%@ page contentType="text/plain" %><%@ page contentType="text/plain" %>
<% response.setContentType("text/plain"); %> <% response.setContentType("text/plain"); %>

The JSP @page Directive (3)
•Defining whether the page will use the implicit
session object (default is true)
•Defining an URL to the page to which all
uncaught exceptions should be sent
•Declaring the current page as error page (allows
access to the exception object)
session="true|false"session="true|false"
errorPage="url"errorPage="url"
isErrorPage="true|false"isErrorPage="true|false"

The JSP @include Directive
•Lets you include files at the time the JSP page is
translated into a servlet (also called static
include)
•The directive looks like this:
•The URL specified is interpreted as relative to the
JSP page that refers to it
•Example:
<%@ include file="relative url" %><%@ include file="relative url" %>
<%@ include file="/<%@ include file="/include/include/menu.jsp" %>menu.jsp" %>

Using JSP @include Directive
•Using the @include directive to include a
small navigation bar on each page
<<htmlhtml>>
<<bodybody>>
<%@ include file="/navbar.html" %><%@ include file="/navbar.html" %>

<!-- Part specific to this page ... --><!-- Part specific to this page ... -->
</</bodybody>>
</</htmlhtml>>

Dynamic Include
•Including a page at runtime (dynamic include):
•Dynamic include executes the page at runtime
and appends the results of it
•More powerful and flexible
<jsp:include page="header.jsp"<jsp:include page="header.jsp" /> />
<% String headerPage = "header.jsp"<% String headerPage = "header.jsp" ;; %> %>
<jsp:include page="<%= headerPage %>" /> <jsp:include page="<%= headerPage %>" />

JSP Predefined Variables
request, response, session,
application, config, …

More About The JSP Predefined
Variables
•request
•The HttpServletRequest associated with the
request
•Allows accessing the request parameters, HTTP
headers, cookies, etc.
•response
•The HttpServletResponse associated with the
response to the client
•It is legal to set HTTP status codes and response
headers (because the output stream is buffered)

More About The JSP Predefined
Variables (2)
•out
•The PrintWriter used to send text output to the
client
•session
•The HttpSession object associated with the
request
•Sessions are created automatically, so this
variable is bound even if there was no incoming
session reference
•Can store state information about the current
client

More About The JSP Predefined
Variables (3)
•application
•The ServletContext as obtained via
getServletConfig().getContext()
•Can store information accessible from whole the
application
•All servlets and JSP pages can share information
through this object
•pageContext
•Encapsulates all other implicit JSP objects
(request, response, session, ...) in a
PageContext instance

More About The JSP Predefined
Variables (4)
•page
•Synonym of this object (not very useful)
•exception
•The implicit Throwable object
•Available only in the error pages
•Contains the last exception
•config
•Contains the ServletConfig for the current JSP
page
•Useful for accessing the init parameters

Using The application Object
•Always use the application object in a
synchronized section
•It is shared object between all threads
•Web containers run a separate thread for
each client request
synchronized (application)synchronized (application) { {
VectorVector items = (Vector)items = (Vector)
application.getAttributeapplication.getAttribute ("items");("items");
if (sharedItems == null) {if (sharedItems == null) {
sharedItems = new Vector ();sharedItems = new Vector ();
application.setAttributeapplication.setAttribute ("items", items);("items", items);
}}
}}

Using The application Object –
Example
<%@ page import="java.util.Vector" %><%@ page import="java.util.Vector" %>
<%// Get the global list of shared items<%// Get the global list of shared items
Vector<String> sharedItems;Vector<String> sharedItems;
synchronized (application)synchronized (application) { {
sharedItems = (Vector<String>)sharedItems = (Vector<String>)
application.getAttributeapplication.getAttribute ("items");("items");
if (sharedItems == null) {if (sharedItems == null) {
sharedItems = new Vector<String>();sharedItems = new Vector<String>();
application.setAttributeapplication.setAttribute ("items", sharedItems);("items", sharedItems);
}}
}}
// Append the new item (if exists)// Append the new item (if exists)
String newItem = request.getParameter("item");String newItem = request.getParameter("item");
if (newItem != null)if (newItem != null)
sharedItems.addElement(newItem);sharedItems.addElement(newItem);
%>%>

Using The application Object –
Example (2)
<html><html>
<head><title>Global Shared List</title></head><head><title>Global Shared List</title></head>
<body><body>
Available shared items:Available shared items:
<ol><ol>
<% for (String item : sharedItems) {<% for (String item : sharedItems) { %>%>
<li><%= item %></li><li><%= item %></li>
<% }<% } %>%>
</ol></ol>
<form method="POST" <form method="POST"
action="Global-Shared-List.jsp">action="Global-Shared-List.jsp">
<input type="text" name="item"><input type="text" name="item">
<input type="submit" value="Add"><input type="submit" value="Add">
</form></form>
</body></body>
</html></html>

Client and Server
Redirections

Client Redirection to Another
URL
•Client redirection
•Redirects the client's Web browser to given
new relative URL
•Actually sends HTTP response code 302
(Resource moved temporarily)
•The browser requests the new location
•Example:
response.sendRedirect(<url>);response.sendRedirect(<url>);
response.sendRedirect("date.jsp");response.sendRedirect("date.jsp");

Server Redirection to Another
Resource
•Server redirection
•Returns the contents of given resource at
the server
•The browser does not know that a
redirection is occurred at the server
•Example:
request.getRequestDispatcher(<url>).request.getRequestDispatcher(<url>).
forward(request, response)forward(request, response)
request.getRequestDispatcher("date.jsp").request.getRequestDispatcher("date.jsp").
forward(request, response);forward(request, response);

<jsp:forward>
•Forwards a client request to an HTML file,
JSP file, or servlet for processing
•Simple syntax
•Syntax with parameters
<jsp:forward page=<jsp:forward page=
{"{"relativeURLrelativeURL" |" | "<%= "<%= expressionexpression %>"} /> %>"} />
<jsp:forward <jsp:forward
page={"page={"relativeURLrelativeURL" |" | "<%="<%= expression expression %>"} > %>"} >
<jsp:param name="<jsp:param name="parameterNameparameterName""
value="{value="{parameterValueparameterValue | | <%= <%= expressionexpression %>}" /> %>}" />
</jsp:forward> </jsp:forward>

<jsp:forward> – Example
•Example:
•<jsp:forward> actually performs a server-
side redirection
•The client does not know that a redirection
has occurred
<jsp:forward page="Global-Shared-List.jsp"><jsp:forward page="Global-Shared-List.jsp">
<jsp:param name="<jsp:param name="itemitem" value=" value=
"This item is added by JSP-forward.jsp" />"This item is added by JSP-forward.jsp" />
</jsp:forward></jsp:forward>

Escaping Problems
And How to Avoid Them

Escaping Problems
•Escaping problems are very common in the
Web programming
•Displaying not escaped text is dangerous
•Makes the application unstable
•Opens security vulnerabilities
•When displaying text it should not contain
any HTML special characters
•Performing escaping of the HTML entities is
obligatory!

Escaping Problems – Example
•Consider the following JSP page:
•What will happen if we enter this?
<html><html>
You entered:You entered:
<%= request.getParameter("something") %><%= request.getParameter("something") %>
<form><form>
Enter something:<br>Enter something:<br>
<input type="text" name="something"><input type="text" name="something">
<input type="submit"><input type="submit">
</form></form>
</html></html>
<script language="JavaScript">alert('Bug!');</script><script language="JavaScript">alert('Bug!');</script>

What To Escape?
•What symbols to escape depends on the
place where we put the escaped text:
•In the HTML document body dangerous
characters are:
•<, >, &, space (and maybe tab, new line)
•Inside an attribute of a HTML tag the
dangerous characters are:
•" and &
•Inside a <textarea> we need to escape:
•<, > and &

•Generally we should always escape the following
HTML special characters:
•In the HTML body we may need to escape also:
Escape The HTML Special
Characters
"&quot;Quotation Mark
&&amp;Ampersand
>&gt;Greater Than
<&lt;Less Than
CharacterHTML EntityCharacter Name
&nbsp;&nbsp;&nbsp; &nbsp;Tab
<br>New Line
&nbsp;Space
EscapingCharacter Name

HTML Escaping
•There is no standard method in Servlet/JSP
API for HTML escaping
•We need a custom escaping method:
public static String htmlEscape(String text) {public static String htmlEscape(String text) {
if (text == null) {if (text == null) {
return "";return "";
}}
StringBuilder escapedText = StringBuilder escapedText =
new StringBuilder();new StringBuilder();
for (int i=0; i<text.length(); i++) {for (int i=0; i<text.length(); i++) {
char ch = text.charAt(i);char ch = text.charAt(i);

HTML Escaping (2)
if (ch == '<')if (ch == '<')
escapedText.append("&lt;");escapedText.append("&lt;");
else if (ch == '>')else if (ch == '>')
escapedText.append("&gt;");escapedText.append("&gt;");
else if (ch == '&')else if (ch == '&')
escapedText.append("&amp;");escapedText.append("&amp;");
else if (ch == '\"')else if (ch == '\"')
escapedText.append("&quot;");escapedText.append("&quot;");
elseelse
escapedText.append(ch);escapedText.append(ch);
}}
String result = escapedText.toString();String result = escapedText.toString();
return result;return result;
}}

Problems
1.Create a JSP page that calculates the sum of 2
integer numbers. The page should have two form
fields and a submit button.
2.Create a JSP page that can add an remove items.
The items are strings and should be stored in the
client's session.
3.Using the JSP dynamic include create a small web
site (2-3 pages) that has header, footer and a menu
on each page. The header contents, footer contents
and the menu should be placed in separate files.

Problems (2)
1.Using the global application object implement a
counter of the visitors of the site.
2.Using the client's session object and the client
redirection technique implement a JSP page that
enters an integer number sequentially 5 times.
After the entering the 5th number the client's Web
browser should be redirected to another JSP page
that shows all entered numbers and their sum.
3.Ensure that no escaping problems are present in all
your previous JSP pages. Correct them as needed.

Homework
•Using the global application object implement
the "number guess game" that can be played
globally by multiple players in the same time.
The number guess game starts with a secret
number randomly chosen by the server. Each
player can make guesses and the server tells
whether the number is smaller, larger or the same.
The player who first guesses the number wins and
the game starts again.

Homework (2)
1.Using the JSP technology implement a simple
discussion forum. Each visitor should be able to
post new topics, to reply to a topic and to delete
topics and replies. Each topic is a message and
can have replies. The replies are messages in the
same topic (no nesting is allowed). Each message
consists of author subject and contents.
Each page in the forum should have a header, a
footer and a menu (implemented by including
fragments of JSP pages).
Take care of possible escaping problems.