Title: COSC 2956 Internet Tools
1COSC 2956 Internet Tools
2What is a Java Server Page
- A JSP combines Java code and template HTML in a
single file. - This is similar to the way PHP works.
- Scripting elements are used to provide dynamic
pages
3Connection with servlets
- Each Java server page is compiled into a servlet
before it can be used - This is normally done when the first request is
made so there could be a short wait. - However, JSP's can be precompiled so there is no
wait.
Java ServerPage
page
translation
Java servletsource code
Java Servletclass file
compiler
(show an example)
4Translated servlets
- You can example the source code produced by the
JSP translation process. - There is a directory called work in the main
tomcat directory where you can find the source
code. - Note that the _jspService method corresponds to
the servlet service method (which is called by
doGet or doPost)
5JSP elements (overview)
- Directives of the form lt_at_ ... gt
- Scripting elements
- Expressions of the form lt expr gt
- Scriptlets of the form lt code gt
- Declarations of the form lt! code gt
- JSP Comments lt-- ... --gt
- Standard actions
- Example ltjspuseBeangt ... lt/jspuseBeangt
- Implicit variables like request, response, out
6Directives
lt_at_ name attribute1"...", attribute2"..." ... gt
Specify page properties
page include taglib
Include a file at translation time
Specify custom tags
7Directives examples
- Import java packages
- lt_at_ pageimport"java.util.,java.sql." gt
- Multiple import statements
- lt_at_ page import"java.util." gtlt_at_ page
import"java.sql." gt - including file at translation time
- lt_at_ include file"header.html" gt
- For include the path is relative to the jsp
8Scripting elements expression
- For an expression scripting element like lt
expr gt, expr is evaluated and the result is
converted to a string and placed into the JSP's
servlet output stream. In a Java servlet this
would be equivalent to
PrintWriter out response.getWriter()...out.pr
int(expr)
9Expression examples
- Displaying request parameters (request is an
implicit object available in a JSP) - Doing calculations
Your name is lt request.getParameter("name")
gtand your age is lt request.getParameter("age")
gt
The value of pi is lt Math.PI gt and the square
rootof two is lt Math.sqrt(2.0) gt and today's
date islt new java.util.Date() gt.
10Scripting elements scriptlet
- For a scriplet lt statements gt the Java
statements are placed in the translated servlet's
_jspService method body (it's like the servlet
service method which calls either doGet or doPost)
public void _jspService(HttpServletRequest
request, HttpServletResponse response) throws
java.io.IOException, ServletException...
statements ...
11Scriplet examples
- Check a request parameter
lt String name request.getParameter("name")
if (name null) gt lth3gtPlease supply
a namelt/h3gtlt else gt
lth3gtHello lt name gtlt/h3gtlt gt
There are 3 scriptlets here and an expression
element
12Scripting elementsdeclaration
- For a declaration lt! declarations gt the Java
statements are placed in the class outside the
_jspService method. Typical declarations can be
Java instance variable declarations or Java
methods
// declarations would go herepublic void
_jspService(...) ...
13Declaration examples
- Declaring instance variables
- Declaring methods
lt! private int count 0 gt...The count is
lt count gt.
lt!private int toInt(String s) return
Integer.parseInt(s)gt
14Including files
- Including files at translation time (when JSP is
translated to a servlet) - Including files at request time
lt_at_ include file"filename" gt
ltjspinclude page"filename" flush "true" /gt
15Where do you put JSP's ?
- If you have a web application called c2206 then
create a directory called jsp below it and put
JSP's there - For example a JSP called test.jsp would have the
path c2206/jsp/test.jsp - To run this JSP use the URL
- http//localhost8080/c2206/jsp/test.jsp
16A simple JSP
lthtmlgtltheadgtlttitlegtJSP Testlt/titlegtlt/headgtltbodygt
lth1gtJSP Testlt/h1gtTime lt new java.util.Date()
gtlt/bodygtlt/htmlgt
The expression scripting element lt ... gt
isequivalent to the scriptlet lt
out.print(...) gt
17The implicit out object
- In a scriptlet lt ... gt you can use the out
object to write to the output stream - Example
lt out.print("The sum is ") out.print("1
2 " (12))gt
18The implicit request object
lthtmlgtltheadgtlttitlegt...lt/titlegtlt/headgtltbodygtlth1gt
...lt/h1gtltpgtlt request.getParameter("greeting")
gtlt/pgtlt/bodygtlt/htmlgt
Try this using http//localhost8080/c2206/jsp/si
mple/greeting0.jsp?greetingHello Frank
19Processing form using GET
lthtmlgtltheadgtlttitlegtJSP Processing
...lt/titlegtlt/headgtltbodygtlth1gtJSP Processing form
with GETlt/h1gtltform action"doForm1.jsp"
method"GET"gtFirst name ltinput type"text"
name"firstName"gtltbr /gtLast name ltinput
type"text" name"lastName"gtltpgtltinput
type"submit" name"button"
value"SubmitName"gtlt/pgtlt/formgtlt/bodygtlt/htmlgt
c2206/jsp/forms/form1_get.html
20Processing form using POST
lthtmlgtltheadgtlttitlegtJSP Processing
...lt/titlegtlt/headgtltbodygtlth1gtJSP Processing form
with POSTlt/h1gtltform action"doForm1.jsp"
method"POST"gtFirst name ltinput type"text"
name"firstName"gtltbr /gtLast name ltinput
type"text" name"lastName"gtltpgtltinput
type"submit" name"button"
value"SubmitName"gtlt/pgtlt/formgtlt/bodygtlt/htmlgt
c2026/jsp/forms/form1_post.html
21doForm1.jsp
lt_at_ include file"../doctype.html" gtltheadgt
lttitlegtJSP Form Resultslt/titlegtlt/headgtltbodygtlth1
gtJSP Form Resultslt/h1gtHello lt
request.getParameter("firstName") gtlt
request.getParameter("lastName")
gtlt/bodygtlt/htmlgt
c2206/jsp/forms/doForm1.jsp
Try this using http//localhost8080/c2206/jsp/fo
rms/form1_get.html
22Temperature conversion
input
output
23temperature.jsp (1)
lt_at_ page import"java.text.DecimalFormat"
gtlthtmlgtltheadgtlttitlegtFahrenheit ...
Conversionlt/titlegtlt/headgtltbodygtlth1gtFahrenheit
to Celsius Conversionlt/h1gtlt String self
request.getRequestURI() if (request.getParamet
er("convert") null) gt ltform
action"lt self gt" method"POST"gt Fahrenheit
temperature ltinput type"text"
name"fahrenheit" /gt ltpgtltinput type"submit"
name"convert" value"Convert to
Celsius" /gtlt/pgt lt/formgt
24temperature.jsp (2)
lt else double fahr 0.0
try fahr Double.parseDouble(
request.getParameter("fahrenheit"))
catch (NumberFormatException e)
// do nothing, accept default value
25temperature.jsp (3)
double celsius (fahr - 32.0)
(5.0/9.0) DecimalFormat f2 new
DecimalFormat("0.00")gt lt
f2.format(fahr) gtF is lt
f2.format(celsius) gtC ltpgtlta href"lt self
gt"gtAnother conversionlt/agt lt/pgtlt
gtlt/bodygtlt/htmlgt
26Java Beans
- Special classes that encapsulate some data
- They have a default constructor
- get and set methods for data fields (properties)
- A bean can be constructed in JSP using
- ltjspuseBean id "..." class "..." /gt
- If the bean already exists this statement does
nothing
27setting properties
- To set a property of a bean useltjspsetProperty
name"..." property"..." value"..." /gt - To set a property using the value of a request
parameter useltjspsetProperty name"..."
property"..." param"..." /gt
28getting properties
- To get a property of a bean useltjspgetProperty
name"..." property"..." /gt
29A Greeting bean
package beanspublic class Greeting private
String greeting // the property public
Greeting() greeting "Hello World"
public String getGreeting() return greeting
public void setGreeting(String g)
greeting (g null) ? "Hello World" g
beans/Greeting.java
30Naming convention
- If the property name is greeting
- the get method must have the name getGreeting
- the set method must have the name setGreeting
31Creating a Greeting bean (1)
- Create a bean and use default property
- Create a bean and set its property when it is
constructed - Here ltjspsetPropertygt is in the body of the
ltjspuseBeangt element.
ltjspuseBean id"hello" class"beans.Greeting" /gt
ltjspuseBean id"hello" class"beans.Greeting"
gtltjspsetProperty name"hello"
property"greeting" value"Hello JSP World"
/gtlt/jspuseBeangt
32Creating a Greeting bean (2)
- Create a bean and set its property after it has
been constructed - The ltjspsetPropertygt tag is now outside the
ltjspuseBeangt tag so it will always set the
property, not just when the bean is constructed
ltjspuseBean id"hello" class"beans.Greeting"
/gtltjspsetProperty name"hello"
property"greeting" value"Hello JSP World" /gt
33greeting1.jsp
ltjspuseBean id"hello" class"beans.Greeting"
/gtltjspsetProperty name"hello"
property"greeting" value"Hello JSP World"
/gtlthtmlgtltheadgtlttitlegtGreeting JSP that uses a
Greeting beanlt/titlegtlt/headgtltbodygtlth1gtGreeting
JSP that uses a Greeting beanlt/h1gtltpgtltjsp.getProp
erty name"hello" property"greeting"
/gtlt/pgtlt/bodygtlt/htmlgt
test/jsp/greeting1.jsp
http//localhost8080/test/jsp/greeting1.jsp
34Two beans
- One initialized explicitlyand the other is
initializedusing a request parameter
35greeting2.jsp
ltjspuseBean id"greet1" class"beans.Greeting"
/gtltjspuseBean id"greet2" class"beans.Greeting"
/gtltjspsetProperty name"greet1"
property"greeting" value"Hello JSP World"
/gtltjspsetProperty name"greet2"
property"greeting" param"greeting"
/gtlthtmlgtltheadgtlttitlegtGreeting JSP using two
Greetingbeanslt/titlegtlt/headgtltbodygtlth1gtGreeting
JSP using two Greeting beanslt/h1gtltpgt1st bean
ltjspgetProperty name"greet1"
property"greeting" /gtlt/pgtltpgt2nd bean
ltjspgetProperty name"greet2"
property"greeting" /gtlt/pgtlt/bodygtlt/htmlgt
test/jsp/greeting2.jsp
http//localhost8080/test/jsp/greeting2.jsp
http//localhost8080/test/jsp/greeting2.jsp?greet
ingHelloFred
36three beans and include file
- One initialized explicitly, one isinitialized
using a requestparameter, and one isinitialized
using getParameter
37greeting3.jsp (1)
ltjspuseBean id"greet1" class"beans.Greeting"
/gtltjspuseBean id"greet2" class"beans.Greeting"
/gtltjspuseBean id"greet3" class"beans.Greeting
" /gtltjspsetProperty name"greet1"
property"greeting" value"Hello JSP World"
/gtltjspsetProperty name"greet2"
property"greeting" param"greeting" /gtlt--
Following works but param method is better
--gtltjspsetProperty name"greet3"
property"greeting" value"lt
request.getParameter(\"greeting\") gt" /gt
38greeting3.jsp (2)
lt-- Include file contains doctype and html tag
--gtltjspinclude page"doctype.html"
flush"true" /gtltheadgtlttitlegtGreeting
JSPlt/titlegtlt/headgtltbodygtlth1gtGreeting
JSPlt/h1gtltpgt1st bean ltjspgetProperty
name"greet1" property"greeting"
/gtlt/pgtltpgt2nd bean ltjspgetProperty
name"greet2" property"greeting"
/gtlt/pgtltpgt3rd bean ltjspgetProperty
name"greet3" property"greeting"
/gtlt/pgtltpgtrequest lt request.getParameter("greet
ing") gtlt/pgtlt/bodygtlt/htmlgt
test/jsp/greeting3.jsp
http//localhost8080/test/jsp/greeting3.jsp
http//localhost8080/test/jsp/greeting3.jsp?greet
ingHelloFred
39Beans and forms
- Using a bean to represent the data of a form
40form1_bean.html (1)
lthtmlgtltheadgtlttitlegtJSP Processong form using a
beanlt/titlegtlt/headgtltbodygtlth1gtJSP Processing
form using a beanlt/h1gtltform action"doForm1Bean.j
sp" method"GET"gtFirst name ltinput type"text"
name"firstName"gtlt/ brgtLast name ltinput
type"text" name"lastName"gtltpgtltinput
type"submit" name"button" value"Submit
Name"gtlt/pgtlt/formgtlt/bodygtlt/htmlgt
test/jsp/forms/form1_bean.html
http//localhost8080/test/jsp/forms/form1_bean.ht
ml
41A Name bean
package beanspublic class NameBean private
String firstName // property private String
lastName // property public String
getFirstName() return firstName public
String getLastName() return lastName
public void setFirstName(String first)
firstName first public void
setLastName(String last) lastName last
beans/NameBean.java
42doForm1Bean.jsp
ltjspuseBean id"name" class"beans.NameBean"
/gtltjspsetProperty name"name" property""
/gtltjspinclude page"../doctype.html"
flush"true" /gtltheadgtlttitlegtJSP Form results
using a beanlt/titlegtlt/headgtltbodygtlth1gtJSP Form
results using a beanlt/h1gtHelloltjspgetProperty
name"name" property"firstName"
/gtltjspgetProperty name"name"
property"lastName" /gtlt/bodygtlt/htmlgt
test/jsp/forms/doForm1Bean.jsp
Note the use of property"" to set all the bean
propertiesusing the form data vaules
43MVC approach
- MVC stands for Model-View-Controller
- Controller
- controls the application by getting the input and
forwarding the request to the appropriate page - View
- visual appearance of the output data
- Model
- logic, calculations necessary to produce the
data. Sometimes called business logic
44MVC example (Temperature)
- Getting the input (Fahrenheit temperature)
- controller.jsp (dispatch (forward) request)
- form.jsp (user input of temperature)
- Displaying the output (Celsius temperature)
- response.jsp
- Model (logic and calculations done by beans)
- TemperatureBean.java (form data)
- TemperatureCalculatorBean.java(does the
temperature conversio)
45TemperatureBean
package beanspublic class TemperatureBean
private String temp public String
getTemperature() return temp
public void setTemperature(String t) temp
t
beans/TemperatureBean.java
46TemperatureCalculatorBean
package beansimport java.text.DecimalFormatpub
lic class TemperatureCalculatorBean private
double celsius public String
getTemperature() return new
DecimalFormat("0.00").format(celsius)
// continued on next slide
47TemperatureCalculatorBean
public void setTemperature(String fahr)
double f try f
Double.parseDouble(fahr) catch
(NumberFormatException e) f
0.0 celsius (f - 32.0) (5.0 /
9.0)
beans/TemperatureCalculatorBean.java
48Forwarding a page
- A JSP can forward the request to another page
using - ltjspforward page"file.jsp" /gt
- The important idea here is that this new page
receives all the request parameters of the
forwarding page.
49controller.jsp
ltjspuseBean id"temp" class"beans.TemperatureBea
n"gtltjspsetProperty name"temp" property""
/gtlt/jspuseBeangtlt if (request.getParameter("tem
perature") null) gt ltjspforward
page"form.jsp" /gtlt else gt
ltjspforward page"response.jsp" /gtlt gt
test/jsp/temperature/controller.jsp
http//localhost8080/test/jsp/temperature/control
ler.jsp
50form.jsp
ltjspinclude page"../doctype.html" flush"true"
/gtltheadgtlttitlegtFahrenheit to Celsius
Conversionlt/titlegtlt/headgtltbodygtlth1gtFahrenheit
to Celsius Conversionlt/h1gtltform
action"controller.jsp" method"GET"gtFahrenheit
temperatureltinput type"text"
name"temperature"gtlt/ brgtltinput type"submit"
name"button" value"Submit Temperature"gtlt/pgtlt
/formgtlt/bodygtlt/htmlgt
test/jsp/temperature/form.jsp
51response.jsp
ltjspuseBean id"temp" class"beans.Temperature"
scope"request" /gtltjspuseBean id"convert"
class"beans.TempertureCalculatorBean"
/gtltjspsetProperty name"convert"
property"temperature" value"lt
temp.getTemperature() gt" /gtltjspinclude
page"../doctype.html" flush"true"
/gtltheadgtlttitlegtFahrenheit to Celsius
Conversionlt/titlegtlt/headgtltbodygtlth1gtFahrenheit to
Celsius Conversionlt/h1gtltjspgetProperty
name"temp" property"temperature" /gtFahrenheit
isltjspgetProperty name"convert"property"tempe
rature" /gt Celsius.ltpgtlta href"controller.jsp"gtCo
nvert another .. lt/agtlt/pgtlt/bodygtlt/htmlgt
test/jsp/temperature/response.jsp
52Databases using JSP
- Display the books database table
- bookdisplay1.jsp
- BookBean.java
- BookDataBean.javaDBConnectorBean.java
53bookdisplay1.jsp (1)
lt_at_ page import"java.text., java.util.,
beans." gtltjspuseBean id"db"
class"DBConnectorBean" gt ltjspsetProperty
name"db" property"driver" value"lt
application.getInitParameter(
\"jdbc.driver\") gt"/gt
ltjspsetProperty name"db" property"url"
value"lt application.getInitParameter(
\"jdbc.url\") gt"/gt
ltjspsetProperty name"db" property"username"
value"lt application.getInitParameter(
\"jdbc.username\") gt"/gt
ltjspsetProperty name"db" property"password"
value"lt application.getInitParameter(
\"jdbc.password\")
gt"/gtlt/jspuseBeangt
54bookdisplay1.jsp (2)
ltjspuseBean id"book" class"BookBean"/gtltjspus
eBean id"bookDataBean" class"BookDataBean"gt
ltjspsetProperty name"bookDataBean"
property"connection" value"lt
db.getConnection()gt"/gtlt/jsbuseBeangtlt!
DecimalFormat cents new DecimalFormat("0.00")
gtltjspinclude page"doctype.html" flush"true"
/gtltheadgtlttitlegtDisplaying the books database
tablelt/titlegtlt/headgtltbodygtlth1gtDisplaying the
books database tablelt/h1gt
55bookdisplay1.jsp (3)
lttable border"1"gtlttrgt ltthgtISBNlt/thgtltthgtTITLElt
/thgtltthgtAUTHORlt/thgt ltthgtPUBlt/thgtltthgtYEARlt/thgtltt
hgtPRICElt/thgtlt/trgtlt Iterator
bookListIterator bookDataBean.getIterator
() while (bookListIterator.hasNext())
book (BookBean) bookListIterator.next()gt
56bookdisplay1.jsp (4)
lttrgtlttdgtlt book.getIsbn() gtlt/tdgtlttdgtlt
book.getTitle() gtlt/tdgtlttdgtlt book.getAuthor()
gtlt/tdgtlttdgtlt book.getPub() gtlt/tdgtlttdgtlt
book.getYear() gtlt/tdgtlttdgtlt cents.format(book.g
etPrice()) gtlt/tdgtlt/trgt lt gtlt/tablegtlt/bod
ygtlt/htmlgt
test/jsp/bookdisplay1.jsp
http//localhost8080/test/jsp/bookdisplay1.jsp