L17 Presentation Layer Design

90
Lecture 17 Presentation Layer Design

description

Vefurinn hefur á undanförnum árum náð fótfestu sem sjálfgefið viðmót á hugbúnaði. Enterprise lausnir hafa gjarnan vefviðmót, bæði fyrir viðskiptavini og starfsmenn. Á síðari árum hafa snjallsímalaunsir bæst við. Við það hefur orðið skýrari skil milli viðmóts og bakenda, með forritaskilum - API. Í þessum fyrirlestri skoðum við framsetningarlagið - Presentation Layer Design og hvernig við getum hannað forrit fyrir þetta lag. Skoðuð eru ýmis munstur og það helsta er eitt það frægasta í hugbúnaðargerð: Model View Controller. Við skoðum einnig Play framework en það er ramminn sem við notum til að forrita.

Transcript of L17 Presentation Layer Design

Page 1: L17 Presentation Layer Design

Lecture 17Presentation Layer Design

Page 2: L17 Presentation Layer Design

2

Reading Patterns

– Model View Controller– Page Controller– Front Controller– Template View– Application Controller

Page 3: L17 Presentation Layer Design

3

Agenda The Web Layer

– Model-View-Controller Input controller patterns

– Page Controller– Front Controller– Application Controller

View patterns– Template View

Page 4: L17 Presentation Layer Design

Play! Framework We will be using Play! framework

– Based on MVC

Page 5: L17 Presentation Layer Design

The Web Layer

5

Page 6: L17 Presentation Layer Design

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: L17 Presentation Layer Design

7

Presentation and Web Layers Embedded and Desktop clients

Web Browser is a different type of client

Page 8: L17 Presentation Layer Design

Web Applications

8

Page 9: L17 Presentation Layer Design

9

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 10: L17 Presentation Layer Design

10

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 11: L17 Presentation Layer Design

11

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 12: L17 Presentation Layer Design

12

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 13: L17 Presentation Layer Design

13

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 14: L17 Presentation Layer Design

14

Web Design Web Layer must handle the request and

the response

Page 15: L17 Presentation Layer Design

API Based User Interface is HTML5 or Native App

– Server side is just API– Information format in XML or Json

HTML5

JavaScript Web Server

DB

Controllers

Service Layer

Domain Model

Data Source LayerNative App

HTTP Request

HTTP Request

Json/XML

Json/XML

Page 16: L17 Presentation Layer Design

Model-View-Controller

16

Page 17: L17 Presentation Layer Design

17

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 18: L17 Presentation Layer Design

18

Model View Controller How It Works

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

Page 19: L17 Presentation Layer Design

19

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 20: L17 Presentation Layer Design

20

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 21: L17 Presentation Layer Design

21

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 22: L17 Presentation Layer Design

22

MVC in Web Design

Page 23: L17 Presentation Layer Design

23

MVC Patterns Input controller patterns

– Page Controller– Front Controller– Application Controller

View patterns– Template View– Transform View – Transforms view to some

format– Two Step View – Logical Screen and final UI

Page 24: L17 Presentation Layer Design

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 25: L17 Presentation Layer Design

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 26: L17 Presentation Layer Design

26

MVC Patterns Input controller patterns

– Page Controller– Front Controller– Application Controller

View patterns– Template View– Transform View – Transforms view to some

format– Two Step View – Logical Screen and final UI

Page 27: L17 Presentation Layer Design

27

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 28: L17 Presentation Layer Design

28

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 29: L17 Presentation Layer Design

29

Page Controller pattern

Page 30: L17 Presentation Layer Design

30

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 31: L17 Presentation Layer Design

31

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 32: L17 Presentation Layer Design

32

Front ControllerA 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 33: L17 Presentation Layer Design

33

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 34: L17 Presentation Layer Design

34

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 35: L17 Presentation Layer Design

35

Front Controller Handler takes the request

– Examines the URL– Creates command and calls the command

Page 36: L17 Presentation Layer Design

36

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 37: L17 Presentation Layer Design

37

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 38: L17 Presentation Layer Design

38

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 39: L17 Presentation Layer Design

39

Application Controller How it works

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

Page 40: L17 Presentation Layer Design

40

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 41: L17 Presentation Layer Design

41

MVC Patterns Input controller patterns

– Page Controller– Front Controller– Application Controller

View patterns– Template View– Transform View – Transforms view to some

format– Two Step View – Logical Screen and final UI

Page 42: L17 Presentation Layer Design

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 43: L17 Presentation Layer Design

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 44: L17 Presentation Layer Design

44

MVC Patterns Input controller patterns

– Page Controller– Front Controller– Application Controller

View patterns– Template View– Transform View – Transforms view to some

format– Two Step View – Logical Screen and final UI

Page 45: L17 Presentation Layer Design

45

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 46: L17 Presentation Layer Design

46

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 47: L17 Presentation Layer Design

47

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 48: L17 Presentation Layer Design

