L13 Presentation Layer Design

92
HÖNNUN OG SMÍÐI HUGBÚNAÐAR 2015 L13 PRESENTATION LAYER DESIGN

Transcript of L13 Presentation Layer Design

Page 1: L13 Presentation Layer Design

HÖNNUN OG SMÍÐI HUGBÚNAÐAR 2015L13 PRESENTATION LAYER DESIGN

Page 2: L13 Presentation Layer Design
Page 3: L13 Presentation Layer Design

HÖNNUN OG SMÍÐI HUGBÚNAÐAR 2015L13 PRESENTATION LAYER DESIGN

Page 4: L13 Presentation Layer Design

Agenda

▪ Web Presentation Patterns– Model View Controller– Page Controller– Front Controller– Application Controller– Template View

▪ MVC Design▪ API Design▪ Play framework

Page 5: L13 Presentation Layer Design

Reading

Model View ControllerPage ControllerFront ControllerTemplate ViewApplication Controller

Page 6: L13 Presentation Layer Design

Play! Framework▪ We will be using Play! framework– Based on MVC

Page 7: L13 Presentation Layer Design

7

The Web Layer

Page 8: L13 Presentation Layer Design

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

8

Page 9: L13 Presentation Layer Design

Presentation and Web Layers▪ Embedded and Desktop clients

▪ Web Browser is a different type of client

9

Page 10: L13 Presentation Layer Design

Web Applications

Page 11: L13 Presentation Layer Design

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

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

WebApplication

DBServer

HTML/HTTP

Page 13: L13 Presentation Layer Design

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

Web Browser WebServer

Configuration file

HTTP Request

HTTP Request

Web Script

Web Page

Page 14: L13 Presentation Layer Design

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

Web Browser

WebServer

HTTP Request

HTTP Request

Web Application

CodeHTML

JavaScript

CodeCode

Template

DB

Page 15: L13 Presentation Layer Design

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

Web Browser

WebServer

HTTP Request

HTTP Request

Web Application

HTML

JavaScriptCode

CodeServer Page DBServer

Page Code

Page 16: L13 Presentation Layer Design

Web Design▪ Web Layer must handle the request and the response

Web Browser

WebLayer

Domain Layer Data Source Layer

HTTPrequest Request

Controller

PresentationView

HTTPresponse

Service Layer

Domain ModelTable DataGateway

Page 17: L13 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 18: L13 Presentation Layer Design

Model-View-Controller

Page 19: L13 Presentation Layer Design

Model View ControllerSplits user interface interactions

into three distinct roles

▪ Separates the user interface from the logic– Originally from 70s Smalltalk▪ 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 20: L13 Presentation Layer Design

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

20

Page 21: L13 Presentation Layer Design

Model View Controller

BenefitsSeparation of the view from the domain logic in the modelThis is key in any presentation design

Importance of MVCView and model are different concernsView can change, usually the model is the sameEasy to test the model without the view

Coupling DependenciesView depends on the model, but the model is not depending on the view

Page 22: L13 Presentation Layer Design

Model View ControllerWhen to Use It

The value is in the separation of concernSeparating the model and the viewAs this separation is so fundamental in any software design, any non-trivial system should use MVC in some form

Page 23: L13 Presentation Layer Design

MVC in Web DesignWeb Applications are request/response based

Input Controller 1. Takes the request2. Examines the input parameters3. Calls the Model4. Decides how to

handle the response5. Sends the control

to the View for rendering

6. Returns the Response

Controllerrequest

Model

View

response

Page 24: L13 Presentation Layer Design

MVC in Web Design

Page 25: L13 Presentation Layer Design

MVC Patterns

View patternsTemplate ViewTransform ViewTwo Step View

Input controller patternsPage ControllerFront ControllerApplication Controller

Page 26: L13 Presentation Layer Design

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

A) Separation  of  different  concerns B) All  request  go  the  same  place C) Easy  to  test  different  components D) Easy  to  change  the  view

QUIZ

Page 27: L13 Presentation Layer Design

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

A) Separation  of  different  concerns B) All  request  go  the  same  place C) Easy  to  test  different  components D) Easy  to  change  the  view

QUIZ

Page 28: L13 Presentation Layer Design

MVC Patterns

View patternsTemplate ViewTransform ViewTwo Step View

Input controller patternsPage ControllerFront ControllerApplication Controller

Page 29: L13 Presentation Layer Design

Page Controller

An 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 30: L13 Presentation Layer Design

Page Controller

How It WorksOne Page Controller for each logical page

Page controller as ScriptServlet or CGI programUseful for web application that need some logic and data

Page controller as a server pageASP, PHP, JSPCombines the Page Controller and Template ViewHelpers used to get data from the modelWorks fine if the logic is simple or none

Page 31: L13 Presentation Layer Design

Page Controller pattern

Page 32: L13 Presentation Layer Design

Page Controller▪ The basic responsibility of a Page Controller are

1. Decode the URL and extract any form data to figure out all data for the action

