You are on page 1of 33

Perspective: Servlet and JSP

Servlet Life Cycle

Life of a JSP file

Uses of JSP Constructs

Scripting elements calling servlet code directly

Scripting elements calling servlet code indirectly (by means of


utility classes) Beans

Servlet/JSP combo (MVC)


MVC with JSP expression language Custom tags

Servlet vs JSP

JSP is a webpage scripting language that can generate dynamic

content while Servlets are Java programs that are already compiled
which also creates dynamic web content. Servlets run faster compared to JSP

JSP can be compiled into Java Servlets


Its easier to code in JSP than in Java JSP and Java Servlets are usually used in conjunction nowadays

Why Combine Servlets & JSP?

Typical picture: use JSP to make it easier to develop and

maintain the HTML content


For simple dynamic code, call servlet code from scripting elements For slightly more complex applications, use custom classes called from scripting elements For moderately complex applications, use beans and custom tags

But, that's not enough


For complex processing, starting with JSP is awkward

Despite the ease of separating the real code into separate classes, beans, and
custom tags, the assumption behind JSP is that a single page gives a single basic look

Possibilities for Handling a Single Request


Servlet only
Output is a binary type. E.g.: an image No output. E.g.: you are doing forwarding or redirection as in Search Engine example. Format/layout of page is highly variable. E.g.: portal.

JSP only
Output is mostly character data. E.g.: HTML
Format/layout mostly fixed.

Combination
A single request will result in multiple substantially different looking results. Complicated data processing, but relatively fixed layout.

These apply to a single request


You still use both servlets and JSP within your overall application.

Design Patterns

Model View Controller

History

A framework pattern for reusable applications. Depends on the Observer pattern. First developed by Xerox PARC for Smalltalk-80. Used by the Application Kit system in NeXTstep. Used by the Cocoa APIs for Apples OS X. Recommended structural framework pattern in J2EE.

Design Patterns

The hard problem in O-O programming is deciding what objects to have, and what their responsibilities are Design Patterns describe the higher-level organization of solutions to

common problems
Design patterns are a major topic in O-O design

10

Observable
An Observable is an object that can be observed An Observer is notified when an object that it is observing announces a change

When an Observable wants the world to know about what it has done, it executes:
setChanged(); notifyObservers(); /* or */ notifyObservers(arg);
The arg can be any object

The Observable doesnt know or care who is looking But you have attach an Observer to the Observable with:
myObservable.addObserver(myObserver); This is best done in the controller class not in the model class!
11

Observer and Observable


java.util provides an Observer interface and an Observable class An Observable is an object that can be observed An Observer is notified when an object that it is observing

announces a change
Heres an analogy:
An Observable is like a Button

An Observer is like a Listener


You have to attach a Listener to a Button

Another analogy:
12

Observer
Observer is an interface An Observer implements public void update(Observable obs, Object arg) This method is invoked whenever an Observable that it is listening to does an addNotify() or addNotify(arg) The obs argument is a reference to the observable object itself If the Observable did addNotify(), the arg is null

13

Observer Pattern

Defines a one-to-many dependency between objects so that when

one object changes state, all its dependents are notified and
updated automatically. Used to decouple the subject from the observer, since the subject

needs little information to notify the observer.


Can result in excessive notifications.

The MVC pattern

MVC stands for Model-View-Controller

The Model is the actual internal representation


The View (or a View) is a way of looking at or displaying the model The Controller provides for user input and modification

These three components are usually implemented as separate


classes

15

MVC

Divides interactive applications into three distinct components:


Model Contains core functionality and data.
View Displays information to user. Controller Handles user input.

Includes a change-propagation mechanism.


Ensures consistency between user interface and model.

Model

Encapsulates data.
Exports procedures that perform specific application processing.
Used by Controller on behalf of user.

Provides functions to access Models data.


Used by View, maybe Controller too.

Model

Manages change-propagation mechanism.


Maintains registry of components dependent on the model.
Views and controllers register their need to be informed about changes. Changes in state of model trigger notifications.

Responsibilities include:
Providing functional core. Register dependent views and controllers. Notify dependent components about changes.

View

Presents information to user.


Different Views present information in different ways.

Defines an update procedure that is activated by changepropagation mechanism in Model.

Retrieves current data values to be displayed from Model.


During initialization, associates itself with Model and registers for change notification. Corresponds to a single Controller. Offers functionality that allows Controller to manipulate display.
E.g. scrolling.

Controller

Accepts user inputs as events.

Translates events into requests for the associated Model or View.

Registers itself with Model if it depends on state of the Model in any way.
E.g. A certain change in the Model results in a menu item being enabled or
disabled.

Combining Controller and View


Sometimes the Controller and View are combined, especially in small programs Combining the Controller and View is appropriate if they are very interdependent

The Model should still be independent


Never mix Model code with GUI code!

21

Separation of concerns
As always, you want code independence The Model should not be contaminated with control code or display code The View should represent the Model as it really is, not some remembered status The Controller should talk to the Model and View, not manipulate them

The Controller can set variables that the Model and View can read

22

Advantages

Separation between the data layer and the interface is the key:
The view is easily replaced or expanded. Model data changes are reflected in all interfaces because all views are Observers. Better scalability since UI and application logic are separated. Distribution over a network is greatly simplified.

Key points
A Model does the business logic
It should be I/O free

Communication with the Model is via methods


This approach gives maximum flexibility in how the model is used

The Controller organizes the program and provides input (control) to the Model The View displays what is going on in the model
It should never display what should be going on in the model For example, if you ask to save a file, the View shouldnt itself tell you that the file has been savedit should tell you what the model reports.
24

MVC1 Architecture Page centric

MVC2 Architecture

Comparison of Web Frameworks

MVC Frameworks

Adobe Flex

Grails, together with Groovy


Google Web Toolkit (GWT), together with GWT-Ext JavaServer Faces (JSF), together with Facelets

Seam
Spring MVC, which is a part of the Spring Framework Stripes

Struts 2
Tapestry Wicket

Pros and Cons

JSF

Pros:

Java EE Standard - lots of demand and jobs


Fast and easy to develop with initially Lots of component libraries

Cons:
Tag soup for JSPs Doesn't play well with REST or Security

No single source for implementation

Spring MVC

Pros:

Lifecyle for overriding binding, validation, etc.


Integrates with many view options seamlessly: JSP/JSTL, Tiles, Velocity, FreeMarker, Excel, PDF

Inversion of Control makes it easy to test


Cons: Configuration intensive - lots of XML

Almost too flexible - no common parent


Controller No built-in Ajax support

Stripes

Pros:

No XML - Convention over Configuration


Good documentation (easy to learn) Enthusiastic community

Cons:
Small Community Not as actively developed as other projects

Hard-coded URLs in ActionBeans

Struts 2

Pros:

Simple architecture - easy to extend


Tag Library is easy to customize with FreeMarker or Velocity

Controller-based or page-based navigation


Cons: Documentation is poorly organized

No feedback for missing properties or invalid


OGNL expressions Googling results in Struts 1.x documentation

You might also like