l10 web programming

80
Lecture 10 Web Programming

Upload: olafur-andri-ragnarsson

Post on 07-May-2015

883 views

Category:

Technology


0 download

DESCRIPTION

The web has become the default and standard user interface for enterprise programming. In this lecture we look at the challenges of adding a web user interface to enterprise systems. The main design pattern we look at is the classical Model View Controller. The idea is to break user interface components into three distinct roles. The Controller is the entry of the request, and handles the parameters that come with the request. The controller uses the model for the "state" or domain logic, be it calculations or getting some data. The model will deliver some data that needs to be rendered. It is the responsibility of the view to render the user interface. We will also briefly look at the Play! framework: http://www.playframework.org/

TRANSCRIPT

Page 1: L10 Web Programming

Lecture 10Web Programming

Page 2: L10 Web Programming

2

Reading Fowler

– Chapter 4 Web Presentation– Chapter 14 Web Presentation Patterns

Patterns– Model View Controller (330)– Page Controller (333)– Front Controller (344)– Template View (350)– Transform View (361)– Two-Step View (365)– Application Controller (379)

Page 3: L10 Web Programming

3

Agenda The Web Layer

– Model-View-Controller (330) Input controller patterns

– Page Controller (333) – Front Controller (344)– Application Controller (379)

View patterns– Template View (350)– Transform View (361)– Two Step View (365)

Page 4: L10 Web Programming

Play! Framework We will be using Play! framework

– Based on MVC

Page 5: L10 Web Programming

The Web Layer

5

Page 6: L10 Web Programming

6

The Challenge How to design web applications? How to separate user interface from the

business logic?– User Interface is an HTML string

How to provide OO design?– Code reuse

How can we abstract underlying system– For example data base

Page 7: L10 Web Programming

7

Presentation and Web Layers Embedded and Desktop clients

Web Browser is a different type of client

Page 8: L10 Web Programming

Web Applications

8

Page 9: L10 Web Programming

9

Web Layer Design How to design Web Applications

Two approaches– Script based – Code using HTML– Server Page based – HTML page with code

Web Browser WebServer

HTML/HTTP

Web Application

??DB

Server

Page 10: L10 Web Programming

10

Web Applications Client is a web Browser

– All interface is HTML with graphics Server is configured to map URLs to

applications– The web application can be script or page

Page 11: L10 Web Programming

11

Script Based Useful when the logic and the flow is important

– Request is not easily mapped to a single page

Examples– CGI, ISAPI, Java Servlets

Page 12: L10 Web Programming

12

Server Page Based Useful where there are lots of pages

– Flow is not as important– Each request can easily be mapped to a page

Examples– PHP, JSP, ASP

Page 13: L10 Web Programming

13

Web Design Web Layer must handle the request and

the response

Page 14: L10 Web Programming

14

The Three Layers Presentation

– User’s interface to the system– User can be another system– Accepts input, displays views

Domain– The Application of the system– The “Business logic”– Has the tendency to creep into presentation

and data source Data Source

– Connection to the database

Page 15: L10 Web Programming

Model-View-Controller

15

Page 16: L10 Web Programming

16

Model View ControllerSplits user interface interactions

into three distinct roles Separates the user interface from the logic

– Originally from 70s Smalltalk– Similar to Doc/View in MFC

MVC considers three roles– Clear separations of concerns– Model: The domain layer handles state– View: Presentation logic– Controller: Connects the model and the view

Page 17: L10 Web Programming

17

Model View Controller How It Works

– Model: The domain layer handles state– View: Presentation logic– Controller: Connects the model and the view

Page 18: L10 Web Programming

18

Model View Controller Benefits

– Separation of the view from the domain logic in the model

– This is key in any presentation design Importance of MVC

– View and model are different concerns– View can change, usually the model is the

same– Easy to test the model without the view

Coupling Dependencies– View depends on the model, but the model is

not depending on the view

Page 19: L10 Web Programming

19

Model View Controller When to Use It

– The value is in the separation of concern– Separating the model and the view– As this separation is so fundamental in any

software design, any non-trivial system should use MVC in some form

