SlideShare a Scribd company logo
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.pptx
AbhijayKulshrestha1
 
Multi Client Development with Spring
Multi Client Development with SpringMulti Client Development with Spring
Multi Client Development with Spring
Joshua 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 MVC
PawanMM
 
Java Web Programming [6/9] : MVC
Java Web Programming [6/9] : MVCJava Web Programming [6/9] : MVC
Java Web Programming [6/9] : MVC
IMC Institute
 
IP UNIT III PPT.pptx
 IP UNIT III PPT.pptx IP UNIT III PPT.pptx
IP UNIT III PPT.pptx
ssuser92282c
 
Spring - Part 4 - Spring MVC
Spring - Part 4 - Spring MVCSpring - Part 4 - Spring MVC
Spring - Part 4 - Spring MVC
Hitesh-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 MVC
Brad 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 HTML5
Tuna Tore
 
springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892Tuna Tore
 
Jsp
JspJsp
Spring mvc
Spring mvcSpring mvc
Spring mvc
Hui Xie
 
Jsf2 overview
Jsf2 overviewJsf2 overview
Jsf2 overview
sohan1234
 
Next stop: Spring 4
Next stop: Spring 4Next stop: Spring 4
Next stop: Spring 4
Oleg Tsal-Tsalko
 
Server side programming bt0083
Server side programming bt0083Server side programming bt0083
Server side programming bt0083
Divyam Pateriya
 
JAVA SERVER PAGES
JAVA SERVER PAGESJAVA SERVER PAGES
JAVA SERVER PAGES
Kalpana T
 
Spring mvc
Spring mvcSpring mvc
Spring mvc
Pravin Pundge
 
Soa development using javascript
Soa development using javascriptSoa development using javascript
Soa development using javascriptDsixE Inc
 
18CSC311J Web Design and Development UNIT-3
18CSC311J Web Design and Development UNIT-318CSC311J Web Design and Development UNIT-3
18CSC311J Web Design and Development UNIT-3
sivakumarmcs
 

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
 
18CSC311J Web Design and Development UNIT-3
18CSC311J Web Design and Development UNIT-318CSC311J Web Design and Development UNIT-3
18CSC311J Web Design and Development UNIT-3
 

Recently uploaded

Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Product School
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
RTTS
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Jeffrey Haguewood
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Inflectra
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
Paul Groth
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
DianaGray10
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 

Recently uploaded (20)

Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 

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);