You are on page 1of 42

Java Server Pages

JSP

12/13/2014

6-1

Concept:
Server-side programming

CGI scripts
servlet

JavaServer page (JSP)

Java program that runs on webserver


Called from html page
Follows Sun servlet standard

Contains html and

Java or JavaScript

Compiled into a servlet and run on server


12/13/2014

6-2

JSP is servlet

follows request-response model


loaded into webserver
webserver manages instance
typical logic

examine request:

parameters, session, cookies, context

produce response

add to output stream

12/13/2014

6-3

JSP page

stored with extension .jsp


contains

html
JSP scripting elements
JSP directives
JSP actions
JSP comment
<%--

12/13/2014

--%>

6-4

JSP scripting elements

declaration

<%!

%>

expression

<%=

%>

scriptlet

<%

12/13/2014

%>

6-5

JSP declaration

placed into servlet outside of service


method

<%! int accessCount = 0; %>

12/13/2014

6-6

JSP expression

expression is evaluated and placed into


output
This page has been accessed
<%= accessCount %>
times

12/13/2014

6-7

JSP scriptlet

code that is inserted into service method

<% accessCount += 1; %>

12/13/2014

6-8

first JSP example


<html>
<head><title>Very Simple JSP</title></head>
<body>
<h1>Very Simple JSP</h1>
<%! int accessCount = 0; %>
This page has been accessed
<%= accessCount %>
times
<% accessCount += 1; %>
</body>
</html>

12/13/2014

6-9

Run from Internet explorer

12/13/2014

6-10

JSP directives

control overall structure of servlet


include

<%@ include file=relative URL %>

used to include another file

URL may start with /

12/13/2014

6-11

JSP directive: page

has attributes

import

to add import statements to servlet


<%@ page import=java.util.* %>

content-type
isThreadSafe

value true is default


false makes servlet implement
SingleThreadModel

12/13/2014

6-12

JSP page directive:


more attributes

session

value true is default


false disables session management

buffer="sizekb|none

specifies the buffer size for the JspWriter out

autoflush="true|false
extends="package.class
info="message
errorPage="url
isErrorPage="true|false
language="java"
12/13/2014

6-13

Predefined variables

request

response

instance of HttpServletRequest
ex: request.getParameter(username);
instance of HttpServletResponse
ex: response.addCookie(myCookie);

12/13/2014

6-14

Predefined variables

out

same as html text outside of <% %>

instance of JSPWriter
buffered version of output stream
ex: out.println(hello world);

12/13/2014

6-15

Predefined variables

session

instance of HttpSession
only available if session attribute of

<%@ page %> directive is true


ex: session.setAttribte(user, John Doe);
ex: name = (String) session.getAttribute(user);

12/13/2014

6-16

Predefined variables

application

instance of HttpContext
ex: application.setAttribute(user, John Doe);
ex: name = (String)application.getAttribute(user);

config

instance of HttpConfig

page

same as this in Java

12/13/2014

6-17

JSP example: second.jsp


<html><head><title>Session JSP</title></head><body>
<h1>Welcome to our World</h1>
<%@ page session="true" %>
<form action="second.jsp">
<% if (session.isNew()) { %>
Enter your ID:
<input type="text" name="username">
<% } else {
String name = request.getParameter("username");
if (name == null)
name = (String)session.getAttribute("user");
else
session.setAttribute("user", name);
%>
Welcome back <%= name %>
<% } %>
<input type="submit"></form>
</body></html>
12/13/2014

6-18

Run and observe JSP

12/13/2014

6-19

JSP actions

jsp:include

include a file at the time the page is requested

jsp:forward

forward the requester to a new page

jsp:useBean

find or instantiate a JavaBean

jsp:setProperty

set the property of a JavaBean

jsp:getProperty

insert the property of a JavaBean into the output

jsp:plugin
12/13/2014

6-20

jsp:include action
<jsp:include page="relative URL" flush="true" />

inserts the file at the time the JSP page


is translated into a servlet

similar to include method of


RequestDispatcher
12/13/2014

6-21

jsp:forward action
<jsp:forward page="relative URL" />

forwards the request to another page


similar to forward method of
RequestDispatcher
examples:
<jsp:forward page="errorReporter.jsp" />

12/13/2014

6-22

Exercise: shopping cart

12/13/2014

6-24

Exercise: shopping cart

12/13/2014

6-25

Greeting.html
<html><head>
<title>Shopping cart example</title></head>
<body><h1>Welcome to the Mini Store</h1>
<form action="MiniStore.jsp" method="post">
Please select one or more of our products:<br>
<select name="products" multiple>
<option>product 1 <option>product 2
<option>product 3 <option>product 4
<option>product 5 <option>product 6 </select>
<input type="submit">
</form>
</body></html>