Page 20: L10 Web Programming

20

MVC in Web Design Web Applications are request/response

based Input Controller

– Takes the request– Examines the input parameters– Calls the Model– Decides how to

handle the response– Sends the control

to the View for rendering

Page 21: L10 Web Programming

21

MVC in Web Design

Page 22: L10 Web Programming

22

MVC Patterns Input controller patterns

– Page Controller (333) – Front Controller (344)– Application Controller (379)

View patterns– Template View (350)– Transform View (361)– Two Step View (365)

Page 23: L10 Web Programming

What design principle is the most important in Model View Controller?

A) Separation of different concernsB) All request go the same placeC) Easy to test different componentsD) Easy to change the view

QUIZ

Page 24: L10 Web Programming

24

MVC Patterns Input controller patterns

– Page Controller (333) – Front Controller (344)– Application Controller (379)

View patterns– Template View (350)– Transform View (361)– Two Step View (365)

Page 25: L10 Web Programming

25

Page ControllerAn object that handles a request for a specific page or action on a Web site

One input controller for each logical page of the web site

Page 26: L10 Web Programming

26

Page Controller How It Works

– One Page Controller for each logical page Page controller as Script

– Servlet or CGI program– Useful for web application that need some logic and

data Page controller as a server page

– ASP, PHP, JSP– Combines the Page Controller and Template View– Helpers used to get data from the model– Works fine if the logic is simple or none

Page 27: L10 Web Programming

27

Page Controller pattern

Page 28: L10 Web Programming

28

Page Controller The basic responsibility of a Page

Controller are– Decode the URL and extract any form data to

figure out all data for the action– Create and invoke any model objects to

process the data.• All relevant data from the HTML request should be

passed to the model so that the mode objects don’t need any connection to the HTML request

– Determine which view should display the result page and forward the information to it

Page 29: L10 Web Programming

29

Page Controller When to Use It

– Works well in a site where the controller logic is simple

– When the controller logic is simple the Front Controller adds too much overhead

Examples– Simple Display with a Servlet Controller and a

JSP View– Using a JSP as a Handler– Page Handler with Code Behind

Page 30: L10 Web Programming

30

Front Controller (344)A controller that handles all requests for

a web site

One controller handles all requests– The handler dispatches to command objects

for behaviour particular to the request

Page 31: L10 Web Programming

31

Front Controller How It Works

– Takes care of common tasks, for example security, authentication, i18n, and so on

– Built on Commands– Usually implemented as script, not page

Two phases– Request handling – Web Handler– Command handling – Command classes

Page 32: L10 Web Programming

32

Front Controller Request handling – Web Handler

– Any common logic – Authentication, Web Security etc.– Changes in one place apply for the whole site– Handler creates the requested command

Command handling – Command classes– Specific functionality– Command classes extend abstract classes and

implements process method– Can be separated form the web infrastructure

Page 33: L10 Web Programming

33

Front Controller Handler takes the request

– Examines the URL– Creates command and calls the command

Page 34: L10 Web Programming

34

Front Controller Web handler can have commands

statically or dynamically– Static case has the advantage of explicit

logic and compile time error checking– Dynamic case has some property file to map

request URL to command classes– Dynamic case has more flexibility to add new

commands

Page 35: L10 Web Programming

35

Front Controller When to Use It

– Front controller is more complicated design than the Page Controller

– Only one controller needs to be configured in the web server, the handler takes care of the dispatching

– With dynamic commands, you can easily add new commands

– Single point of entry allowing centralized logic

Page 36: L10 Web Programming

36

Application ControllerA centralized point for handling screen

navigation and the flow of an application

Applications that have significant amount of logic about the screens to use at different points– For example Wizard style applications– Screens depend on the state

Page 37: L10 Web Programming

37

Application Controller How it works

– Two responsibilities: Decide which domain logic to use and deciding the view

Page 38: L10 Web Programming

38

Application Controller Can be used with Command pattern

– Commands execute the domain logic– Not easy to determine what is domain logic

and what is the application logic State machine

– The Controller must maintain a state When to Use It

– If the flow and application logic is complex and simple controllers need to share code

