SlideShare a Scribd company logo
1 of 30
Download to read offline
Integrating Servlets and JSP:
The Model View Controller
(MVC) Architecture
• Understanding the benefits of MVC
• Using RequestDispatcher to implement MVC
• Forwarding requests from servlets to JSP pages
• Handling relative URLs
• Choosing among different display options
• Comparing data-sharing strategies
Agenda
Modèle MVC 2
MVC Motivation
Modèle MVC 3
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 ("maladroit")
– 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
Modèle MVC 4
Modèle MVC 5
Possibilities for Handling a Single Request
• Servlet only. Works well when:
– Output is a binary type. E.g.: an image
– There is 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. Works well when:
– Output is mostly character data. E.g.: HTML
– Format/layout mostly fixed.
• Combination (MVC architecture). Needed when:
– A single request will result in multiple substantially different looking results.
– You have a large development team with different team members doing the Web
development and the business logic.
– You perform complicated data processing, but have a relatively fixed layout.
Modèle MVC 6
MVC Misconceptions
❑ An elaborate framework is necessary
➢ Frameworks are often useful
❖ JSF (JavaServer Faces)
✓ You should strongly consider JSF 2.0 for medium/large projects!
❖ Struts
➢ They are not required!
❖ Implementing MVC with the builtin RequestDispatcher works very
well for most simple and even moderately complex applications
❑ MVC totally changes your system design
➢ You can use MVC for individual requests
➢ Think of it as the MVC approach, not the MVC architecture
❖ Also called the Model 2 approach
Modèle MVC 7
• Servlets and JSP
– Well-established standard
– Used by google.com, ebay.com, walmart.com, and thousands of other
popular sites
– Relatively low level by today’s standards
• JSF (JavaServer Faces) Version 2
– Now an official part of Java EE 6
• But runs in any recent Java-enabled server, including Tomcat 6+
– Higher-level features: integrated Ajax support, field validation, page
templating, rich third-party component libraries, etc. Designed around
the MVC approach.
– Not yet as widely used, but recommended for many or most new
projects
MVC-Based Alternative to Servlets and JSP: JSF 2
Modèle MVC 8
Basic MVC Design
Modèle MVC 9
Modèle MVC 10
Modèle MVC 11
Modèle MVC 12
Modèle MVC 13
Modèle MVC 14
MVC Flow of Control
HTML or JSP
Form Servlet
Java Code
Business Logic
Arguments
based on
Form data
Results
(beans)
Submit Form
Form action matches
URL of servlet
JSP1
JSP2
JSP3
(Extract data from beans
and put in output)
(Store beans in request,
session, or application
scope)
Modèle MVC 15
MVC Flow of Control
(Annotated : example for a banking application)
HTML or JSP
Form Servlet
Java Code
Business Logic
Arguments
based on
Form data
Results
(beans)
Submit Form
Form action matches
URL of servlet
JSP1
JSP2
JSP3
(Extract data from beans
and put in output)
(Store beans in request,
session, or application
scope)
Send customer ID
Pass
customer
ID to
lookup
service
Customer currentCustomer =
lookupService.findCustomer(customerId);
Get back current Customer
that has the ID
${customer.firstName}
${customer.balance}
Modèle MVC 16
Implementing MVC with RequestDispatcher
1. Define beans to represent result data
– Ordinary Java classes with at least one getBlah method
2. Use a servlet to handle requests
– Servlet reads request parameters, checks for missing and malformed data, calls business
logic, etc.
3. Obtain bean instances
– The servlet invokes business logic (application-specific code) or data-access code to obtain
the results.
4. Store the bean in the request, session, or servlet context
– The servlet calls setAttribute on the request, session, or servlet context objects to store a
reference to the beans that represent the results of the request.
Modèle MVC 17
Implementing MVC with RequestDispatcher (Continued)
5. Forward the request to a JSP page.
– The servlet determines which JSP page is appropriate to the situation and uses
the forward method of RequestDispatcher to transfer control to that page.
6. Extract the data from the beans.
– JSP 1.2 (Old!)
• The JSP page accesses beans with jsp:useBean and a scope matching the location of step 4. The
page then uses jsp:getProperty to output the bean properties.
– JSP 2.0 (Preferred!)
• The JSP page uses ${nameFromServlet.property} to output bean properties
– Either way, JSP page does not create or modify bean; it merely extracts and
displays data that servlet created.
Modèle MVC 18
Request Forwarding Example
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
... // Do business logic and get data
String operation = request.getParameter("operation");
if (operation == null) {
operation = "unknown";
}
String address;
if (operation.equals("order")) {
address = "/WEB-INF/Order.jsp";
} else if (operation.equals("cancel")) {
address = "/WEB-INF/Cancel.jsp";
} else {
address = "/WEB-INF/UnknownOperation.jsp";
}
RequestDispatcher dispatcher = request.getRequestDispatcher(address);
dispatcher.forward(request, response);
20 }
Modèle MVC 19
jsp:useBean in MVC vs. in Standalone JSP Pages
• The JSP page should not create the objects
– The servlet, not the JSP page, should create all the data objects. So, to guarantee
that the JSP page will not create objects, you should use
<jsp:useBean ... type="package.Class" />
instead of
<jsp:useBean ... class="package.Class" />
• The JSP page should not modify the objects
– So, you should use jsp:getProperty but not jsp:setProperty.
Modèle MVC 20
Scopes:
request, session, and
application (ServletContext)
Modèle MVC 21
Scopes
• Idea
– A “scope” is a place that the bean is stored. This place controls where and for how
long the bean is visible.
• Three choices
– Request
• Data stored in the request is visible to the servlet and to the page the servlet forwards to. Data
cannot be seen by other users or on other pages. Most common scope.
– Session
• Data stored in the session is visible to the servlet and to the page the servlet forwards to. Data can
be seen on other pages or later in time if it is the same user. Data cannot be seen by other users.
Moderately common.
– Application (Servlet Context)
• Data stored in the servlet context is visible to all users and all pages in the application. Rarely used.
Modèle MVC 22
Request-Based Data Sharing
• Servlet
SomeBean value = LookupService.findResult(...);
request.setAttribute("key", value);
RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-
INF/SomePage.jsp");
dispatcher.forward(request, response);
• JSP 2.0
${key.someProperty}
• JSP 1.2 (Old!)
<jsp:useBean id="key" type="somePackage.SomeBean" scope="request" />
<jsp:getProperty name="key" property="someProperty" />
Name chosen by the servlet.
Name of accessor method, minus the
word “get”, with next letter changed
to lower case.
Modèle MVC 23
Request-Based Data Sharing: Simplified Example
• Servlet
Customer myCustomer = Lookup.findCust(request.getParameter("customerID"));
request.setAttribute("customer", myCustomer);
RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/SomePage.jsp");
dispatcher.forward(request, response);
• JSP 2.0
${customer.firstName}
• JSP 1.2
<jsp:useBean id="customer" type="somePackage.Customer" scope="request" />
<jsp:getProperty name="customer" property="firstName"/>
Assume that the findCust method
handles missing/malformed data.
Note: the Customer class must
have a method called “getFirstName”.
Modèle MVC 24
Session-Based Data Sharing
• Servlet
SomeBean value = LookupService.findResult(...);
HttpSession session = request.getSession();
session.setAttribute("key", value);
RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/SomePage.jsp");
dispatcher.forward(request, response);
• JSP 2.0
${key.someProperty}
• JSP 1.2
<jsp:useBean id="key" type="somePackage.SomeBean" scope="session" />
<jsp:getProperty name="key" property="someProperty" />
Modèle MVC 25
Session-Based Data Sharing: Variation
• Redirect to page instead of forwarding to it
– Use response.sendRedirect instead of RequestDispatcher.forward
• Distinctions: with sendRedirect:
– User sees JSP URL (user sees only servlet URL with RequestDispatcher.forward)
– Two round trips to client (only one with forward)
• Advantage of sendRedirect
– User can visit JSP page separately
• User can bookmark JSP page
• Disadvantages of sendRedirect
– Two round trips to server is more expensive
– Since user can visit JSP page without going through servlet first, bean data might not
be available
• So, JSP page needs code to detect this situation
Modèle MVC 26
ServletContext-Based Data Sharing (Rare)
• Servlet
synchronized(this) {
SomeBean value = SomeLookup.findResult(...);
getServletContext().setAttribute("key", value);
RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/SomePage.jsp");
dispatcher.forward(request, response);
}
• JSP 2.0
${key.someProperty}
• JSP 1.2
<jsp:useBean id="key" type="somePackage.SomeBean" scope="application" />
<jsp:getProperty name="key" property="someProperty" />
28
Modèle MVC 27
Relative URLs in JSP Pages
• Issue:
– Forwarding with a request dispatcher is transparent to the client. Original URL (i.e.,
the form action URL) is only URL browser knows about.
• Why does this matter?
– What will browser do with tags like the following?
<img src="foo.gif" …/>
<link rel="stylesheet" href="my-styles.css" type="text/css">
<a href="bar.jsp">…</a>
– Browser treats addresses as relative to servlet URL
Modèle MVC 28
Exemple:
Consultation de soldes bancaires
Modèle MVC 29
Application de l'approche MVC:
Soldes de comptes bancaires
• Bean
– BankCustomer
• Business Logic
– BankCustomerLookup
• Servlet that populates bean and forwards to appropriate JSP page
– Reads customer ID, calls BankCustomerLookup’s data-access code to obtain BankCustomer
– Uses current balance to decide on appropriate result page
• JSP pages to display results
– Negative balance: warning page
– Regular balance: standard page
– High balance: page with advertisements added
– Unknown customer ID: error page
Modèle MVC 30
Bank Account Balances: Servlet Code
@WebServlet("/show-balance")
public class ShowBalance extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String customerId = request.getParameter("customerId");
CustomerLookupService service = new CustomerSimpleMap();
Customer customer = service.findCustomer(customerId);
request.setAttribute("customer", customer);
String address;
if (customer == null) {
request.setAttribute("badId", customerId);
address = "/results/unknown-customer.jsp";
} else if (customer.getBalance() < 0) {
address = "/results/negative-balance.jsp";
} … /* normal-balance and high-balance cases*/ …}
RequestDispatcher dispatcher =
request.getRequestDispatcher(address);
32 dispatcher.forward(request, response);