2. 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

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

Page 33: L13 Presentation Layer Design

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

Front ControllerA controller that handles all requests for

a web site

One controller handles all requestsThe handler dispatches to command objects for behaviour particular to the request

Page 35: L13 Presentation Layer Design

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

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

36

Page 37: L13 Presentation Layer Design

Front Controller▪ Handler takes the request– Examines the URL– Creates command and calls the command

Page 38: L13 Presentation Layer Design

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

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 centralised logic

Page 40: L13 Presentation Layer Design

Application ControllerA centralised 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 pointsFor example Wizard style applicationsScreens depend on the state

Page 41: L13 Presentation Layer Design

Application Controller▪ How it works– Two responsibilities: Decide which domain logic to use and

deciding the view

41

Page 42: L13 Presentation Layer Design

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

42

Page 43: L13 Presentation Layer Design

MVC Patterns

View patternsTemplate ViewTransform ViewTwo Step View

Input controller patternsPage ControllerFront ControllerApplication Controller

Page 44: L13 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  Controller B) Page  Controller C) Front  Controller D) Application  Controller

QUIZ

Page 45: L13 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  Controller B) Page  Controller C) Front  Controller D) Application  Controller

QUIZ

Page 46: L13 Presentation Layer Design

MVC Patterns

View patternsTemplate ViewTransform ViewTwo Step View

Input controller patternsPage ControllerFront ControllerApplication Controller

Page 47: L13 Presentation Layer Design

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

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

48

Page 49: L13 Presentation Layer Design

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

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

Example

51

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

Example

Page 53: L13 Presentation Layer Design

Template▪ Velocity template example

Page 54: L13 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 55: L13 Presentation Layer Design

Template▪ Template Engine will execute the view and create HTML

Template  Engine HTMLView  Template  Language

reads generates

Model  Parameters

Page 56: L13 Presentation Layer Design

What  pattern  is  described  like  this?

A) Template  View B) Transform  View C) Model  View D) Two  Step  View

QUIZ

Page 57: L13 Presentation Layer Design

What  pattern  is  described  like  this?

A) Template  View B) Transform  View C) Model  View D) Two  Step  View

QUIZ

Page 58: L13 Presentation Layer Design

MVC Design

Page 59: L13 Presentation Layer Design

MVC Design

2. Call the model

Page 60: L13 Presentation Layer Design

MVC Design

60

Page 61: L13 Presentation Layer Design

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

Polymorphism

Page 62: L13 Presentation Layer Design

Domain and Presentation▪ Single Request

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

using setAttribute– JSP view can access the

data using the request

Page 63: L13 Presentation Layer Design

Combining Model and View

Input  Controller  HTTP/HTML  handling

Model  Domain  Layer

View  Template

Model  Parameters

Page 64: L13 Presentation Layer Design

API Design

Page 65: L13 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 66: L13 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 67: L13 Presentation Layer Design
Page 68: L13 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 69: L13 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– REST has become the preferred way

Page 70: L13 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 71: L13 Presentation Layer Design

REST Explained BrieflyGET to get resourcePOST to add resourcePUT to update resourceDELETE to delete resource

Page 72: L13 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 73: L13 Presentation Layer Design

Play Framework

Page 74: L13 Presentation Layer Design
Page 75: L13 Presentation Layer Design

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– Optimise developer productivity by using convention over

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

75

Page 76: L13 Presentation Layer Design

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

76

Page 77: L13 Presentation Layer Design

Play MVC

77

Page 78: L13 Presentation Layer Design

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

79

Page 80: L13 Presentation Layer Design

Creating a Play appUnzip typesafe-activator-1.2.10-minimal.zipOpen CMD or TerminalRun activator

This will download and install Play Framework$activaor

Add activator to PATH

80

Page 81: L13 Presentation Layer Design

Creating a Play appOpen CMD or Terminal >activator new RuFan

Creates a new appliction >cd RuFan >play run

Runs the Web AppOpen a browser and goto localhost:9000

81

Page 82: L13 Presentation Layer Design

82

Page 83: L13 Presentation Layer Design

83

Page 84: L13 Presentation Layer Design
Page 85: L13 Presentation Layer Design

85

Page 86: L13 Presentation Layer Design

Play in IntelliJ

86

Page 87: L13 Presentation Layer Design
Page 88: L13 Presentation Layer Design

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

index.html▪ View is a Scala template– views/index.scala.html

▪ Compiles in to class– views/html/index.class

89

@(message: String)

@main("Welcome to Play") {

@message

}

Page 90: L13 Presentation Layer Design

Routing▪ conf/routes contains the routing information

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

# Home page GET / controllers.Application.index()

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

Page 91: L13 Presentation Layer Design

Errors▪ Play displays errors– CMD has more information

91

Page 92: L13 Presentation Layer Design

Summary▪ Web Presentation Patterns– Model View Controller– Page Controller– Front Controller– Application Controller– Template View

▪ MVC Design▪ API Design▪ Play framework

92