Page 39: L10 Web Programming

39

MVC Patterns Input controller patterns

– Page Controller (333) – Front Controller (344)– Application Controller (379)

View patterns– Template View (350)– Transform View (361)– Two Step View (365)

Page 40: L10 Web Programming

We are designing an application for corporate tax reduction which have multiple of screens and various conditions and exceptions. What controller pattern might be useful

A) Input ControllerB) Page ControllerC) Front ControllerD) Application Controller

QUIZ

Page 41: L10 Web Programming

41

MVC Patterns Input controller patterns

– Page Controller (333) – Front Controller (344)– Application Controller (379)

View patterns– Template View (350)– Transform View (361)– Two Step View (365)

Page 42: L10 Web Programming

42

Template ViewRenders information into HTML by

embedding markers in an HTML page

Place markers in HTML page that can be resolved into calls to get dynamic information

Page 43: L10 Web Programming

43

Template View How it Works

– Embed markers into static HTML page when it’s written

– When the page is used to service a request, the markers are replaced by the results of some computation

Server Pages for presentation– ASP, PHP, JSP– Page receives data to work with– Allow scriptlets

Page 44: L10 Web Programming

44

Template View Embedding the markers

– Markers are used for dynamic data– <% and %> JSP, ASP– Tags such as JSTL and customized– Data is sent with the request

Helper Objects– Provide helper object that give the results– Avoids scriptlets and keeps the code in classes

Page 45: L10 Web Programming

45

Template View Conditional display

– Most Server Pages support conditional tags– Provides some presentation logic

– Can lead to bad code and should be avoided if possible

– Try to move the condition into helper object or tags

<c:if test="${!empty cookie.userName}"> Welcome back <c:out value="${cookie.userName.value}" /> </c:if>

Page 46: L10 Web Programming

46

Example<jsp:include page="top.jsp" flush="true" /><table cellpadding="4" cellspacing="4" border="0" width="100%"><tr><td><%@ page import="is.ru.honn.domain.User" session="true" %>

<% User user = (User)request.getSession().getAttribute ("user"); if (user == null) {%><h1>Sportvefurinn</h1>Ef þú ert nýr notandi getur þú skráð þig með því að smella á <b>Nýskrá</b> í valmyndinni hér til vinstri.Annars, smelltu á <b>Innskrá</b> til að skrá þig inn á vefinn.<% } else { %><h1>Halló <%= user.getName() %></h1>Smelltu á <b>Leikir</b> til að sjá næstu leiki.<% } %></td></tr></table>

<%-- bot.jsp síðan inniheldur restina af HTML síðunni --%><jsp:include page="bot.jsp" flush="true" />

Page 47: L10 Web Programming

47

Example

Page 48: L10 Web Programming

Template Velocity template example

Page 49: L10 Web Programming

Template Template Engine will execute the view and

create HTML

Template Engine HTMLView TemplateLanguage

reads generates

ModelParameters

Page 50: L10 Web Programming

50

Transform ViewA view that processes domain data element

by element and transforms it into HTML

Transformation of the domain data into HTML– Think how elements are transformed

Page 51: L10 Web Programming

51

Transform View How It Works

– Organized around separate transforms for each kind of input element

– XSLT (EXtensible Stylesheet Language) is one way Each object can be serialized into XML which can be transform to any output using XSLT

When to Use It– Comes down to preference– XSLT is awkward to work with without tools– Avoids too much logic in the view– Easy to test and verify the output

Page 52: L10 Web Programming

52

Two Step ViewTurns domain data into HTML in two steps: first

by forming some kind of logical page, then rendering the logical page into HTML

Splits the transformation from domain data to HTML into two steps– First transforms the model data into logical page– Second converts the logical page into HTML

Second step can provide additional elements– Global changes to big sites

Page 53: L10 Web Programming

53

Two Step View How It Works

– The process oftransforming thedata to HTML is intwo steps

Intermediate form– Contains fields,

header, footer, etc.– Logical information

Page 54: L10 Web Programming

54

Two Step View When to Use It

– When we need to separate the formatting from the logical page

