Title: JavaBeans, ModelViewController, Struts
1JavaBeans, Model-View-Controller, Struts
2Objectives
- Two-tier vs. Three-tiered architecture
- Basics of JavaBeans.
- Why use the model-view-controller framework?
- Writing your own MVC application.
3Two Tiered Architecture
- The two tiers are
- PresentationLogic
- Data
- What you did for your first project
- Pros -
- Easy to code
- Good for one-offs
4Problems with Two-Tiered architecture
- Hard to change
- Often have to change many pages
- Most designers don't know Java
- Hard to maintain
- Difficult to follow page flow
- No standards exist
- Not reusable
- Classes won't work in other applications
- Application can't easily be extended beyond web
clients
5Three tiered architecture
- Presentation, Application, Data
- A middle layer with business logic
- Isolates database connection from presentation
- Can change the logic without changing front end
- Pros
- Allows engineers and designers to focus on
expertise - Logic can be reused in other applications
- Centralized logic means reduced work
- Can separate components across different machines
to balance load - Cons
- More complicated to code
6JavaBeans
- We'll just use the data package aspects of them.
- A Bean is a Java class which JSP can play with.
- Just a class with the following criteria
- It has a constructor with zero arguments
- It has public methods to get and set its
variables - These methods look like this
- getXXX() - to read what's in the variable
- setXXX() - to set the value in the variable
- All values returned from the gets are converted
to String - All values set will be converted from strings
7Typical Bean
- package mystuff
- import java.util.
- public class CurrentTimeBean implements
serializable - private int hours
- private int minutes
- public CurrentTimeBean()
- Calendar now Calendar.getInstance()
- this.hours now.get(Calendar.HOUR_OF_DAY)
- this.minutes now.get(Calendar.MINUTE)
-
- public int getHours()
- return hours
-
- public int getMinutes()
- return minutes
-
8JavaBean conventions
- Implements serializable is a good idea
- Good idea to have Bean in the class name
- For booleans use isXXX() to return the value,
instead of getXXX() - If your Bean needs to return null (which it
can't) create a method isValidXXX() to check if
the value is null or not before using it
9Accessing Beans in JSP
ltjspuseBean idtime scopesession
classmyStuff.CurrentTimeBean/gt lthtmlgtltbodygt It
is now ltjspgetProperty nametime
propertyminutes/gt past the hour. lt/bodygtlt/html
gt OR ltjspuseBean idtime scopesession
classmyStuff.CurrentTimeBean/gt lthtmlgtltbodygt It
is now lttime.getMinutes() gt past the
hour. lt/bodygtlt/htmlgt
10The jsp useBean tag
ltjspuseBean idtime scopesession
classmyStuff.CurrentTimeBean/gt
id what this bean will be called by the JSP
page class what kind of thing this bean is,
note it must be in a package for JSP to work
well scope where to look for the bean called
time of class
myStuff.CurrentTimeBean if there isn't
such a bean in that scope, create
one and put it there
11The Four Scopes
application the entire web application,
everyone running it everywhere session
each user gets his or her own session this is
it! request each request to the web
application has it's own space you
can forward the request from page to
page page this page, once you leave it
anything in this page scope is gone
12JavaBeans and Enterprise Java Beans (EJB)
- Enterprise Java Beans are like JavaBeans except
they can be shipped around to other machines - They're part of Java 2 Enterprise Edition
- Very useful for organizations with lots of
infrastructure - To learn more about J2EE, go to
http//java.sun.com/j2ee/index.html
13Model View Controller (MVC)
- The view is the presentation layer JSP pages
with little Java can only get information from
the model - The model is a set of JavaBeans representing the
state of your application logic is in the Beans - The controller is a servlet which
- Takes requests from the Application server
(tomcat) - Summons up the appropiate model objects and feeds
them the appropriate input - Reroutes the client to the appropriate view
14Real Life MVC example A Clock
- Model stores a time and has a way to get and set
that time - views analog and digital displays
- controller(s) us (we can wind the hands), the
gears (or whatever) that change the time
15MVC Graphically
16Why is MVC Good?
- Separates presentation, data and logic
- Less (or no) code in HTML pages
- Don't have to change every page when logic
changeds - All of the control flow is in the controller
- Only have to look in one place to see what's
happening - Maximizes reuse of components in model
17Do It Yourself MVC
- Create a servlet to act as a controller
- Takes requests from Tomcat
- Passes them onto the right JavaBeans
- Redirects to the right JSP after JavaBean returns
- Create a bunch of Beans to handle the logic, this
is the controller - Create a bunch of JSP pages to handle the view
18So you need to...
- Change the web.xml file to send requests to your
controller - Write the controller, which is the heart of your
application it's a servlet - Write the views they're JSP pages with tag
libraries - Write the model a bunch of JavaBeans
19The First View Page
lt_at_page contentType"text/html"gt lthtmlgt ltheadgtltti
tlegtWho are you?lt/titlegtlt/headgt ltbodygt ltform
method"POST" action"processHello.do"gt What is
your name? ltinput type"text" name"name"/gt ltbr/gt
ltinput type"hidden" name"action"
value"processName"/gt ltinput type"submit"/gt lt/for
mgt lt/bodygt lt/htmlgt
20What goes into the web.xml file
ltservletgt ltservlet-namegtcontrollerlt/servlet-
namegt ltdisplay-namegtcontroller
appletlt/display-namegt ltdescriptiongtthe
application's controller lt/descriptiongt
ltservlet-classgtmypackage.controllerlt/servlet-class
gt ltload-on-startupgt1lt/load-on-startupgt
lt/servletgt ltservlet-mappinggt
ltservlet-namegtcontrollerlt/servlet-namegt
lturl-patterngt.dolt/url-patterngt
lt/servlet-mappinggt
21The Controller Overview
import java.io. import java.net. import
javax.servlet. import javax.servlet.http. pub
lic class controller extends HttpServlet
public void init(ServletConfig config) throws
ServletException super.init(config)
public void destroy()
protected void doGet(HttpServletRequest
request, HttpServletResponse response)
throws ServletException, IOException
processRequest(request, response)
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws
ServletException, IOException
processRequest(request, response)
protected void processRequest(HttpServletRequest
request, HttpServletResponse response) throws
ServletException, IOException
//all the stuff you want to do
22Example processRequest Code
protected void processRequest(HttpServletRequest
request, HttpServletResponse response) throws
ServletException, IOException
String action request.getParameter("action")
if ("processName".equals(action))
String name request.getParameter("nam
e") HelloBean hello new
HelloBean() hello.setName(name)
boolean isKnown hello.isKnown()
if (isKnown)
goTo("/knownPerson.jsp", request, response)
else
goTo("/unknownPerson.jsp", request, response)
else
goTo("/unknownRequest.jsp", request, response)
protected void goTo(String url,
HttpServletRequest request, HttpServletResponse
response) if (url ! null)
RequestDispatcher dispatcher
getServletContext().getRequestDispatcher(url)
try dispatcher.forward(reques
t, response) catch (Exception e)
23The Model HelloBean.java
import java.util. public class HelloBean
private String name "" private static
String friendArray "gomez","morticia","wednes
day","pugsly" private static ArrayList
friends new ArrayList(Arrays.asList(friendArray)
) public java.lang.String getName()
return name public void
setName(java.lang.String name)
this.name name public boolean
isKnown() String theName getName()
boolean result false if
(friends.contains(theName)) result
true return result
24Another jsp page knownPerson.jsp
lt_at_page contentType"text/html"gt lthtmlgt ltheadgtlt
titlegtWelcome Back!lt/titlegtlt/headgt ltbodygt Good
to see you again, ltrequest.getParameter("name")
gt! lt/bodygt lt/htmlgt