12/13/2014

6-26

MiniStore.jsp (1/3)
<%@ page import="java.util.*" %>
<HTML><BODY>
<%
if (session.isNew()) {
%>
<h1>Welcome Newcomer</h1>
<% } else { %>
<h1>Welcome Back</h1>
<% } %>

12/13/2014

6-27

MiniStore.jsp (2/3)
<%
Vector list = (Vector)
session.getAttribute("cart");
if (list == null)
list = new Vector();
String products[] =
request.getParameterValues("products");
if (products != null)
for (int i = 0; i < products.length; i++)
list.addElement(products[i]);
session.setAttribute("cart", list);
%>

12/13/2014

6-28

MiniStore.jsp (3/3)
<H2>Thanks for your selection:</H2>
<TABLE><TR><TH>Product</TH></TR>
<%
Enumeration all = list.elements();
while (all.hasMoreElements())
out.println("<TR><TD>" + all.nextElement()
+"</TD>");
%>
</tr></table>
<jsp:include page="continue.html"/>
</body></html>

12/13/2014

6-29

continue.html
<form action="Greeting.html">
<input type="submit" value="Continue
Shopping">
</form>

12/13/2014

6-30

jsp:useBean action
<jsp:useBean id="name" class="package.class" />

instantiates an object of the specified class


binds it to a variable with id name
variable can be used to invoke bean methods or
to handle its properties
bean can be associated with scope

12/13/2014

6-31

jsp:useBean action
scope attribute
<jsp:useBean id="name"
class="package.class"
scope=value/>
values can be

page
(default)
request
session
application

makes bean accessible within scope

12/13/2014

6-32

jsp:setProperty action
<jsp:setProperty name="orderBean"
property="numberOfItems"
value=21" />
<jsp:setProperty name="orderBean"
property="numberOfItems"
param="numItems" />
sets value of bean property

12/13/2014

6-33

jsp:getProperty action
<jsp:getProperty name="itemBean"
property="numItems" />

value of bean property is returned

12/13/2014

6-34

Bean example
package jspexamples;
public class Counter {
private int value = 0;
public int getValue() {
return value;
}
public void setValue(int newValue) {
value = newValue;
}
}
12/13/2014

6-35

JSP example
<html>
<head>
<title>Bean JSP example</title>
</head>
<body>
<jsp:useBean id="counter" class="jspexamples.Counter"/>
<jsp:setProperty name="counter"
property="value" value="10"/>
Current value is
<jsp:getProperty name="counter" property="value"/>
</body></html>

12/13/2014

6-36

Variation in scope

request

example
<jsp:useBean id=counter"
class=jspexamples.Counter"
scope=request/>

make bean accessible via the request variable


request is shared in forward or include JSP

12/13/2014

6-37

Variation in scope

<jsp:useBean > action

other scopes

will find existing bean within scope

session
application

available to all servlets within the same


ServletContext

12/13/2014

6-38

Jsp example (1/2)


<html><head>
<title>Bean JSP example</title>
</head><body>
<jsp:useBean id="counter"
class="jspexamples.Counter scope="request"/>
<jsp:setProperty name="counter
property="value" value="10"/>
<jsp:forward page="BeanTest2.jsp"/>
</body></html>

12/13/2014

6-39

Jsp example (2/2):


BeanTest2.jsp
<html><head>
<title>Bean JSP example</title>
</head><body>
<jsp:useBean id="counter"
class="jspexamples.Counter scope="request"/>
Value is now:
<jsp:getProperty name="counter" property="value"/>
</body></html>

12/13/2014

6-40

Advanced Exercise

create Shopping cart bean


share with session scope

12/13/2014

6-41

ShoppingCart bean
package mypackage;
import java.util.*;
public class ShoppingCart {
private Vector<String> products = new Vector<String>();
public String getTable() {
StringBuffer buf = new StringBuffer();
Enumeration all = products.elements();
while (all.hasMoreElements())
buf.append("<TR><TD>" + all.nextElement() + "</TD>");
return buf.toString();
}
public void setAddOns(String[] addOns) {
for (int i = 0; i < addOns.length; i++)
products.addElement(addOns[i]);
}
}
12/13/2014

6-42

MiniBeans.jsp
<HTML><BODY>
<H2>Thank you for your selection</H2>
<jsp:useBean id="cart"
class=mypackage.ShoppingCart" scope="session"/>
<jsp:setProperty name="cart" property="addOns"
param="products"/>
<TABLE><TR><TH>Content of Shopping Cart:</TH></TR>
<jsp:getProperty name="cart" property="Table"/>
</TR></TABLE>
<jsp:include page="continue.html" />
</BODY></HTML>
12/13/2014

6-43

You might also like