More Related Content

Similar to My04_MVC.pdf

Unit 38 - Spring MVC Introduction.pptx
Unit 38 - Spring MVC Introduction.pptxUnit 38 - Spring MVC Introduction.pptx
Unit 38 - Spring MVC Introduction.pptxAbhijayKulshrestha1
 
Multi Client Development with Spring
Multi Client Development with SpringMulti Client Development with Spring
Multi Client Development with SpringJoshua Long
 
Session 46 - Spring - Part 4 - Spring MVC
Session 46 - Spring - Part 4 - Spring MVCSession 46 - Spring - Part 4 - Spring MVC
Session 46 - Spring - Part 4 - Spring MVCPawanMM
 
Java Web Programming [6/9] : MVC
Java Web Programming [6/9] : MVCJava Web Programming [6/9] : MVC
Java Web Programming [6/9] : MVCIMC Institute
 
IP UNIT III PPT.pptx
 IP UNIT III PPT.pptx IP UNIT III PPT.pptx
IP UNIT III PPT.pptxssuser92282c
 
Spring - Part 4 - Spring MVC
Spring - Part 4 - Spring MVCSpring - Part 4 - Spring MVC
Spring - Part 4 - Spring MVCHitesh-Java
 
Struts 2-overview2
Struts 2-overview2Struts 2-overview2
Struts 2-overview2divzi1913
 