48

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 49: L17 Presentation Layer Design

49

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 50: L17 Presentation Layer Design

50

Example

Page 51: L17 Presentation Layer Design

Template Velocity template example

Page 52: L17 Presentation Layer Design

Template Scala template example

@(customer: Customer, orders: Seq[Order]) <h1>Welcome @customer.name!</h1>

<ul> @orders.map { order => <li>@order.title</li>} </ul>

Page 53: L17 Presentation Layer Design

Template Template Engine will execute the view and

create HTML

Template Engine HTMLView TemplateLanguage

reads generates

ModelParameters

Page 54: L17 Presentation Layer Design

What pattern is described like this?

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

QUIZ

Page 55: L17 Presentation Layer Design

What pattern is described like this?

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

QUIZ

Page 56: L17 Presentation Layer Design

MVC Design

56

Page 57: L17 Presentation Layer Design

57

MVC Design

2. Call the model

Page 58: L17 Presentation Layer Design

58

MVC Design

Page 59: L17 Presentation Layer Design

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: L17 Presentation Layer Design

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: L17 Presentation Layer Design

Combining Model and View

Input ControllerHTTP/HTML handling

ModelDomain Layer

ViewTemplate

ModelParameters

Page 62: L17 Presentation Layer Design

API Design

62

Page 63: L17 Presentation Layer Design

Trends Mobile is bigger than Desktop

– Mobile is the most important platform for many applications

The Programmable Web– If you want to be in the game, you have an API

When Good Enough is Not Enough– Rise Apps– Single purpose programs

Page 64: L17 Presentation Layer Design

Rise of the API Separating UI from code

– Model View Controller patterns User Interface is HTML5 or Native App

– Server side is just API– Information format in XML or Json

Page 65: L17 Presentation Layer Design
Page 66: L17 Presentation Layer Design

API Based User Interface is HTML5 or Native App

– Server side is just API– Information format in XML or Json

HTML5

JavaScript Web Server

DB

Controllers

Service Layer

Domain Model

Data Source LayerNative App

HTTP Request

HTTP Request

Json/XML

Json/XML

Page 67: L17 Presentation Layer Design

API Design HTTP is designed to be simple

– GET, POST, PUT, DELETE Trends was to build on top of this

– SOAP SOAP does not use any of the HTTP built in

functionality– Adds a complexity layer on top

Page 68: L17 Presentation Layer Design

REST Explained Briefly REST over HTTP leverages HTTP

– Uses HTTP request methods: GET, POST, PUT, DELETE

GET is safe – does not have side effects– Possible to cache client side– 80% or more of the requests are GET

PUT and DELETE are idempotent

Page 69: L17 Presentation Layer Design

REST Explained Briefly GET to get resource POST to add resource PUT to update resource DELETE to delete resource

Page 70: L17 Presentation Layer Design

Getting

Adding

Updating

GET someservice.com/api/customer/3829

POST someservice.com/api/customer/

REST examples

PUT someservice.com/api/customer/3829

Page 71: L17 Presentation Layer Design

Play Framework

71

Page 72: L17 Presentation Layer Design
Page 73: L17 Presentation Layer Design

73

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 74: L17 Presentation Layer Design

74

Play MVC Model

– Domain specific Java classes View

– User Interface– HTML, XML, JSON– Scala template language

Controller – Java classes that take requests and operate on

the model– Results are rendered by the view

Page 75: L17 Presentation Layer Design

75

Play MVC

Page 76: L17 Presentation Layer Design

76

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 77: L17 Presentation Layer Design

77

Page 78: L17 Presentation Layer Design

78

Creating a Play app Unzip typesafe-activator-1.2.10-

minimal.zip Open CMD or Terminal Run activator

– This will download and install Play Framework$activaor

Add activator to PATH

Page 79: L17 Presentation Layer Design

79

Creating a Play app Open CMD or Terminal

>activator new RuBook Creates a new appliction

>cd RuBook>play run

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

Page 80: L17 Presentation Layer Design

80

Page 81: L17 Presentation Layer Design

81

Page 82: L17 Presentation Layer Design
Page 83: L17 Presentation Layer Design

83

Page 84: L17 Presentation Layer Design

84

Play in IntelliJ

Page 85: L17 Presentation Layer Design
Page 86: L17 Presentation Layer Design

86

Application.java input controller

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

public class Application extends Controller{

public static Result index() { return ok(index.render("Fagra veröld")); }

Page 87: L17 Presentation Layer Design

87

index.html View is a Scala template

views/index.scala.html

Compiles in to classviews/html/index.class

@(message: String)

@main("Welcome to Play") {

@message

}

Page 88: L17 Presentation Layer Design

88

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 89: L17 Presentation Layer Design

89

Errors Play displays errors

– CMD has more information

Page 90: L17 Presentation Layer Design

90

Summary Web Presenation Patterns

– Model View Controller– Page Controller– Front Controller– Template View– Application Controller

Play framework