Title: Building Web Applications with Java
1Building Web Applications with Java
EPFL - Ecole Polytechnique Fédérale de
Lausanne (Swiss Federal Institute of
Technology) Claude Petitpierre, Olivier
Buchwalder, Paul-Louis Meylan
2Web Applications
3J2EE
php
Websphere Weblogic
CVS
Visual Age
.net
ant
RMI
Eclipse
JDO
Hybernate
Java
MySQL
Javascript
HTML
Entity Bean
Servlet
Cookie
JSP
JBoss
MDBean
Tomcat
taglib
XML
Struts
4Web server (J2EE, JBoss)
- Servlets, Struts
- objects to access databases
- Development environment
- wizards
- diagrams
- WebLang (language developed at the EPFL)
- Software engineering
- geography (collaboration diagrams)
- behavior (use cases, finite state machine)
- data (class diagrams)
5Precision
- This course is about the application
architecture, not the formatting of the pages,
for which there are many specialized editors!
6Content
Servlets 7 Javascript 118 JSP 23 Struts CMP beans
36 structure (MVC) 124 Relationships
Java beans 130 DB object views 54 JSP
(in-out) 138 operations 67
FSM 146 Finders 77 Data transfers 151 Transact
ions 90 Hibernate 3 155 Java client 98 SQL
beans 160 JMS 99 RMI modules 168 Architecture 110
Software Engineering 171
7Calling an HTML Page
Tomcat, Apache (server)
Browser (client)
ltA HREF"URL"gtlinklt/agt
Internet
8Servlet handle data entered in such fields
Submit button
9Calling a Servlet
JBoss Server
Browser
servlet Test.java
HTML page ltA HREF"URL"gtlinklt/agt ltFORM
ACTION"URL"gt ltINPUT TYPE text
NAME"field"gt lt/FORMgt
Internet
HTML page
10Structure of a Servlet
public class Test extends HttpServlet public
void doGet ( HttpServletRequest
request, HttpServletResponse response
) throws ServletException, IOException
response.setContentType("text/html") out.p
rintln ("lthtmlgtltbodygt") out.println
("lth1gtTitlelt/h1gtlt/bodygt")
Produces the html page automatically when the
method returns.
11Retrieval of the parameter value within the
servlet(see J2EE Javadoc)
ltINPUT type text name "txtInp"gt in the
browser . . .
yyy
http//www.epfl.ch/servletName?txtInpyyy
String valueParam
in the servlet valueParam
request.getParameter("txtInp")
12Loading a Servlet into Tomcat-JBoss
WEB-INF/jboss-web.xml WEB-INF/web.xml WEB-INF/clas
ses/packageName/MyServlet.class jar cf
Test-WEB.war WEB-INF In order to load the
servlet in the server, one must transfer the
Test-WEB.war into the deploy folder of Tomcat or
JBoss
13Content of web.xml
ltservletgt ltservlet-namegtMyServletServletlt/se
rvlet-namegt ltdisplay-namegtMyServletlt/display
-namegt ltdescriptiongtlt!CDATAA simple
Servletgtlt/descriptiongt ltservlet-classgtserv
.MyServletlt/servlet-classgt lt/servletgt ltservlet-ma
ppinggt ltservlet-namegtMyServletServletlt/servl
et-namegt lturl-patterngt/MyServletlt/url-patter
ngt lt/servlet-mappinggt
14Read by xDoclets to create web.xml
import javax.rmi.PortableRemoteObject
. . . / _at_web.servlet name
"MyServletServlet" display-name
"TestServlet" description "A simple
Servlet" _at_web.servlet-mapping
url-pattern "/MyServlet" / public class
TestServlet extends HttpServlet public void
doGet (HttpServletRequest request,
. . .
15How to create all that stuff ?
- WebSphere, JBossIDE, WebLogic, JBuilder based
on wizards - Optimal-J, Arc Styler based on diagrams (MDA)
- WebLang our simple programming language
16What should a generator produce ?Here is our
choice
html InputForms ltFORM action "test"gt a b
m1 c b m2
servlet Test.java doGet() . .
. m1(int a, String b) ...
m2(String c, long d) ...
17With more details
html InputForms ltFORM action "test"gt
ltINPUT ... name"a"gt ltINPUT ... name"b"gt
ltSUBMIT name"m1"gt lt/FORMgt ltFORM
action "test"gt ltINPUT ... name"c"gt
ltINPUT ... name"b"gt ltSUBMIT
name"m2"gt lt/FORMgt
servlet Test.java doGet() a
getParameters(a) m1(a, b) or
m2(c, d) m1(int a, String b) ...
m2(String c, long d) ...
18Servlet Module in WebLang
servlet TestServlet package
packageName int attribute // delicate
public void add ( PrintWriter out, int
number) attribute number
out.println(attribute)
public void sub (int number)
attribute ? number
19Output of the WebLang Compiler
Test.la
- MyServlet.java (with the xdoclets
(_at_web...) - xdoclet-build.xml
- packaging-build.xml
- README/MyServlet.html
20(No Transcript)
21Exercise 1
- Create a servlet that returns the current date
Client Server
servlet showDate show()
html showDate
Specify in a WebLang module
Automatically created by WebLang
22Session Objectsin servlets
Client 2
Client 2
Serveur
action form 1
Client 1 (cookie)
action form 1
Servlet y session.getAttribute("xx")
action form 3
action form 4 xx
action form 1
Client 2 (cookie)
action form 1
action form 3
action form 4 xx
23Session
public public void doGet (
HttpServletRequest request,
HttpServletResponse response) HttpSession
session request.getSession() MyForm myForm
new MyForm() session.setAttribute("myForm",
myForm ) session.getAttribute("someName") .
. .
24JSP Java Server Page
(WebLang generates JSP on their own and as Struts
companion)
25Use of a JSP
JSP compiler
Java compiler
Execution
JSP code html
Servlet Java code
Servlet Java source
server
browser
http//www.ch/xxxx.jsp
26Example of a JSP page(details follow)
lthtmlgt ltheadgtlttitlegtFilelt/titlegtlt/headgt ltbodygt lth1
gtExamplelt/h1gt lt! declarations gt lt code
Java gt Nouvelle valeur de l'attribut lt
attribute gt ltpgt ltform action"http//localhost8
080/Exercice3-WEB/File.jsp"gt ltinput
type"text" name"attribute"/gt ltinput
type"submit"/gt lt/formgt lt/bodygt lt/htmlgt
27Page JSP
lt! declarations gt lt--! Methods,
attributes Attention, a single servlet
object is shared by all clients --gt
28Page JSP
Value of the attribute lt attribute gt lt
myClass.text() gt lt // Java code
out.println( "Text ltpgt" ) gt
29URL of a JSP
ltform action"http//localhost8080/
Exercice3-WEB/File.jsp"gt ltinput
type"text" name"attribute"/gt ltinput
type"submit"/gt lt/formgt
30Exercise 2
- Create a JSP that display the date and has a link
pointing to the same JSP Client
Server
jsp jspDate lth1gtDatelt/h1gt lta href"This
JSP"gt Show date lt/agt
html jspDate See this link !
Specify in a JSP WebLang module
Automatically created by WebLang
31JSP statement
lt_at_ pageimport"packName." gt
32Applet
ltjspplugin type"applet"
code"package.HorlogeApplet"
width"370" height"50"gt lt/jspplugingt
33Importing a tag
definition lt_at_ taglib uri "pack/myTag.tld"
prefix
"tag"gt use lttagmyTag/gt
34Corresponding class tag
package pack import java.io.IOException /
_at_jsp.tag name "myTag"
description "A test class for tags" / public
class myTag extends TagSupport public
int doStartTag() JspWriter out
pageContext.getOut() out.println("I
am a tag") return 1
35Description of a tag MyTag.tld
Created by the xDoclets
?xml version"1.0" encoding"UTF-8"?gt lt!DOCTYPE
taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP
Tag Library 1.2//EN" "http//java.sun.com/dtd/web
-jsptaglibrary_1_2.dtd"gt lttaglibgt
lttlib-versiongt1.0lt/tlib-versiongt
ltjsp-versiongt1.2lt/jsp-versiongt
ltshort-namegtxdoclet-buildlt/short-namegt
lttaggt ltnamegtmyTaglt/namegt
lttag-classgtpack.myTaglt/tag-classgt
ltdescriptiongtlt!CDATAA test class for
tagsgtlt/descriptiongt lt/taggt lt/taglibgt
36Where is the compiled JSP file ?
C\jboss-4.0.0\server\standard\work
37Database access with the helpof persistent
objects
EJB Enterprise Java Beans
38Client-server Application (J2EE)
Server
JBoss
Container
Container
Client
Session EJB
Entity EJB
Client
proxies
DB
Container
Network
Entity EJB
39Web Application (J2EE)
JBoss
Server
Container
Container
Entity EJB
Session EJB
DB
Client
Tomcat
Browser
Servlet
proxies
Container
Entity EJB
x.html
Network
40CMP entity beans
(Container Managed Persistency) BMP, Bean
Managed Persistency will not be studied as there
are better alternatives
41Files generatedby WebLang and by the xDoclets
src /control/ejb Game.java GameCMP.java /control/p
roxy GameLocalHomeProxy.java GameLocalObjectProxy.
java GameRemoteHomeProxy.java GameRemoteObjectProx
y.java
sources of the beans interfaces of the
proxies
42Parts of a CMP entity bean
EJBContainer
servlet other EJB
XxxxLocalHomeProxy create
findByPrimaryKey
XxxxEntityBean
Xxxx ejbCreate ejbPostCreate
ejbFindByPrimaryKey ejbLoad
ejbStore userMethods
XxxxLocalObjectProxy userMethods
43Instantiation of a persistent object
InitialContext lookup
XxxxHomeProxy create
findByPrimaryKey
client servlet bean
44Lookup to get a home proxy
TownLocalHomeProxy townLocalHomeProxy
null Context context new InitialContext() Obj
ect ref context.lookup("store_PersonLocal") to
wnLocalHomeProxy (TownLocalHomeProxy)
PortableRemoteObject.narrow ( ref,
TownLocalHomeProxy.class ) // narrow cast
from object to TownLocalHomeProxy
45CMP entity bean Attributes
/ A pair of getter / setter for each
attribute _at_ejb.persistent-field
_at_ejb.interface-method view-type "both
/ public abstract String getAtt() /
_at_ejb.interface-method view-type "both
/ public abstract void setAtt(String att)
46CMP entity bean (beginning)
. . . / Attribute Pk is
used as primary key by default.
_at_ejb.persistent-field / public abstract
java.lang.Long getPk() public abstract void
setPk(java.lang.Long pk) / Default
remove method _at_throws RemoveException
_at_ejb.remove-method / public void ejbRemove()
throws RemoveException
47Control files generated by the xDoclets
META-INF ejb-jar.xml jboss.xml jbosscmp-jdbc.xml
48Class specifying a CMP entity bean(continuation)
package store.ejb import javax.ejb.EntityBean im
port javax.rmi.PortableRemoteObject /
_at_ejb.bean name "Customer"
display-name "CMP Entity Bean"
description "Description of the CMP Entity
Bean" view-type "both" type
"CMP" primkey-field "pk"
jndi-name "store_CustomerRemote"
local-jndi-name "store_CustomerLocal"
_at_ejb.pk class "java.lang.Long"
/ public abstract class Customer implements
EntityBean EntityContext entityContext
. . .
49Specification of CMP entity beans in WebLang
CMP bean attributes methods finders /
creators relations
50Definition of an object in WebLang
cmpbean Town package geo String name
// DB attributes int numero public void myMet
(String s) System.out.println(s) //
creators - finders
51CMP Bean method create
cmpbean Person package beans
String firstName String lastName
// attributes DB columns int age
public Person createPerson
( String firstName, String
lastName ) // age not initialised // the
arguments of the create must correspond // to
the attributes. They are stored in the latter.
52CMP Bean finder method
Person findPerson () query
"SELECT OBJECT(o) FROM Course o WHERE
o.name?1" // more details later
53Creation and use of an object in WebLang
Town t Country c t townHome.create("Lausanne
") c countryHome.create("Switzerland") System.
out.println( t.getName() ) c.setName( "Suisse" )
54Servlet using a bean
servlet myservlet package servlets
public void newPerson ( PrintWriter out,
String
firstName,
String lastName, int age)
throws Exception
Person aPers aPers
personHome.createPerson
(firstName, lastName, age) //
it is a simple means to test CMP beans, an html
// file that calls this servlet is created
automatically
55Java Client (remote)
jclient Ouf package clientPack
public void method1 (String s1, String s1)
Person aPers Course aCourse
aPers personHome.createPerson("a",
s1) aCourse courseHome.createCourse
("prof", s2) // WebLang generates
automatically a remote access
56Reading the HSQLDB database
http//localhost8080/jmx-console Select
serviceHypersonic (fifth line under
jboss) Select invoke (below startDatabaseManager)
Look at the task bar and let the DB window
appear. Click View/Refresh tree in this
window Examine the tables (Command gt Select )
57Exercise 3
- Create a servlet that gets a town and a country,
introduces each component in its table(the check
to determine if an object already exists in the
database will be performed in a subsequent
exercise)
Generated automatically
html TownInCtr town country
WebLang modules
CMP bean Town name
servlet TownInCountry addTownCountry(
String t, String c )
submit
CMP bean Country name
58Relations between CMP beans
59An example of relation
Books title borrower (1) Borrower
name books (N)
60Object / Database view
books local-PK title
borrower-PK
Borrowers local-PK name
1
N
3 Hans
4 Peter
7 Uli
12 Islands 7
15 Countries 4
11 Mountains 4
61Person ? book
Hans
3
12 Islands 7
15 Countries 4
11 Mountains 4
Peter
4
Uli
7
Books of borrower ("Peter") SELECT Books. FROM
Books, Borrowers WHERE books.borrower_pk
borrowers.local_pk AND borrowers.namePeter
62Book ? person
Hans
3
12 Islands 7
15 Countries 4
11 Mountains 4
Peter
4
Uli
7
Borrower of book("Countries") SELECT
Borrowers.name FROM Borrowers, Books
WHERE borrowers.local_pk books.borrower_pk
AND books.title countries returns the
borrower
631N Relation
Y
4
23
X
N
23
8
23
1
5
WebLang cmpbean X relations (Y 1N)
23
6411 Relation (bidirectional)
Y
X
23
4
23
WebLang cmpbean X relations (Y 11
target) cmpbean Y relations (X
11)
65NM Relation
23
4
27
X
8
Y
24
5
23
5
8
23
8
27
4
24
66NM Relation (bidirectional)
WebLang cmpbean X relations (Y NM)
attributes cmpbean Y relations (X
NM) attributes
67Object View
Books local-PK title
borrower-PK
EJB Books abstract getPk() abstract
setPk(pk) abstract getTitle() abstract
setTitle(title) abstract getBorrower()
// relation 11 abstract
setBorrower(borrower)
68Object View
Borrowers local-PK name
EJB Borrowers abstract getPk() abstract
setPk(pk) abstract getName() abstract
setName(name) abstract getBooksN()
// 1N relation abstract
setBooksN(booksN) abstract add(book)
// added by WebLang abstract remove(book)
69xdocletsof the relationships
/ Implementation of the relationship
getCollection _at_ejb.interface-method
view-type "local" _at_ejb.relation
name"Courses-Students-NM"
role-name"Courses-N-role"
target-ejb"Students"
target-role-name"Students-M-role"
target-multiple"yes" _at_jboss.relation-mapping
style"relation-table"
_at_jboss.relation-table table-name"Courses
XStudents" _at_jboss.relation
related-pk-field "pk"
fk-column"students_pk" fk-constraints
"false" _at_jboss.target-relation
related-pk-field "pk" fk-column
"courses_pk" fk-constraints "false"
/ public abstract java.util.Collection
getStudentsN()
70Operations concerning the relationships between
beans
(WebLang)
71Relationships used in the following pages
cmpbean Country relations (Capital11,
Town1N) cmpbean Capital relations
(Country11) cmpbean Town relations
(Country11)
72Handling of a 11 bidirectional reference
Country-Capital
Capital t capitalHome.create("Bern") Country
c countryHome.create("Switzerland") t.setCountr
y(p) System.out.println( c.getCapital().getName()
)
// setCountry is automatically defined when one
specifies (Country11)
73Addition of an element to a relationship
Country (1) Town (N)
Town v Country p t townHome.create("Lausanne
") c countryHome.create("Switzerland") t.setCo
untry(c) // 11 side t
townHome.create("Bern") c.addTown(t)
// 1N side
74Storing a relationship and accessing it
Collection collection aCountry.getTownN() Itera
tor it collection.iterator() while
(it.hasNext()) // Java 1.4
System.out.println( ( (Town)
it.next() ) .getName() )
75addTown is introduced by WebLang
void addTown(v) getTownN().add(p)
// standard add and remove of Collection//
added automatically by WebLang removeTown(t)
getTownN().remove(t) // the collections
must be handled within a transaction
76Summary of the relationships and their methods
indication in Xxxx Other end in Yyyy methods available in Xxxx
Yyyy 11 no relationXxxx 11Xxxx 11 targetXxxx 1N Yyyy y getYyyy() setYyyy(yyyy)
Yyyy 11 target no relationXxxx 11Xxxx 11 target Yyyy y getYyyy() setYyyy(yyyy)
Yyyy 1N no relationXxxx 11 java.util.Collection y getYyyyN()setYyyyN(collection)addYyyy(yyyy), removeYyyy(yyyy)
Yyyy NM no relationXxxx NM java.util.Collection y getYyyyN()setYyyyN(collection)addYyyy(yyyy), removeYyyy(yyyy)
77Comparisons between objects
CB h1 cBHome.create("5") CB h2
cBHome.findH("5") if (h1.isIdentical(h2))
System.out.println("2 x the same bean") if (h1
h2) // does not work ! if (h1.getPrimaryKey()
.equals(h2.getPrimaryKey())
System.out.println("2 x the same bean") if (
((Long)h1.getPrimaryKey()).intValue()
((Long)h2.getPrimaryKey()).intValue())
System.out.println("2 x the same bean")
78Advices
Before starting JBoss, clear the database, by
deleting c\jboss-4.0.0\server\standard\dat
a c\jboss-4.0.0\server\standard\tmp
c\jboss-4.0.0\server\standard\work As well as
the files .ear in c\jboss-4.0.0\server\sta
ndard\deploy
79Exercise 4
- Create a servlet that gets a town and a country,
introduces each component in its table (no
checks)and establish a relationship between them
WebLang modules
CMP bean Town name
servlet TownInCountry addTownCountry(
String t, String c )
N
1
CMP bean Country name
80Finders
http//ltiwww.epfl.ch/petitp/ProgrammationInterne
t/Lecon_CMP/ejb-2_1-fr-spec.pdf (voir example
du paragraphe 11.2.6.8)
81Finder returning an object( WebLang )
Course findCourse (java.lang.String name)
query "SELECT OBJECT(o)
FROM Course o
WHERE o.courseName?1"
82Checking if an object exists in WebLang
Country c null try c countryHome.findByNam
e("Switzerland") catch (javax.ejb.FinderExcepti
on fe) c countryHome.create(" Switzerland
")
83Finder returning a collection
(here the whole table)
java.util.Collection findCourses ()
query "SELECT OBJECT(o)
FROM Course o" Note the collections must
be handled either in the CMP entity beans, or in
the sessions beans, not directly in the servlets.
84Cascaded 11 references
Option findOptionByProf (java.lang.String
profName) query "SELECT OBJECT(s)
FROM Option o
WHERE o.course.profName?1"
// the finder must be located in the CMP bean
// that defines the returned object
8511 relation returning a collectionof members
belonging to a relation
public java.util.Collection findRoomByCourseName
(java.lang.String CourseName) query
"SELECT c.room FROM
CourseDescriptions c WHERE
c.course_name ?1
AND c.room.number LIKE '5' "
// If several beans may correspond to the same
criteria
861N Relation
public java.util.Collection
findStudentByCourseName (java.lang.String name)
query "SELECT OBJECT(s)
FROM Students s, IN (s.courseDescriptionsN) ca
WHERE ca.course_name?1"
!
87Cascaded 1N relations
public java.util.Collection findGradeByCourseGrade
(int
courseGrade, java.lang.String name)
query "SELECT OBJECT(g)
FROM Students s, IN
(s.courseDescriptionsN) a,
IN (a.gradesN) g WHERE
a.course_name ?2 AND g.grade lt ?1"
88Cascaded Relations
A 11 B 11 C 11 D
- dd public A findAByX (java.lang.String
name) query "SELECT OBJECT (o)
FROM A o WHERE
o.b.c.d.dd?1"
89Cascaded Relations
An 1N Bn 1N Cn 1N Dn -
dd public java.util.Collection
findA(java.lang.String name) query
"SELECT OBJECT (o) FROM An
o, IN(o.bnN) bx, IN(bx.cnN) cx, IN(cx.dnN) dx
WHERE dx.dd?1"
90Cascaded Relations
(the query returns an An)
An 11 Bn 1N Cn 11 Dn -
dd public java.util.Collection findAn
(java.lang.String name) query
"SELECT OBJECT (o) FROM An
o, IN(o.bn.cnN) cx WHERE
cx.dn.dd?1" // to be stored in bean An
91Cascade Relations
(the query returns an Bn)
An 11 Bn 1N Cn 11 Dn -
dd public java.util.Collection findBn
(java.lang.String s) query "SELECT
o.bn FROM An o, IN(o.bn.cnN)
cx WHERE o.aa?1" // to
be stored in bean Bn as it returns a collection
of Bn
92Exercise 5
- Same as before, but check that the country does
not already exist - and print the list of towns within a given
country - (both checks use a finder)
WebLang modules
CMP bean Town name
servlet TownInCountry addTownCountry(
String t, String c )
N
1
CMP bean Country name
93Transactions
94Transactions in the session beans
transaction Bean The transaction is not handled
automatically. It can be used to handle the
collections.
95NM Relation handled in a session bean
Courses
Students
N
M
- Experience
- Register a student in a course
- See if the student is known from the course
96beanContext.getUserTransaction().begin() s1.getCo
ursesN().add(c1)
// s1, s2 are students and s1.getCoursesN().ad
d(c2)
// c1,c2 courses s1.getCoursesN().add(c3)
s2.getCoursesN().add(c3) System.out.println("Add
itions terminées") Thread.sleep(10000)
// sleep for 10 seconds to allow
peering
//
into the database Iterator it
c3.getStudentsN().iterator() while
(it.hasNext()) Students s (Students)
it.next() System.out.println("c3.colle
ction"s.getName()) beanContext.getUserTransact
ion().commit()
97Transactions
CMP Bean A
Transaction available before entering B
CMP Bean B
Transaction created by the container for B
98In the CMP bean (WebLang) transaction
RequiresNew In the methods of the CMP bean
beanContext.setRollbackOnly()
99Transaction types
Transaction type Transaction available before the execution Reaction of the container
Required available none keeps it starts a new one
RequiresNew available none starts a new one starts a new one
Mandatory available none keeps it error
100Java Clients
- External programs can access the session beans in
the same way as the servlets - They can access the CMP beans, but not manage
their relationships (the collections must be
handled within transactions)
101jclient Module
jclient Ouf package clientPack void method1
(String s) Person aPers Course aCourse
aPers personHome.createPerson(s"pers") aC
ourse courseHome.createCourse(s"course")
void method2 () List aList String str
"Text "listHome.create().text() // session
bean System.out.println(str)
102JMS Java Message Services
- Channels (queues, topics, durable topics)
- Message driven beans
- Architecture
103Message Driven Beanqueue, topic
Server
Clients
Sender
queue/topic
MDBean
Receiver
queue topic
SynReceiver
If the MDBean reads a topic, it must write to a
topic. Similarly for the queues (?).
104Types of channels
Queues Each message by a single client
Topics Each client receives all messages
Durable Topics Each client receives all messages, even if it is temporarily disconnected Only in input, requires subscription name username, passwd
105Creation of queues and topics
- A few queues and topics are created when the
JBoss serv er is started A, B, C, D, testTopic
(read the information printed when JBoss starts) - The queue or the topic of an MDBean is created at
the creation of theMDBean. - One may create other queues and topics by
modifying the files controlling the environment
of JBoss according to http//ltiwww.epfl.ch/WebLan
g/JBossQueues.html - One can also create them dynamically according to
http//ltiwww.epfl.ch/olivier/jmx.html
106Channels available in WebLang
- MDBeans (1 input / 0-n outputs)
no other entry call possible - Servlets, (0-n outputs)JSPs, Struts
- CMP beans (0-n outputs)
- clients (0-n inputs / 0-n outputs)
107Module MDBean in WebLang
No name (unlike the other ones)
mdbean MyMDB package myPackage
inputchannel (queue, "MDBQueue")
String s ((TextMessage) msg).getText())
varName.send(msg) outputchannel
varName (queue, "B")
108Module client en WebLang
jclient MyClient package myPackage
inputchannel inputName (topic, "MDBTopic")
String s ((TextMessage)msg).getText())
varName.publish(msg)
outputchannel varName (topic, "testTopic")
public void method(String s) . . .
109Synchronous reading
// Read the queue in a synchronous manner //
(at most 5 seconds waiting) for ()
Message msg (Message)
inputName.receive(5000) if (msg null)
System.out.println("Timed out")
else System.out.println(msg.getText())
110Module servlet en WebLang
servlet MyClient package myPackage
// pas dinputchannel ! outputchannel
varName (queue, "A") public void
method(String s) TextMessage tm
queueSession.createTextM
essage(s) varName.send(tm)
111Connection to a topic
(generated by WebLang)
public void newTopicEnv(String name, String
passwd)
throws Exception
Object tmp initCtx.lookup("UIL2ConnectionFactor
y") TopicConnectionFactory tcf
(TopicConnectionFactory) tmp topicConn
tcf.createTopicConnection(name,
passwd) topicSession topicConn.createTopicSess
ion( false, javax.jms.TopicSession.AUTO_ACKNOWLE
DGE ) topicConn.start()
112Connection to a topic
(generated by WebLang)
tmpTopic (javax.jms.Topic) initCtx.lookup("topi
c/testTopic") fromTopic topicSession.createSub
scriber(tmpTopic) fromTopic.setMessageListener(n
ew fromTopicListener())
113Architecture Example
114Example
paper scissors - stone
topic
Player 1
Player 2
- One uses a topic, so that the two players do not
need to address different queues (same source) - One receives thus the choice of the other and
ones own choice
115Distinction between the two returned choices
- If one receives a message different from ones
own choice, it is the others message - If one receives a message equal to ones own
choice, it may be ones own choice or the others
choice, but it is then not necessary to know
which one it is !
116Java client
GUI setUsername () getUsername () setPosition
() setError ()
topic
GUI Listeners actionPerformed()
Message Listener onMessage ()
Business layer FSM ()
117Finite State Machine
public synchronized void transition(String
source) try switch
(state) case 0 if
(source ! "username") return
game gameHome().findByName(gui.getGameName())
. . .
state 1 break
case 1 if (source ! "nextmove")
return state 2
break case 2 if
(source ! "done") return
game.moveTerminated() state
1 catch (Exception e)
118The FSM is shared
- synchronized java.awt.EventQueue.invokeLater(
new Runnable() public void run()
// handling of the GUI
) // the direct access to the GUI is delicate
119Automaton of the example
0 0
My choice has been sent
His choice received
Message received (his/my choice)
My choice sent
x y
Message received (his/my choice)
My choice received
The messages I have received I have sent my
choice
See following slides!
120Exercise 6
- Create a game environment in which a die runs
among all players (once they have registered
themselves in the match)
Server
Browser
Servlet
CMP beans (match name)
Java client
Java client
topic
Java client
121Javascript
- Similar, but different from Java
- Interpreted in the browser (not a servlet)
- Image animation
- Checking data input
- Allows each element to become a submit
122Use of an event
- ltBODY onLoad"someFunction()"gt
- ltINPUT TYPE button
onClick'alert("HELP,HELP !")' - gt
- quotes and apostrophes
- (could be swapped)
123Conditional Submit
ltFORM NAME "record" ACTION
"http//ltisun.epfl.ch8080/xxx" onSubmit
"return confirm ('Really submit?')"gt
Open dialog box
Important
124Every element may call a submit
ltSCRIPTgt var i0 function
key(j) forms0.submit() // values passed
within // text or
hidden fields lt/SCRIPTgt ltIMG SRC "im2.jpg"
width 50px onClick
"key(2)"gt
125Hidden fields
- ltINPUT TYPE "hidden"
- NAME "myValue"
- VALUE "notSeen"
- gt
- document.forms0.myValue.value "coucou"
- // value returned to the servlet, if placed
within an HTML form
126Events
onClick the user clicks on form element or
link onChange the user changes value of text,
text area, or select element onFocus the user
gives form element input focus onBlur the user
removes input focus from form element onMouseOver
the user moves mouse pointer over a link or
anchor onMouseOut the user moves mouse pointer
off of link or anchor onSelect the user selects
form element's input field onSubmit the user
submits a form onResize the user resizes the
browser window onLoad the user loads the page in
the Navigator (must be placed in
the BODY command) onUnload the user exits the
page (must be placed in the BODY command)
127Struts
128Basic structure of struts
PersonManagement
SportManagement
Servlet
Servlet
JSP
JSP
sport
person
3
2
personName
sportName location
1
sportForm
personForm
1291 Action Form PersonForm.java ( java bean )
/ _at_struts.form name"personForm" / public
final class PersonForm extends ActionForm
private String personName public String
getPersonName() return
(this.personName) public void
setPersonName(String personName)
this.personName personName
130HTML Form, calling an action-servlet
2 JSP input.jsp lth3gtpersonForm.sportFormlt/h3gt
lthtmlform action"/personManagement"gt
sportName lthtmltext
property"name"/gt lthtmlsubmit/gt
lt/htmlformgt
1313 Action Servlet
public final class PersonManagement extends
Action PersonForm f public
ActionForward execute (ActionMapping mapping,
ActionForm form, HttpServletRequest
request, HttpServletResponse response)
try f (PersonForm) form
f.getName() return
(mapping.findForward("sport"))
catch(Exception e) // trap exceptions that
may occur in your servlet
e.printStackTrace() // you will
get better error messages ! return
(mapping.findForward("error"))
132Auxiliary file struts-config.xml
(generated by xDoclet)
ltaction-mappingsgt ltaction
path"/personManagement" type"management.Pe
rsonManagement" name"personForm"
scope"session" input"/pages/Error.jsp"
unknown"false" validate"true" gt
ltforward name"sport"
path"/pages/sport.jsp" redirect"false"
/gt lt/actiongt ltaction-mappingsgt
133- Action forms,- arrays of action forms,- trees
of action forms
134Complex Java beans
person
SportManagement
In/out
PersonManagement
Action
Action
In/out
In/out
sport
job
jobName location
jobName location
personName
sportName location
jobName location
jobName location
personName
jobName location
sportForm
jobName location
personForm
jobFormN
jobForm
sportName location
sportForm
135WebLang Module Forms (Java beans)
form SportForm package fmPack fields
(String sportName, int location) form
PersonForm // sub-form package
fmPack fields ( String
personName ) forms ( jobForm, sportFormN
) form JobForm // arrays
add N and package fmPack fields
(String jobName, int location)
136Tree of action forms
/ _at_struts.form name"personForm" / public
final class PersonForm extends ActionForm .
. . private SportForm sportForm public
SportForm getSportForm () return
(this.sportForm) public void
setSportForm (SportForm sportForm)
this.sportForm sportForm
137Array of sub-action forms
(
x or Collection or Set ) / _at_struts.form
name"personForm" / public final class
PersonForm extends ActionForm . . .
private Collection sportFormN public
Collection getSportFormN () return
(this.sportFormN) public void
setSportFormN (Collection sportFormN)
this.sportFormN sportFormN
138Reference to an Action Form
Dans laction servlet f.getName() Dans la
JSP lthtmltext property"name"/gt f est liée à
la JSP dans struts-config.xml
139Reference to a Sub-Action Form
Dans laction servlet f.getSportForm().getName()
Dans la JSP lthtmltext property"sportForm.name
"/gt f est liée à la JSP dans struts-config.xml
140Reference to an array of Sub-Action Forms
In the action servlet (first element ! ) o
((ArrayList) f.getSportForm() name
((SportForm) o.get(0)).getName() In the
JSP lthtmltext property"sportForm0.name"/gt
f is linked to a JSP in struts-config.xml
141Automatic Creation of JSPs
142WebLang use of the JSPs and servlets
sportName location
FSM bean
FSM bean
JSP
JSP
personName
Where to start ? Same bean,but different
states
143Other Tags in the JSP and the Struts
ltjspuseBean id"managementForm"
scope"session"
class"man.ManagementForm"/gt ltbeanwrite
name"managementForm"
property"warning" filter"false"/gt
http//localhost8080/struts-documentation http
//ltiwww.epfl.ch/WebLang/references.html
144HTML form in the preceding JSP
lth3gtPetFormlt/h3gt lthtmlform action"/Supplier_Stat
e_0_Action" gt lthtmlhidden name"petForm"
property"lt page_prop_token gt"
value"lt pageId gt" /gt lttable
border0gtlttrgt lttrgtlttdgt nbsp nbsp nbsp
name nbsp nbsp
lttdgtlthtmltext property"name"/gt lttrgtlttd
colspan2 aligncentergt lthtmlsubmit
property"submit"gtsubmitlt/htmlsubmitgt lt/tablegt lt
/htmlformgt
145Array in the HTML form
lthtmlform action"/Supplier_State_0_Action"
gt lthtmlhidden name"petForm" property"lt
page_prop_token gt" value"lt pageId
gt" /gt lttable border"0" cellspacing"1"gt lt
trgtlttdgt lttable border"0" width"100"gtlttdgtsubName
lt/tablegt lttdgt lttable border"0"
width"100"gtlttdgtnumberlt/tablegt lttdgt lttable
border"0" width"100"gtlttdgtchecklt/tablegt lttrgtltt
dgt lttable border"0" cellspacing"1"gtlt/tablegt
lt!-- tableau ?
transparent suivant lttrgtlttd colspan10
aligncentergt lthtmlsubmit
property"submit"gtsubmitlt/htmlsubmitgt
lt/tablegt lt/htmlformgt
146Iteration on the array (or collection)
ltlogiciterate name"petForm" property"thingN
" id"item1" indexId"index1"gt lttrgtlttdgt lt
table border"0" width"100"ltcolorindex1.intVa
lue()2gtgt lttdgt nbspltbeanwrite name"item1"
property"subName"/gt lt/tablegt lttdgt lttable
border"0" width"100"ltcolorindex1.intValue()
2gtgt lttdgtltbeanwrite name"item1"
property"number"/gt lt/tablegt lttdgt lttable
border"0" width"100" ltcolorindex1.intValue()
2gtgt lttdgtlthtmlcheckbox property'lt"thingN"
index1.intValue()".check"gt'/gt lt/tablegt lt/logi
citerategt
pour que la valeur soit
retournée dans lURL
147Struts JSP
struts Supplier . . . page
supply forms (petForm, petForm.thingN
) form PetForm package fp
fields (String name) forms
(thingN) form Thing package fp
fields ( String subName, int
number, boolean check)
148Different display formats
page SomePage forms ( petForm,
petForm.thingN , petForm.bbb
(MySubmit), // displays a MySubmit
button petForm.ccc ( "An indication",
Cancel) // display a comment and a
button petForm.aaa (),
// displays no button )
149Finite State Machine in a Struts
Struts
0
not confir- med
showBasket
1
confirmed
2
OK
150Struts in WebLang
browseForm.petForm (form)
Struts
Action Forms
browser (JSP)
0
not confir- med
basket.petFrom (form)
showBasket
1
showBasket (JSP)
confirmed
order- registered (JSP)
2
PetOrder status ordered OrderItems
(CMPCMR)
CMP bean
OK
JSPs
Action Servlet
151WebLang Module states and pages
struts PersonManagement package
management stateMachine statedef
State_0 (person) statedef State_1
(job) . . . FSM . . . page
person forms ( personForm,
personForm.sportForm ,
personForm ("Comment", submitName) )
152WebLang Module Finite State Machine
stateMachine statedef State_0 (supply)
statedef State_1 (supplyConfirmation)
switch (sessionState) case State_S
sessionState State_0 break
case State_0 Pet pet petHome.create(
petForm.getName() ) sessionState
State_1 break case State_1
if (supplyConfirmation.getConfirmation())
sessionState State_0
// Pure Java code
153Three tiers (overview)
browseForm.petForm (form)
Buying
Struts
browser (JSP)
Administrator Struts
0
areYouThe- Administrator (JSP)
PetOrder status toBeChecked OrderItems
(CMPCMR)
0
not confir- med
basket.petFrom (form)
showBasket
login
1
showBasket (JSP)
checkOrders (JSP)
OrderForm.petForm not ? accept (form)
select
1
confirmed
order- registered (JSP)
2
confirmed
PetOrder status ordered OrderItems
(CMPCMR)
OK
SendSupplierPO MDBean
Queue
file
PetOrder status awaitInvoice OrderItems
(CMPCMR)
Database Dataflow
Display
Business Layer
Display
Business Layer
154Transfer of data
- From an action form to a CMP bean
- and vice-versa
155Action Forms ??CMP Beans
Action forms
finder or getCollection
Recreates a collection and copies one into the
other member by member
CMP beans
// code next page
156Action Forms ??CMP Beans
String courseName result.getCourseForm().getName
()
// reads an
action form java.util.CollectionltPersongt
coll personHome.findPersonInCourse(courseName
) java.util.CollectionltPersonFormgt c new
ArrayListltPersonFormgt () for (Person aPerson
coll) // scan the collection of
CMP beans PersonForm personF new
PersonForm() personF.setFirstName(aPe
rson.getFirstName())
personF.setLastName(aPerson.getLastName())
c.add(personF) // creates
the collection of action forms result.setPersonF
ormN( c )
157Exercise 7
- Transform the exercise about towns and countries
and implement it with Struts - Draw first a diagram with the html forms, the
action forms, the state machine and the database
WebLang modules
CMP bean Town name
Generated automatically
struts TownInCountry - get a town - get a
country - insert and connect
html TownInCtr Start struts
CMP bean Country name
158EJB - Hibernate 3
- Hibernate 3 allows the beans to be either
attached to or detached from the database - The beans can thus be used as action forms too,
which avoids the tedious transfers from the beans
to the action forms
159WebLang module
ejb3 MyCountry package myPackage
relations (Town1N) String name int
number public Country(String name) throws
Exception this.name name
public String toString() String str
"Country id" getId() " name" getName()
java.util.CollectionltTowngt tlist
getTownN() for (Town town tlist)
str str "\n Town" town
return (str)
160Use of the Hibernate bean
javax.persistence.EntityManager
em javax.persistence.EntityTransaction tx em
hibernate_utility.Manager.open() tx
em.getTransaction() tx.begin() Country c
new Country("Switzerland")
em.persist(c) country.setNumber(1291)
tx.commit() // or tx.rollback() hibernate_u
tility.Manager.close()
161Finders of Hibernate
javax.persistence.Query qt qt
em.createQuery("select t from Town t where
t.name?")qt.setParameter(1, town.getName())tr
y town (Town)qt.getSingleResult()
catch (javax.persistence.EntityNotFoundException
enf) town.setId(0)
em.persist(town)
162Action form Hibernate bean
ejb3 MyCountry extends strutsStateMachine.StateFo
rm package myPackage relations
(Town1N) String name int number
163SQL beans
- SQL beans have been devised at the EPFL they
present the same structure as Hibernate 3
(particularly within WebLang), but they only use
JDBC and the standard SQL - Much simpler to debug, as all statements may be
traced within the debugger - No home, the object must be created to hold the
finder (instantiation by new)
164SQL Bean Example
sqlbean Town extends strutsStateMachine.StateForm
package appliT relations ( Country
N1, ltisCapitalOf 11
hasCapitalgt Country) String name public
long findPK_OfTown() throws Exception query
"SELECT FROM Town WHERE namename"
TownN public void findN_TownList(String
s) throws Exception query "SELECT FROM
Town WHERE namegts"
165Use of an SQL bean
// we assume that country has been created //
and filled by the Struts mechanism case State_1
long pkC country.findPK_OfCountry()
if (pkC!0) country.reloadAll(pkC)
else country.store()
country.addTownN(town) //
town.setCountry(country) // either this line or
the line
// above the second one is
// called
automatically
166Finders
TownN tn new TownN() try
tn.findTownList(N) catch (weblangUtils.SQLExc
eption we) System.out.println(Not
found) for (Town t tn)
System.out.println(t.getName())
.. TownN String name
public void findTownList (String s) throws
Exception query "SELECT FROM
Town WHERE namegts"
167FSM of the SQL beans
Detached object
o new Xxx()
o.set(o1) o.add(o1)
o.set(null) o.remove(o1)
o.store()
o.findPKXx()
o.findXx()
o.store()
o.delete()
Attached object pk!0
o.delete()
Linked object pk0
o.reload(pk)
o.delete()
o.set(null) o.remove(o1)
o.set(o1) o.add(o1)
o.reloadAll()
o.storeAll()
Attached linked connected object pk!0 rel!0
o.deleteAll()
o.reload() o.reloadAll() o.update() o.updateAll()
168States of the SQL objects
Detached The object has been instantiated Attache
d The object has a corresponding set of data
in the database Linked The object is embedded
in a structure, but it has no primary key
Attached, linked The object is available in the
database, and connected as well as in memory,
within some relationship
169Operations of the SQL beans
store Copies the data of the object into the
database, new primary key inserted in the
object findXxx Query method returning a DB row,
the object must be instantiated before the method
is called findPKXxx Returns the value of the
primary key (or 0), method may also throw an
exception reload(pk) Method copies the data of
the object into a DB row with primary key
pk update Dual of the reload, updates the
database row that has the PK found in memory
170More Operations
- delete Removes the data in the database, not the
memory, resets the objects primary key - set, add Establishes connections between
- remove the objects, the two directions of the
relationship are handled - storeAll Call all the objects bound by
- deleteAll a relationship (not recursively)
- reloadAll
- updateAll
171RMI Application
172RMI inverse communication (by transmitting the
stub)
myRemStub
MyRemote (stub)
173RMI Module
rmi Test package rmis public void
print (String s) System.out.println("X
"s) jclient Client package
rmis Test x // as Test corresponds to an
rmi interface, // x is automatically
initialized RemoteTest y // y is not
automatically initialized, the client
// must call new RemoteConnection(true)
public void print (String s) try
x.print(s) catch (Exception e)
e.printStackTrace()
174Software Engineering
175Application / implementation
Craig (http//www.codegeneration.net/tiki-read_ar
ticle.php?articleId27) Specifying software
means components, interfaces, archit-ectures, or
what is sometimes referred to as the "How".
Specifying applications means features,
capabilities, options, or what is sometimes
referred to as the "What". So, it seems odd to
me (i.e., Craig ) to use UML (a "how" language)
as a universal specification language.
176My View
Actually, you want to describe the software, the
how. The customer can often not read any schema
and will require a fast prototype, which is
indeed the software.
Library (Librarian, book shelves, quiet
room)
Soft Library (simulator) (terminals,
server, software) Each time a book is borrowed
in the real library, the librarian borrows a
book here
Borrow a book Look for a user A book has been
lost Check differences Sort books Reserve a book
Software application (terminals, server,
software)
177Three tiers (overview)
browseForm.petForm (form)
Buying
Struts
browser (JSP)
Administrator Struts
0
areYouThe- Administrator (JSP)
PetOrder status toBeChecked OrderItems
(CMPCMR)
0
not confir- med
basket.petFrom (form)
showBasket
login
1
showBasket (JSP)
checkOrders (JSP)
OrderForm.petForm not ? accept (form)
select
1
confirmed
order- registered (JSP)
2
confirmed
PetOrder status ordered OrderItems
(CMPCMR)
OK
SendSupplierPO MDBean
Queue
file
PetOrder status awaitInvoice OrderItems
(CMPCMR)
Database Dataflow
Display
Business Layer
Display
Business Layer
178Exercise of Software Engineering (8)
- Creation of a stock exchange application.Customer
s are connected to the bank. The bank keeps a
portfolio for each client, transmits the customer
orders to the stock exchange. The stock exchange
keeps an order book that contains the stocks
that customers want to buy or sell, with the
prices (or price range) they are willing to pay
or get. - Create a diagram that specifies a customer, a
bank and a stock exchange, with CMP beans,
queues, session beans - Create a diagram of the software system that will
run the application, not of the application
itself.