– Multi-appearance applications that have the same functionality but different looks

– When global changes are needed– The second state can be Template View of

Transform View

Page 55: L10 Web Programming

What pattern is described like this?

A) Template ViewB) Transform ViewC) Model ViewD) Two Step View

QUIZ

Page 56: L10 Web Programming

MVC Design

56

Page 57: L10 Web Programming

57

MVC Design

2. Call the model

Page 58: L10 Web Programming

58

MVC Design

Page 59: L10 Web Programming

59

Domain and Presentation Data from the model need to be accessed

by the view– Data is simple classes– Controller handles the flow and decides which

view to call– View needs access to data

Two methods– Use Request if lifetime of

the data is the request– Use Session if the data

must span many requests

Page 60: L10 Web Programming

60

Domain and Presentation Single Request

– Same request object is used– Use getParameter to get input– Store the data in request

using setAttribute– JSP can access the

data using therequest

Page 61: L10 Web Programming

Combining Model and View

Input ControllerHTTP/HTML handling

ModelDomain Layer

ViewTemplate

ModelParameters

Page 62: L10 Web Programming

Play! Framework

62

Page 63: L10 Web Programming
Page 64: L10 Web Programming

64

Play! framework Open source web application framework

– Written in Java– Build and deployment is all handled by scripts

Follows the model-view-controller architectural pattern

Goals– Optimize developer productivity by using

convention over configuration, hot code reloading and display of errors in the browser

Page 65: L10 Web Programming

65

Play! features Stateless: Play is fully RESTful No configuration: download, unpack and develop Easy round trips: no need to deploy to an application

server Integrated unit testing: JUnit and Selenium support is

included in the core Elegant API: rarely will a developer need to import any

third party library Static methods: all controller entry points and business

logic methods are declared as static CRUD module: easily build administration UI with little code Server built in: Jboss Netty web server is used

Page 66: L10 Web Programming

66

Play! MVC Model

– Domain specific Java classes View

– User Interface– HTML, XML, JSON

Controller – Java classes that take requests and operate on

the model– Results are rendered by the view

Page 67: L10 Web Programming

67

Play! MVC

Page 68: L10 Web Programming

68

The Request Life Cycle1. An HTTP Request is received by the framework2. The Router component tries to find the most

specific route able to accept this request. The corresponding action method is then invoked

3. The application code is executed4. If a complex view needs to be generated, a

template file is rendered5. The result of the action method (HTTP Response

code, Content) is then written as an HTTP Response

Page 69: L10 Web Programming

69

Page 70: L10 Web Programming

70

Creating a Play! app Unzip play-2.2.0.zip Add to path Open CMD or Terminal

>play new RuBook Creates a new appliction

>cd RuBook>play run

Runs the Web App Open a browser and goto localhost:9000

Page 71: L10 Web Programming

71

Page 72: L10 Web Programming

72

Page 73: L10 Web Programming

73

Page 74: L10 Web Programming

74

Page 75: L10 Web Programming

75

Play! in IntelliJ

Page 76: L10 Web Programming

76

Application.java input controller

– controllers.Application– Requests will go to this Java class

package controllers;

import play.*;import play.mvc.*;

import views.html.*;

public class Application extends Controller { public static Result index() { return ok(index.render("Your new application is ready.")); } }

Page 77: L10 Web Programming

77

index.html View is views.index.scala.html

@(message: String)

@main("Welcome to Play") { @play20.welcome(message, style = "Java") }

Page 78: L10 Web Programming

78

Routing conf/routes contains the routing

information# Routes# This file defines all application routes (Higher priority routes first)# ~~~~

# Home pageGET / controllers.Application.index()

# Map static resources from the /public folder to the /assets URL pathGET /assets/*file controllers.Assets.at(path="/public", file)

Page 79: L10 Web Programming

79

Errors Play! displays errors

– CMD has more information

Page 80: L10 Web Programming

80

Summary Web Presenation Patterns

– Model View Controller (330)– Page Controller (333)– Front Controller (344)– Template View (350)– Transform View (361)– Two-Step View (365)– Application Controller (379)

Play! framework