Web Applications Internet Engineering Fall 2015 Bahador Bakhshi CE & IT Department, Amirkabir University of Technology
Jan 19, 2016
Web Applications
Internet Engineering
Fall 2015
Bahador Bakhshi
CE & IT Department, Amirkabir University of Technology
OutlineMVC Design PatternMultilayer DesignMultitier ArchitectureIntroduction to Java EEServletJSP
2
OutlineMVC Design PatternMultilayer DesignMultitier ArchitectureIntroduction to Java EEServletJSP
3
Web Application Development(Large) Applications cannot be developed in
ad-hoc manner We need design & architecture (SW engineering)
Concept separation, Component, Relations, …
There are so many architectural patterns ETL, MFT, EAI, TDS, …
http://en.wikipedia.org/wiki/Architectural_pattern Two common architectures in web applications
MVC Multi-layer (Multi-tier)
4
MVC: Model-View-Controller Model
Does all the computational work All communication with the model is via methods It contains data and performs computation on it
View (the user interface) Show the results from model or controller
Controller (of states sequences) Handles events/requests affecting model or view
User inputs/requests go to the controller Available commands are determined by controller (based on model) Tells the model what to do
Examples: Calculator, Email Client, Word Processor5
MVC Interactions (cont’d)
8
model
view controller
event event is passed to the controller
controller updates model
controller updates view
view queries model
model signals changes
MVC for (simple) Web ApplicationsModel
Database tables (persistent data) Session information (current stat data) Parts of processing
View (X)HTML CSS
Controller Client-side scripting Part of processing by server side scripting
9
MVC? MVC works fine for desktop application
The origin is from graphical application development 1970s
Consider large & distributed web application, e.g., online transactions, e-banking, … View Model interactions?!!
View is in user’s browser Model is in back-end server
User Controller interaction? User don’t have direct access to controller
Complicated processing on huge data Model cannot both hold data & process it
10
OutlineMVC Design PatternMultilayer DesignMultitier ArchitectureIntroduction to Java EEServletJSP
11
Layering ApproachMVC Difficulties are due to triangular topology
Linearize the topology Layering approach
Common layering in web applications Presentation Layer Business logic Layer Data (management/resource) Layer
These layers are purely abstractions Not correspond to physical distribution
All layers may or may not be on the same machine
12
Multilayer Architecture
13
Presentation Layer User interface of the application
GUI HTML based browser
Displays information (processing output) which are get from the business logic layer
Gets user’s requests and pass them (with required data) to the business logic layer
Note that the user interface of web applications can be made up client side & server side codes
What is this layer in Gmail?
14
Business Logic LayerThe work that the application needs to do
Processing/Computing/Calculations
Receives requests from presentation layerFetches required data from data layerProcess the request & dataOutput is sent back to the presentation layerWhat does this layer do in Gmail?
15
Data LayerProvides data access interface to business logic
Hide data storage details Hide heterogeneity of underlining systems
Communicating with data store systems Database server Messaging system …
What is this layer in Gmail?
16
OutlineMVC Design PatternMultilayer DesignMultitier ArchitectureIntroduction to Java EEServletJSP
17
Multilayer(logical) Multi-tier (physical)
Should/Can all layers be implemented in a single physical machine (single tier)?
Yes, If application is (fairly) simple Web server, HTML, CSS, PHP, Processing, MySQL,
… all on the same machine
No, If application is huge & complex Web server on machine 1 Data base on machine 2
18
Multitier ArchitectureTwo-tier Architecture:
Two layers are physically separated from the third, forming two physically separated tiers
Three-tier Architecture: The three abstract logical layers are separated into
three physically distributed tiers
N-tire Architecture: Each abstract logical layer is implemented using
multiple physical tiers
19
Two-Tier 1: Fat clientCombining the presentation layer with the
business logic layer in a physical tierThis separation can be seen as the traditional
client-server architecture Client = Process + View Server = Data
This architecture effectively makes the client “fat” and the server “thin”
20
Two-Tier Fat Client Characteristics Deployment costs are high
Many fat clients
Business logic migration or data base modification (changes in database driver, database type, …) costs are high Changing the business logic layer involves
recompiling and redeploying the client tier
Network performance suffers Huge raw data transfer (query & response)
21
Two-Tier 2: Thin ClientClient tier
Presentation layer, e.g., web browser HTTP request Serving mainly HTML pages
Server tier Parts of Presentation + Business + Data E.g. web server & DB server
HTTP response Server side programming: CGI & PHP + MySql
How about complex computing on huge data?!
22
N-Tier Architecture In N-tier deployments, presentation layer, business
logic layer, and data layer are separated into respective physical tiers 3 tier: client + server + data base
Presentation layer is implemented by parts in both client & server sides E.g., dynamic web page using Ajax + PHP 4 tier: Browser + Web server + Application Server + Database
server
Complicated Bussing logic layer itself can be distributed multi-tier application N-tier
23
HTML Client (browser)
Web Server
Application Server
Database Server
Typical Web Application N-tier Architecture
N-Tier Architecture Characteristics Migration costs are low
Each tier can be upgraded independently, e.g. Business logic application migration Database switching Web server switch OS upgrade
Inter-Tier communication performance overhead
Server side maintenance costs are high
25
Multilayer/Multitier ImplementationMany common requirements in business logic
Object creation & garbage collection, Transaction Logging and audit, Security, and much more
These are not implemented by neither OS nor Application developer They are called middleware
Application servers provide middleware services Application components live inside application servers
26
Application ServersExisting technologies can be classified into
three broad categories:Java based platform (Java Enterprise Edition) .NET FrameworkOther web application development
frameworks PHP frameworks: Zend, … Ruby on Rail …
27
OutlineMVC Design PatternMultilayer DesignMultitier ArchitectureIntroduction to Java EEServletJSP
28
What is Java EE?Java Platforms:
Java Card: Smart card version Java ME (Micro Edition): Embedded systems, e.g.
Mobile handheld Java SE (Standard Edition): Desktop application
development Java EE (Enterprise Edition): Enterprise distributed
application software development Java EE adds libraries to SE for fault-tolerant,
distributed, multi-tier, … based components Until java 5, it has been called J2EE
29
Java EEJava EE provides technologies (libraries) for
enterprise level web applicationsJava EE technologies for web applications:
Servlet JavaServer Pages (JSP) JavaServer Faces (JSF) Enterprise Java Beans (EJB)
Many other facilities (via libraries & JVM) Remote method invocation, Security, Database
connectors, XML, …30
Java EE Components: Business LogicEJB: Enterprise version of Java Beans
Java classes that are designed to be reusable standalone software components All data (properties) are private
Exposed by public getter & setter method Public method to process the data
Enterprise version: automated (provided by container) concurrency, life-time management, security, transaction, … Simplify developing complex application
Can be used everywhere, not necessarily web application
31
Java EE Components: PresentationClient side
Client can use HTML, Java Applet, Java Application, …Server side
Servlets are special classes to realize request-response model (get, post,… of HTTP) External server side code
JSP is a developer-friendly wrapper over servlet classes Embed server side code
Faces & Facelets similar to JSP but uses custom tags which can be converted to anything
32
Java EE Multi-tier Architecture
33
Java EE Containers Requirements from different aspects
All java codes must run a virtual machine To run Servlet & JSP we need something like PHP runtime
environment Application server (middleware) is need in business logic
These different terms are named container in Java EE terminology The runtime support for Java EE application components Provides a view of the underlying Java EE API
Security, Logging, Remote Method Invocation, …
34
Java EE Container Architecture
35
Web ContainerApplet Container
Application ClientContainer
EJB Container
Java Servlets
JSP
Databases and
Other Resources
EJBs
App.Client
Applet
JSF
Browser
JRE
Tomcat, JRun, … GlassFish, BEA, …
OutlineMVC Design PatternMultilayer DesignMultitier ArchitectureIntroduction to Java EEServletJSP
36
What is Servlet?! A Java application that runs on the web server in
response to HTTP requests (GET, …) A normal java application +
Read/Write access to HTTP headers Access to HTML Forms Sessions, Cookies, …
Similar to CGI, output is sent to client Servlet is used to generate dynamic content to return to
browser: HTML, XML, …
Each servlet runs as separated thread inside servlet container
37
The Servlet Model
Browser
Java Enabled
Web Server
Servlet container
HTTP Get/Post
HTMLXML
ResourcesJavaBeansDatabase
38
Servlet
Servlet
Why Servlet: Servlets vs. CGI Scripts Servlets do what CGI scripts do (use java instead of
other programming languages); so, why should I learn/use it? Because, it is better approach
More efficient No new process per request (as CGI), with servlets, servlet is
loaded at first time, container stays running and handles each request with a lightweight Java thread
More Convenient Servlets have an extensive infrastructure for automatically
parsing and decoding HTML form data, reading and setting HTTP headers, handling cookies, tracking sessions, …
39
Why Servlet: Servlets vs. CGI Scripts More Portable
Servlets are written in the Java programming language and follow a standard API. Servlets are supported directly or by a plugin on virtually every major web server
More Secure CGI programs are often executed by general-purpose operating
system shells, however, servlets run in container which impose more security enforcement (sand boxing)
More powerful It is java & its container provide mechanisms to use other java
application, e.g. EJB multi-layer architecture
40
Why Servlet: Its Role in Java EE
41
How does Servlet Work? There is a mapping between URL & Servlet classes, e.g.
/1/2/3 abc.class The “web.xml” file (we see later)
When there is a request for URL (/1/2/3/), container calls service method of the class (abc.class) Multiple concurrent requests Multiple threads running the service method
The service method calls do??? method according to the type of requests E.g., doGet for GET method
42
Assumption: servlet is already loaded in RAM
How does Servlet Work? (cont’d) The method accesses to the request information
HTTP headers, form data, cookies, sessions, … Through objects which are passed to the method by
container
The method processes the request Normal java application, DB access, using EJB, …
The method generates output Setting response headers, setting cookies, updating session,
printing HTML to output stream, … Using the objects which are provided by container
43
The “Hello World” Exampleimport java.io.*;import javax.servlet.*;import javax.servlet.http.*;
public class HelloWorld extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException{ response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<body>"); out.println("<h1>Hello World!</h1>"); out.println("</body>"); out.println("</html>"); }}
44
Check it on Real Webserver
OutlineMVC Design PatternMultilayer DesignMultitier ArchitectureIntroduction to Java EEServletJSP
45
JavaServer Pages (JSP)JSP technology is an extension of servlet
Simplify web application development by java We have not to create whole HTML by println
JSPs are easier to develop than servlets
It is the embed version of servlet in HTML Contains static HTML elements + JSP tags in .jsp file
Java code inside the tags creates dynamic content Very similar to PHP, but using Java codes
When JSP runs, a servlet is created It runs on the same container that runs Servlets
46
JSP Invocation
47
JSP Advantages In comparison to Servlet
Only dynamic part are java coded, not whole HTML Separation between HTML (Presentation) & Bussing logic
Develop java code & include them in HTML by JSP tags Automatic recompilation of modified pages As powerful as servlet (it becomes servlet finally!)
In comparison to interpreted scripts (PHP) JSP is compiled & kept in memory Better performance Converted to Servlet (a complete Java program) More complex
logic implementation
48
What is New in JSP? JSP = HTML + tag + Java Servlet We already know HTML + Java + Servlet
So, what do we want to learn about JSP?
Tags!!! Okay, we know it <% %> (or something like that)
JSP is finished! There is nothing to learn ( or ? )
But, wait!! A servlet is composed of some sections imports, variable & method declaration, doGet, … How do we specify which tag in JSP is which part of the servlet class?!
Yes! Tags!!! Different tags for different purposes
We want to learn! ( :P)
49
JSP Tag Examples JSP Comment: <%-- Blah --%>
Developer comment that is not sent to the client
JSP Expression: <%= Java Value %> Expression that is evaluated and sent to the client each time the
page is requested
JSP Scriptlet: <% code %> The code is inserted into the servlet's _jspService
JSP Declaration: <%! Field %> <%! Method %> Field or method that becomes part of class definition when page
is translated into a servlet
50
The Hello World Example<HTML><BODY>Hello World! The time is now <%= new java.util.Date() %></BODY></HTML>
Is converted to out.print("<HTML> <BODY> Hello World! The time is now ");out.print(new java.util.Date());out.print("</BODY> </HTML>");
51
Summary Q8) How are complex/big web applications developed?
We need architectures & design patterns to help us
Q8.1) Design patterns & Architecture? MVC & Multi-layer are common approaches
Q8.2) Deployment architecture? Multi-layer is typically deployed in multi-tier architecture
Q8.3) What does Java EE provide? Servlet & JSP & Some other things (we didn’t see)
Q8.4) Servlet? A java class that run to handle HTTP requests
Q8.5) JSP? Embed version of the Servlet with specially tags for different purposes
52
ReferencesThe “Core Servlet” Bookwww.j2eetutorials.50webs.com
53