What is ASP.NET MVC
What is ASP.NET MVCWhat is ASP.NET MVC
What is ASP.NET MVCBrad Oyler
 
Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5Tuna Tore
 
springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892Tuna Tore
 
Spring mvc
Spring mvcSpring mvc
Spring mvcHui Xie
 
Jsf2 overview
Jsf2 overviewJsf2 overview
Jsf2 overviewsohan1234
 
Server side programming bt0083
Server side programming bt0083Server side programming bt0083
Server side programming bt0083Divyam Pateriya
 
JAVA SERVER PAGES
JAVA SERVER PAGESJAVA SERVER PAGES
JAVA SERVER PAGESKalpana T
 
Soa development using javascript
Soa development using javascriptSoa development using javascript
Soa development using javascriptDsixE Inc
 
Bt0083, server side programming theory
Bt0083, server side programming theoryBt0083, server side programming theory
Bt0083, server side programming theorysmumbahelp
 

Similar to My04_MVC.pdf (20)

Unit 38 - Spring MVC Introduction.pptx
Unit 38 - Spring MVC Introduction.pptxUnit 38 - Spring MVC Introduction.pptx
Unit 38 - Spring MVC Introduction.pptx
 
Multi Client Development with Spring
Multi Client Development with SpringMulti Client Development with Spring
Multi Client Development with Spring
 
