Title: j'c'westlakestaffs'ac'uk
1Java Server Pages and beans!
- Format of lecture
- The N-Tier model
- Introduction to JavaBeans
- How JSP and JavaBeans can work together
- Demo
- Summary
2The N-tier model
- Up to know we have used 2 tier i.e the client
(presentation) and the http server (JSP
application) - For N-tier - where we are heading? - we will use
our HTTP server for java beans and JSPs - N-tier means separation of data application
logic presentation Why is this good software
engineering? Discussion .. - We can introduce JavaBeans as a tier - the JSP
will talk to the bean and the bean can handle
for example access to a database - Beans can be used by many JSPs for common
functionality and can help to slim down the JSP
code - Therefore, what are JavaBeans? They can be
thought as middleware but we need more detail
than that
3Java Beans a definition
- JavaBeans are a portable, platform independent
component model written in the Java programming
language, developed in collaboration with
industry leaders, e.g. IBM. Circa 1998 - They enable developers to write reusable
components once and run them anywhere, benefiting
from the platform independence power of Java
technology - See the JavaBeans homepage link below for more
info http//java.sun.com/products/javabeans/ - Java beans are very, very useful! There are also
what are called Enterprise Java Beans (EJBs)
which we will look briefly at in the last week of
the module
4JavaBeans nuts and bolts
- A JavaBean is developed as a .java file extension
- It HAS to be compiled into a .class file
extension - The name of the Bean MUST match the name of the
class - The Bean cannot be run standalone - it has to be
called by another Java program - in our case a
JSP - the JavaBean has no main method (therefore it
cannot run on its own accord) - it can have variables and methods which can be
called by another Java program in our case a
JSP - lt the compilation of a .java filegt
5JSP and JavaBeans Architecture
- What needs to be where? take care! There is a
supporting document on the week 4 schedule link - For Tomcat
- The bean must be compiled in the JDK environment
and the .class file placed in the Tomcat
Web-Inf\common\classes folder - Beans must be placed into a package (i.e. a
folder) within the beans folder called for
example jonathansbeans the package is named in
the bean source code and also in the JSP using
the bean - lt a recap on the need for packagesgt
6Example using Screen grabs
- A JavaBean called GuestBean
- The source file would be saved as GuestBean.java
- Below shows the top part of the JavaBean code
- import java.sql.
- public class GuestBean
- String email, firstName, lastName
- etc etc
7JavaBean structure
- ANY Java class can be a JavaBean provided it
follows certain conventions - A bean must have fields with corresponding get
and/or set methods - So you need at least one get and/or set method
- It follows that any existing Java class can be
converted to a bean (via of course modifying
the source code and removing the main method)
8JavaBean structure
- A JavaBean can have what are called properties
which are essentially either a get or set prefix
with a variable name suffix see next slide - Properties are manipulated using get and set
access methods - public ltdatatypegt getXXX( )
- public void setXXX(ltdatatypegt)
- XXX is the property name
- Examples follow after the next slide
9Bean get and set syntax
- The general syntax is
- get variableName
- set variableName
- The variable name will follow the naming
conventions being employed by the development
team e.g. the first letter of the variable name
may be capitalised and the rest lower case
10get method
- A get method is ALWAYS used to access a property
- public int getfieldId( )
- return fieldId
-
- The property accessed may be a calculated value
- public double getInterest( )
- return fieldBalance fieldInterestRate
A method
variables
11set method
- A property is ALWAYS set using a set method
- public void setBalance(double newBalance)
- fieldBalance newBalance
-
- Calculated properties do not need a set method
12JavaBeans objects
- Remember that as a JavaBean is a Javaclass and as
Java is object oriented this means that the class
will create an instance of the classes when used
these are called objects - So, on the server we could have many objects of
the JavaBean Class in existence I.e. my use of
the JavaBean would create an object, another
users use of the JavaBean would create another
object - Therefore we can conclude that JavaBeans can be
used in a multi-user environment
13JSP and JavaBeans
- JSPs can use JavaBeans using a set of action tags
- useBean Action - used to access a JavaBean class
instance (object) on the server - setProperty Action - used to set the attributes
of a JavaBean class instance (object) on the
server - getProperty Action - used to get the value of an
attribute of a JavaBean class instance (object)
on the server
14useBean syntax
- ltjspuseBean id"orderedbook" class"jonathansbean
s.Books" /gt
This is just a convenient made up identifier it
has no relation to either the html form name or
the JavaBean Code
15useBean scope
- The useBean action tag can also specify the
scope of a beans lifecycle - Used to access a JavaBean utility class on the
server can have 4 values which represent the
visibility of the bean through the lifetime of
the users request the scope - Page the default current page i.e. the latest
invocation of the JSP - Request throughout the lifetime of the users
request - Session until session is finished
- Application until the server is stopped
16Two demos follow
- Books using a bean Yvan skip this example
(students can read in their own time) Go to slide
26 for - Add Guests using a bean and the bean design
considered from a delete guest point of view
17Demo - Books JavaBean
- Demo consists of a JSP setting data in a
JavaBean and then getting the data - An HTML form Bookorder.html drives the demo and
calls a JSP Confirmbook.jsp - A JSP parses the HTML form and a call is made to
the compiled bean Bean.class (a compiled
JavaBean source code file Books.java - These files are on the zip file for this week
try this one at home
18BookOrder.html
- ltHTMLgt
- ltbodygt
- lth1gtJonathan's Book Order Formlt/h1gt
- Book Java Server Pages How To Guideltbrgt
- Version 1.0ltbrgt
- Price Per copy 2.50 ltbrgt
- ltform action"http//localhost8080/examples/jsp/j
cwexamples/confirmbook.jsp" method"post"gt - Number of copies ltinput type"text"
name"quantity"gtltbrgt - ltinput type"submit" value"Order Book" gt
- lt/formgt
- lt/bodygt
- lt/htmlgt
19Books.java the bean
- package jonathansbeans
- public class Books
- private String bookName
- private int quantity
- private String version
- private float price
This is the header part of the JavaBean source
code for Books.java The bean needs to be placed
in a folder called jonathanbeans Note that four
variables have been declared for this bean
20Confirm.jsp top half
- ltjspuseBean id"orderedbook" class"jonathansbean
s.Books" /gt - ltjspsetProperty name"orderedbook"
property"bookName" value"JSP How To Guide" /gt - ltjspsetProperty name"orderedbook"
property"version" value"1.0" /gt - ltjspsetProperty name"orderedbook"
property"price" value"2.50" /gt - ltjspsetProperty name"orderedbook"
property"quantityofcopies" param"quantity" /gt
The values are being set in the JavaBean
using The setProperty
Notes quantity value has come from the html form
21In the bean
public void setbookName(String name)
this.bookNamename
An example of a setter note the parameter
being received in the brackets The this just
means set the current object variable bookName to
the value received The this keyword is optional
it will work without it
22The response back to the browser confirmbook.jsp
ltHTMLgt ltbodygt lth1gtYour Book Orderlt/h1gt ltbrgtltbrgt Bo
ok ltjspgetProperty name"orderedbook"
property"bookname"/gtltbrgt Version
ltjspgetProperty name"orderedbook"
property"version" /gtltbrgt Price
ltjspgetProperty name"orderedbook"
property"price" /gtltbrgt Quantity
ltjspgetProperty name"orderedbook"
property"quantityofcopies" /gtltbrgt Totalnbsplt
orderedbook.getPrice()orderedbook.getQuantityofc
opies() gt ltpgtlt/pgt lta href"BookOrder.html"gtReturn
to order form to adjust quantitylt/agt lt/bodygt lt/ht
mlgt
This shows the call for the getter methods in
the Bean
23In the bean
public String getBookName() return
this.bookName
An example of a getter The this keyword is
optional it will work without it
24Example of application running
25The end result
26Guest bean demo
- The JSP Forwarding model
- Demo of JSP forwarding example which uses a
JavaBean - Useful for your assignment!
27Forward model
The JSP parses the input from the HTML form and
stores it in a javabean and updates the database
Client Request
HTTP Server - Tomcat
JSP
HTML Form
SQL
JSP
BEAN
Response
DATABASE
28JSP action tags - forward
- JSPs can chain together using a forward action
tag - forward Action - used to forward the request to
another JSP - ltjspforward page"SimpleGuestList.jsp" /gt
29Forward model
- JSPs are chained in the Forwarding requests
model - A JSP accepts a request from the user, possibly
uses a JavaBean and then forwards the request to
another JSP - hence the above term of chaining
JSPs together - This is different to the include model as there
is no primary JSP responsible for sending the
response back to the user
30Demo of a Guestbook bean using forward action
- Demo consists of
- An HTML form InputGuest.html
- A JSP which parses the form AddGuests.jsp
- A call to the compiled bean to do an addition
to the database GuestBean.java - A forward action to a JSP to show the results
31- ltjspuseBean id"Guests" class"jonathansbeans.Gue
stBean" scope"page"/gt - ltjspsetProperty name"Guests" property""/gt
32Warning
- AddGuest.jsp - this parses the request from the
client html form stores the data from the user
in a JavaBean and then updates a database table
with the data - It is VITAL that the HTML form element names
match the variables(attributes) declared in the
JavaBean - see next slides - This allows us to use the setProperty action to
set all properties within one statement
33HTML form elements and JavaBean attributes
- From InputGuests.html
- INPUT TYPE"text" NAME"email
- From GuestBean.java
- public class GuestBean
- String email, firstName, lastName
- public String getEmail()
Must match
34Delete Example
- Another example is provided of a delete method
- public void updateDatabasefordelete()
-
- try
- Class.forName("sun.jdbc.odbc.JdbcOdbcDriver")
.newInstance() - Connection conn DriverManager.getConnection
("jdbcodbcGuestBook") - Statement statement conn.createStatement()
- statement.executeUpdate("DELETE FROM
GuestBook WHERE Email '" email "'" )
35Summary
- It should have struck you by now that a JavaBean
can be used by many JSPs - this is good practice - For example, the GuestBean can service a number
of different JSPs - a JSP to add Guests
- a JSP to delete Guest
- How? Answer - by providing a method which the
JSPs can call - see next slide for diagram
36GuestBean
AddGuests.jsp
DeleteGuests.jsp
ltjspuseBean id"GUESTS" class"jonathansbeans.Gue
stBean" scope"request" /gt ltjspsetProperty
name"GUESTS" property"" /gt ltBRgt lt
GUESTS.updateDatabase() gt
ltjspuseBean id"GUESTS" class"jonathansbeans.Gue
stBean" scope"request" /gt ltjspsetProperty
name"GUESTS" property"" /gt ltBRgt lt
GUESTS.updateDatabasefordelete() gt
37Other examples
- There a numerous JSP examples using JavaBeans
provided by Sun - For example, see Suns Checkbox folder example
for beans - this example uses a getproperty attribute
- Also you will find there are JavaBeans available
out on the Web
38Summary
- This has been an introduction into the world of
JavaBeans - The example has been a very simple one to
demonstrate how a JSP can talk to a JavaBean
39Benefits of beans?
- Separation of work and herein lies the
advantages - simplification
- reducing the size of JSPs by delegating work out
to beans - One disadvantage of forward model is that one JSP
is responsible for the request and another JSP
takes care of the response - could get messy if
the chain was big