Session 46 - Spring - Part 4 - Spring MVC
Session 46 - Spring - Part 4 - Spring MVCSession 46 - Spring - Part 4 - Spring MVC
Session 46 - Spring - Part 4 - Spring MVC
 
Java Web Programming [6/9] : MVC
Java Web Programming [6/9] : MVCJava Web Programming [6/9] : MVC
Java Web Programming [6/9] : MVC
 
IP UNIT III PPT.pptx
 IP UNIT III PPT.pptx IP UNIT III PPT.pptx
IP UNIT III PPT.pptx
 
Spring - Part 4 - Spring MVC
Spring - Part 4 - Spring MVCSpring - Part 4 - Spring MVC
Spring - Part 4 - Spring MVC
 
Struts 2-overview2
Struts 2-overview2Struts 2-overview2
Struts 2-overview2
 
What is ASP.NET MVC
What is ASP.NET MVCWhat is ASP.NET MVC
What is ASP.NET MVC
 
Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5
 
springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892
 
Jsp
JspJsp
Jsp
 
Spring mvc
Spring mvcSpring mvc
Spring mvc
 
Jsf2 overview
Jsf2 overviewJsf2 overview
Jsf2 overview
 
Next stop: Spring 4
Next stop: Spring 4Next stop: Spring 4
Next stop: Spring 4
 
Server side programming bt0083
Server side programming bt0083Server side programming bt0083
Server side programming bt0083
 
JAVA SERVER PAGES
JAVA SERVER PAGESJAVA SERVER PAGES
JAVA SERVER PAGES
 
Spring mvc
Spring mvcSpring mvc
Spring mvc
 
20jsp
20jsp20jsp
20jsp
 
Soa development using javascript
Soa development using javascriptSoa development using javascript
Soa development using javascript
 
Bt0083, server side programming theory
Bt0083, server side programming theoryBt0083, server side programming theory
Bt0083, server side programming theory
 

Recently uploaded

Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Science&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfScience&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfjimielynbastida
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Neo4j
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDGMarianaLemus7
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
Bluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfBluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfngoud9212
 
Unlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsUnlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsPrecisely
 

Recently uploaded (20)

Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Science&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfScience&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdf
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDG
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
Bluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfBluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdf
 
Unlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsUnlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power Systems
 

My04_MVC.pdf

  • 1. Integrating Servlets and JSP: The Model View Controller (MVC) Architecture
  • 2. • Understanding the benefits of MVC • Using RequestDispatcher to implement MVC • Forwarding requests from servlets to JSP pages • Handling relative URLs • Choosing among different display options • Comparing data-sharing strategies Agenda Modèle MVC 2
  • 4. 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 ("maladroit") – 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 Modèle MVC 4
  • 5. Modèle MVC 5 Possibilities for Handling a Single Request • Servlet only. Works well when: – Output is a binary type. E.g.: an image – There is 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. Works well when: – Output is mostly character data. E.g.: HTML – Format/layout mostly fixed. • Combination (MVC architecture). Needed when: – A single request will result in multiple substantially different looking results. – You have a large development team with different team members doing the Web development and the business logic. – You perform complicated data processing, but have a relatively fixed layout.
  • 6. Modèle MVC 6 MVC Misconceptions ❑ An elaborate framework is necessary ➢ Frameworks are often useful ❖ JSF (JavaServer Faces) ✓ You should strongly consider JSF 2.0 for medium/large projects! ❖ Struts ➢ They are not required! ❖ Implementing MVC with the builtin RequestDispatcher works very well for most simple and even moderately complex applications ❑ MVC totally changes your system design ➢ You can use MVC for individual requests ➢ Think of it as the MVC approach, not the MVC architecture ❖ Also called the Model 2 approach
  • 7. Modèle MVC 7 • Servlets and JSP – Well-established standard – Used by google.com, ebay.com, walmart.com, and thousands of other popular sites – Relatively low level by today’s standards • JSF (JavaServer Faces) Version 2 – Now an official part of Java EE 6 • But runs in any recent Java-enabled server, including Tomcat 6+ – Higher-level features: integrated Ajax support, field validation, page templating, rich third-party component libraries, etc. Designed around the MVC approach. – Not yet as widely used, but recommended for many or most new projects MVC-Based Alternative to Servlets and JSP: JSF 2
  • 8. Modèle MVC 8 Basic MVC Design
  • 14. Modèle MVC 14 MVC Flow of Control HTML or JSP Form Servlet Java Code Business Logic Arguments based on Form data Results (beans) Submit Form Form action matches URL of servlet JSP1 JSP2 JSP3 (Extract data from beans and put in output) (Store beans in request, session, or application scope)
  • 15. Modèle MVC 15 MVC Flow of Control (Annotated : example for a banking application) HTML or JSP Form Servlet Java Code Business Logic Arguments based on Form data Results (beans) Submit Form Form action matches URL of servlet JSP1 JSP2 JSP3 (Extract data from beans and put in output) (Store beans in request, session, or application scope) Send customer ID Pass customer ID to lookup service Customer currentCustomer = lookupService.findCustomer(customerId); Get back current Customer that has the ID ${customer.firstName} ${customer.balance}
  • 16. Modèle MVC 16 Implementing MVC with RequestDispatcher 1. Define beans to represent result data – Ordinary Java classes with at least one getBlah method 2. Use a servlet to handle requests – Servlet reads request parameters, checks for missing and malformed data, calls business logic, etc. 3. Obtain bean instances – The servlet invokes business logic (application-specific code) or data-access code to obtain the results. 4. Store the bean in the request, session, or servlet context – The servlet calls setAttribute on the request, session, or servlet context objects to store a reference to the beans that represent the results of the request.
  • 17. Modèle MVC 17 Implementing MVC with RequestDispatcher (Continued) 5. Forward the request to a JSP page. – The servlet determines which JSP page is appropriate to the situation and uses the forward method of RequestDispatcher to transfer control to that page. 6. Extract the data from the beans. – JSP 1.2 (Old!) • The JSP page accesses beans with jsp:useBean and a scope matching the location of step 4. The page then uses jsp:getProperty to output the bean properties. – JSP 2.0 (Preferred!) • The JSP page uses ${nameFromServlet.property} to output bean properties – Either way, JSP page does not create or modify bean; it merely extracts and displays data that servlet created.
  • 18. Modèle MVC 18 Request Forwarding Example public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ... // Do business logic and get data String operation = request.getParameter("operation"); if (operation == null) { operation = "unknown"; } String address; if (operation.equals("order")) { address = "/WEB-INF/Order.jsp"; } else if (operation.equals("cancel")) { address = "/WEB-INF/Cancel.jsp"; } else { address = "/WEB-INF/UnknownOperation.jsp"; } RequestDispatcher dispatcher = request.getRequestDispatcher(address); dispatcher.forward(request, response); 20 }
  • 19. Modèle MVC 19 jsp:useBean in MVC vs. in Standalone JSP Pages • The JSP page should not create the objects – The servlet, not the JSP page, should create all the data objects. So, to guarantee that the JSP page will not create objects, you should use <jsp:useBean ... type="package.Class" /> instead of <jsp:useBean ... class="package.Class" /> • The JSP page should not modify the objects – So, you should use jsp:getProperty but not jsp:setProperty.
  • 20. Modèle MVC 20 Scopes: request, session, and application (ServletContext)
  • 21. Modèle MVC 21 Scopes • Idea – A “scope” is a place that the bean is stored. This place controls where and for how long the bean is visible. • Three choices – Request • Data stored in the request is visible to the servlet and to the page the servlet forwards to. Data cannot be seen by other users or on other pages. Most common scope. – Session • Data stored in the session is visible to the servlet and to the page the servlet forwards to. Data can be seen on other pages or later in time if it is the same user. Data cannot be seen by other users. Moderately common. – Application (Servlet Context) • Data stored in the servlet context is visible to all users and all pages in the application. Rarely used.
  • 22. Modèle MVC 22 Request-Based Data Sharing • Servlet SomeBean value = LookupService.findResult(...); request.setAttribute("key", value); RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB- INF/SomePage.jsp"); dispatcher.forward(request, response); • JSP 2.0 ${key.someProperty} • JSP 1.2 (Old!) <jsp:useBean id="key" type="somePackage.SomeBean" scope="request" /> <jsp:getProperty name="key" property="someProperty" /> Name chosen by the servlet. Name of accessor method, minus the word “get”, with next letter changed to lower case.
  • 23. Modèle MVC 23 Request-Based Data Sharing: Simplified Example • Servlet Customer myCustomer = Lookup.findCust(request.getParameter("customerID")); request.setAttribute("customer", myCustomer); RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/SomePage.jsp"); dispatcher.forward(request, response); • JSP 2.0 ${customer.firstName} • JSP 1.2 <jsp:useBean id="customer" type="somePackage.Customer" scope="request" /> <jsp:getProperty name="customer" property="firstName"/> Assume that the findCust method handles missing/malformed data. Note: the Customer class must have a method called “getFirstName”.
  • 24. Modèle MVC 24 Session-Based Data Sharing • Servlet SomeBean value = LookupService.findResult(...); HttpSession session = request.getSession(); session.setAttribute("key", value); RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/SomePage.jsp"); dispatcher.forward(request, response); • JSP 2.0 ${key.someProperty} • JSP 1.2 <jsp:useBean id="key" type="somePackage.SomeBean" scope="session" /> <jsp:getProperty name="key" property="someProperty" />
  • 25. Modèle MVC 25 Session-Based Data Sharing: Variation • Redirect to page instead of forwarding to it – Use response.sendRedirect instead of RequestDispatcher.forward • Distinctions: with sendRedirect: – User sees JSP URL (user sees only servlet URL with RequestDispatcher.forward) – Two round trips to client (only one with forward) • Advantage of sendRedirect – User can visit JSP page separately • User can bookmark JSP page • Disadvantages of sendRedirect – Two round trips to server is more expensive – Since user can visit JSP page without going through servlet first, bean data might not be available • So, JSP page needs code to detect this situation
  • 26. Modèle MVC 26 ServletContext-Based Data Sharing (Rare) • Servlet synchronized(this) { SomeBean value = SomeLookup.findResult(...); getServletContext().setAttribute("key", value); RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/SomePage.jsp"); dispatcher.forward(request, response); } • JSP 2.0 ${key.someProperty} • JSP 1.2 <jsp:useBean id="key" type="somePackage.SomeBean" scope="application" /> <jsp:getProperty name="key" property="someProperty" /> 28
  • 27. Modèle MVC 27 Relative URLs in JSP Pages • Issue: – Forwarding with a request dispatcher is transparent to the client. Original URL (i.e., the form action URL) is only URL browser knows about. • Why does this matter? – What will browser do with tags like the following? <img src="foo.gif" …/> <link rel="stylesheet" href="my-styles.css" type="text/css"> <a href="bar.jsp">…</a> – Browser treats addresses as relative to servlet URL
  • 29. Modèle MVC 29 Application de l'approche MVC: Soldes de comptes bancaires • Bean – BankCustomer • Business Logic – BankCustomerLookup • Servlet that populates bean and forwards to appropriate JSP page – Reads customer ID, calls BankCustomerLookup’s data-access code to obtain BankCustomer – Uses current balance to decide on appropriate result page • JSP pages to display results – Negative balance: warning page – Regular balance: standard page – High balance: page with advertisements added – Unknown customer ID: error page
  • 30. Modèle MVC 30 Bank Account Balances: Servlet Code @WebServlet("/show-balance") public class ShowBalance extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String customerId = request.getParameter("customerId"); CustomerLookupService service = new CustomerSimpleMap(); Customer customer = service.findCustomer(customerId); request.setAttribute("customer", customer); String address; if (customer == null) { request.setAttribute("badId", customerId); address = "/results/unknown-customer.jsp"; } else if (customer.getBalance() < 0) { address = "/results/negative-balance.jsp"; } … /* normal-balance and high-balance cases*/ …} RequestDispatcher dispatcher = request.getRequestDispatcher(address); 32 dispatcher.forward(request, response);