SlideShare a Scribd company logo
1
Engineering the Java Web
Application (MVC)
SE 432
Software Engineering for Web
Applications
2
Introduction
• What we have studied so far is the following:
– A request is made to a JSP or a Servlet and then that
JSP or Servlet handles all responsibilities for the
request, including
• processing the request,
• validating data,
• handling the business logic,
• and generating a response
• This is known as Model 1 Architecture
3
Model 1 Architecture
• Commonly used in small, simple task
applications due to its ease of development
4
• Client directly calls a JSP page
• The JSP page accesses the JavaBeans (the application model)
• The next view to be displayed is determined either:
– by hyperlinks selected in the source document or
– by request parameters
• Control is decentralized, which is bad, Why?
– because the current page being displayed determines the next page to
display
– In addition, each JSP page or servlet processes its own inputs (parameters
from GET or POST)
• Pros:
– Provides a more lightweight design for small, static applications
– Suitable for applications that have very simple page flow
Model 1 Architecture
5
Model 1 Architecture
• Easy and quick to develop web applications, however it
has the following disadvantages:
– Navigation control is decentralized since every page contains
the logic to determine the next page
• If a JSP page name is changed that is referred to by other
pages, we need to change it in all the pages
– that leads to the maintenance problem
– Time consuming: you need to spend more time to develop
custom tags in JSP
• So that we don't need to use scriptlet tag
– Hard to extend: it is better for small applications but not for
large applications
6
Model 1 Architecture
• Possibilities to handle a single request
– Servlet only
• Output is a binary type
• No output (forwarding or redirection to another page)
• Format/layout of page is highly variable
– JSP only
• Output is mostly character data. i.e. HTML
• Format/layout mostly fixed
– Combination
• A single request will result in multiple substantially different-looking
results
• Complicated data processing, but relatively fixed layout
7
JSP in Model 1
• Typical picture:
– use JSP to make it easier to develop and maintain
the HTML content
– For simple dynamic code, use scripting elements
– For slightly more complex applications, use
custom classes called from scripting elements
– For moderately complex applications, use beans
and custom tags
8
Model 2 Architecture
• Model 2 solves the problems in Model 1
Enterprise information system (EIS) refers to any system that holds the data of an organization.
It can be a mainframe, a messaging system, a database system, or an application.
9
Model-2 Architecture
• Introduces a controller servlet between the browser and the JSP
pages being delivered
• The controller centralizes the logic for dispatching requests
– to the next view based on the request URL, input parameters, and
application state
• The controller also handles view selection,
– which decouples JSP pages and servlets from one another
• Easier to maintain and extend, because views do not refer to each
other directly
• Controller servlet provides a single point of control for security
and logging, and often encapsulates incoming data into a form
usable by the back-end MVC model
– For these reasons, the Model 2 architecture is recommended for most
interactive applications
10
Model-View-Controller (MVC)
• MVC is an architectural pattern
• Consists of three modules
– Model (bean):
• represents the state (data) and business logic of the application
– View (JSP):
• responsible to display data (presentation)
– Controller (servlet):
• acts as an interface between view and model (intercepts all requests)
• In a typical Model-View-Control (MVC) application, servlets are often used
for the Controller (C), which involves complex programming logic. JSPs are
often used for the View (V), which mainly deals with presentation. The
Model (M) is usually implemented using JavaBean or EJB.
11
MVC
• The model, as usual, does all the computational work, and no
I/O
– The model can consist of multiple classes
• The servlet class acts as the controller
– The servlet gives any relevant information from the user
request to the model
– The servlet takes the results and passes them on to the
view
• The view—that is, the HTML page that is returned to the user
—is frequently created by JSP
12
Advantages of MVC
• Separation of concerns
– Computation is not intermixed with I/O
– Consequently, code is cleaner and easier to understand
• Flexibility
– The GUI (if one is used) can be completely redone/modified
without touching the model in any way
• Reusability
– The same model used for a servlet can equally be used for an
application or an applet (or by another process)
14
Model
• The model represents business data and business logic
• Operations that govern access and modification of the business
data
• Often the model serves as a software approximation to real-world
functionality
• It notifies views when it changes and provides the ability for the
view to query the model about its state
• It also provides the ability for the controller to access application
functionality encapsulated by the model
15
View
• The view renders the contents of the model
• It accesses data from the model and specifies how that data should
be presented
• It updates data presentation when the model changes.
• The view also forwards user input to the controller.
16
Controller
• The controller defines the application behavior
• Dispatches user requests and selects views for presentation
• Interprets user inputs and maps them into actions to be
performed by the model
• In a stand-alone GUI client, user inputs include button clicks and
menu selections
• In a Web application, they are HTTP GET and POST requests to the
Web tier
• The controller selects the next view to display based on the user
interactions and the outcome of the model operations
• An application typically has one controller for each set of related
functionality
17
Model-View-Controller Architecture
18
RequestDispatcher
• The RequestDispatcher interface provides the facility of
dispatching the request to another resource it may be html, servlet
or jsp.
• This interface can also be used to include the content of another
resource also.
• There are two methods defined in the RequestDispatcher
interface:
– public void forward(ServletRequest req, ServletResponse resp)
throws ServletException, java.io.IOException
• Forwards a request from a servlet to another resource (servlet, JSP file, or HTML file) on
the server.
– public void include(ServletRequest req, ServletResponse resp)
throws
ServletException,java.io.IOException
• Includes the content of a resource (servlet, JSP page, or HTML file) in the response.
19
20
Example
21
Implementing MVC with RequestDispatcher
1. Define beans to represent the data
2. Use a servlet to handle requests
• Servlet reads request parameters, checks for missing and malformed data, etc.
3. Populate the beans
• The servlet invokes business logic (application-specific code) or data-access
code to obtain the results.
• Results are placed in the beans that were defined in step 1.
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
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
• 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 (the JSP page does not create or modify the bean)
22
Request Forwarding Example
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
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);
}
23
jsp:useBean in MVC vs. in Standalone JSP Pages
• In MVC, 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.
24
jsp:useBean Scope Alternative
• request
– <jsp:useBean id="..." type="..." scope="request" />
• session
– <jsp:useBean id="..." type="..." scope="session" />
• application
– <jsp:useBean id="..." type="..." scope="application" />
• page
<jsp:useBean id="..." type="..." scope="page" />
or just
<jsp:useBean id="..." type="..." />
– This scope is not used in MVC (Model 2) architecture
25
Request-based Data Sharing
• In the Servlet, you create the bean and then dispatch the request:
ValueObject value = new ValueObject(...);
request.setAttribute("key", value);
RequestDispatcher disp = request.getRequestDispatcher ("/WEB-INF/SomePage.jsp");
disp.forward(request, response);
• In JSP 1.2:
<jsp:useBean id="key" type=“somePackage.ValueObject” scope="request" />
<jsp:getProperty name="key" property="someProperty" />
• In JSP 2.0, you can also use the expression language as follows:
${key.someProperty}
This expression is equivalent to <% = key.getSomeProperty()%>
• Exercise: Write the above code for session and application scopes!
26
RequestDispatcher.forward vs
Response.SendRedirect
• Response.SendRedirect:
response.sendRedirect("http://www.se432.com/form1");
• RequestDispatcher.forward:
RequestDispatcher disp = request.getRequestDispatcher ("/WEB-INF/SomePage.jsp");
disp.forward(request, response);
• Distinctions: with sendRedirect:
– User sees JSP URL (user sees only servlet URL with RequestDispatcher.forward)
– Two round trips to client (only one with forward)
• Advantages of sendRedirect
– User can visit JSP page separately
– User can bookmark JSP page
• Disadvantages of sendRedirect
– Since user can visit JSP page without going through servlet first, JSP data
might not be available
• So, JSP page needs code to detect this situation
27
MVC Example – Bank Account Balances
• Bean
– BankCustomer
• Servlet that populates bean and forwards to appropriate JSP page
– Reads customer ID, calls data-access code to populate
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
28
Servlet Code
public class ShowBalance extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
BankCustomer c = BankCustomer.getCustomer (request.getParameter("id"));
String address;
if (c == null) {
address = "/WEB-INF/bank-account/UnknownCustomer.jsp";
} else if (c.getBalance() < 0) {
address = "/WEB-INF/bank-account/NegativeBalance.jsp";
request.setAttribute("badCustomer", c);
}
RequestDispatcher dispatcher = request.getRequestDispatcher(address);
dispatcher.forward(request, response);
}
29
NegativeBalance.jsp
<HTML>
<BODY>
<TABLE BORDER=5 ALIGN="CENTER">
<TR><TH CLASS="TITLE">
We Know Where You Live!</TABLE>
<P>
<IMG SRC="/bank-support/Club.gif" ALIGN="LEFT">
<jsp:useBean id="badCustomer“ type="coreservlets.BankCustomer“ scope="request" />
Watch out,
<jsp:getProperty name="badCustomer“ property="firstName" />,
we know where you live.
<P>
Pay us the $<jsp:getProperty name="badCustomer“ property="balanceNoSign" />
you owe us before it is too late!
</BODY>
</HTML>
30
JSP 2.0 Code
(NegativeBalance.jsp)
<BODY>
<TABLE BORDER=5 ALIGN="CENTER">
<TR><TH CLASS="TITLE">
We Know Where You Live!</TABLE>
<P>
<IMG SRC="/bank-support/Club.gif" ALIGN="LEFT">
Watch out,
${badCustomer.firstName},
we know where you live.
<P>
Pay us the $${badCustomer.balanceNoSign}
you owe us before it is too late!
</BODY></HTML>

More Related Content

Recently uploaded (20)

PDF
Streamline Contractor Lifecycle- TECH EHS Solution
TECH EHS Solution
 
PDF
Understanding the Need for Systemic Change in Open Source Through Intersectio...
Imma Valls Bernaus
 
PDF
iTop VPN With Crack Lifetime Activation Key-CODE
utfefguu
 
PPTX
Equipment Management Software BIS Safety UK.pptx
BIS Safety Software
 
PPTX
Revolutionizing Code Modernization with AI
KrzysztofKkol1
 
PPTX
3uTools Full Crack Free Version Download [Latest] 2025
muhammadgurbazkhan
 
PDF
Mobile CMMS Solutions Empowering the Frontline Workforce
CryotosCMMSSoftware
 
DOCX
Import Data Form Excel to Tally Services
Tally xperts
 
PPTX
Hardware(Central Processing Unit ) CU and ALU
RizwanaKalsoom2
 
PPTX
The Role of a PHP Development Company in Modern Web Development
SEO Company for School in Delhi NCR
 
PDF
HiHelloHR – Simplify HR Operations for Modern Workplaces
HiHelloHR
 
PPTX
Comprehensive Guide: Shoviv Exchange to Office 365 Migration Tool 2025
Shoviv Software
 
PPTX
How Odoo Became a Game-Changer for an IT Company in Manufacturing ERP
SatishKumar2651
 
PDF
Alarm in Android-Scheduling Timed Tasks Using AlarmManager in Android.pdf
Nabin Dhakal
 
PPTX
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pptx
Varsha Nayak
 
PPTX
A Complete Guide to Salesforce SMS Integrations Build Scalable Messaging With...
360 SMS APP
 
PPTX
Writing Better Code - Helping Developers make Decisions.pptx
Lorraine Steyn
 
PDF
Linux Certificate of Completion - LabEx Certificate
VICTOR MAESTRE RAMIREZ
 
PDF
Continouous failure - Why do we make our lives hard?
Papp Krisztián
 
PPTX
Migrating Millions of Users with Debezium, Apache Kafka, and an Acyclic Synch...
MD Sayem Ahmed
 
Streamline Contractor Lifecycle- TECH EHS Solution
TECH EHS Solution
 
Understanding the Need for Systemic Change in Open Source Through Intersectio...
Imma Valls Bernaus
 
iTop VPN With Crack Lifetime Activation Key-CODE
utfefguu
 
Equipment Management Software BIS Safety UK.pptx
BIS Safety Software
 
Revolutionizing Code Modernization with AI
KrzysztofKkol1
 
3uTools Full Crack Free Version Download [Latest] 2025
muhammadgurbazkhan
 
Mobile CMMS Solutions Empowering the Frontline Workforce
CryotosCMMSSoftware
 
Import Data Form Excel to Tally Services
Tally xperts
 
Hardware(Central Processing Unit ) CU and ALU
RizwanaKalsoom2
 
The Role of a PHP Development Company in Modern Web Development
SEO Company for School in Delhi NCR
 
HiHelloHR – Simplify HR Operations for Modern Workplaces
HiHelloHR
 
Comprehensive Guide: Shoviv Exchange to Office 365 Migration Tool 2025
Shoviv Software
 
How Odoo Became a Game-Changer for an IT Company in Manufacturing ERP
SatishKumar2651
 
Alarm in Android-Scheduling Timed Tasks Using AlarmManager in Android.pdf
Nabin Dhakal
 
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pptx
Varsha Nayak
 
A Complete Guide to Salesforce SMS Integrations Build Scalable Messaging With...
360 SMS APP
 
Writing Better Code - Helping Developers make Decisions.pptx
Lorraine Steyn
 
Linux Certificate of Completion - LabEx Certificate
VICTOR MAESTRE RAMIREZ
 
Continouous failure - Why do we make our lives hard?
Papp Krisztián
 
Migrating Millions of Users with Debezium, Apache Kafka, and an Acyclic Synch...
MD Sayem Ahmed
 

Featured (20)

PDF
How to Leverage AI to Boost Employee Wellness - Lydia Di Francesco - SocialHR...
SocialHRCamp
 
PDF
2024 State of Marketing Report – by Hubspot
Marius Sescu
 
PDF
Everything You Need To Know About ChatGPT
Expeed Software
 
PDF
Product Design Trends in 2024 | Teenage Engineerings
Pixeldarts
 
PDF
How Race, Age and Gender Shape Attitudes Towards Mental Health
ThinkNow
 
PDF
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
marketingartwork
 
PDF
Skeleton Culture Code
Skeleton Technologies
 
PDF
PEPSICO Presentation to CAGNY Conference Feb 2024
Neil Kimberley
 
PDF
Content Methodology: A Best Practices Report (Webinar)
contently
 
PPTX
How to Prepare For a Successful Job Search for 2024
Albert Qian
 
PDF
Social Media Marketing Trends 2024 // The Global Indie Insights
Kurio // The Social Media Age(ncy)
 
PDF
Trends In Paid Search: Navigating The Digital Landscape In 2024
Search Engine Journal
 
PDF
5 Public speaking tips from TED - Visualized summary
SpeakerHub
 
PDF
ChatGPT and the Future of Work - Clark Boyd
Clark Boyd
 
PDF
Getting into the tech field. what next
Tessa Mero
 
PDF
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Lily Ray
 
PDF
How to have difficult conversations
Rajiv Jayarajah, MAppComm, ACC
 
PDF
Introduction to Data Science
Christy Abraham Joy
 
PDF
Time Management & Productivity - Best Practices
Vit Horky
 
PDF
The six step guide to practical project management
MindGenius
 
How to Leverage AI to Boost Employee Wellness - Lydia Di Francesco - SocialHR...
SocialHRCamp
 
2024 State of Marketing Report – by Hubspot
Marius Sescu
 
Everything You Need To Know About ChatGPT
Expeed Software
 
Product Design Trends in 2024 | Teenage Engineerings
Pixeldarts
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
ThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
marketingartwork
 
Skeleton Culture Code
Skeleton Technologies
 
PEPSICO Presentation to CAGNY Conference Feb 2024
Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
contently
 
How to Prepare For a Successful Job Search for 2024
Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Kurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
SpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
Clark Boyd
 
Getting into the tech field. what next
Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Lily Ray
 
How to have difficult conversations
Rajiv Jayarajah, MAppComm, ACC
 
Introduction to Data Science
Christy Abraham Joy
 
Time Management & Productivity - Best Practices
Vit Horky
 
The six step guide to practical project management
MindGenius
 
Ad

Engineering the Java Web Application (MVC)

  • 1. 1 Engineering the Java Web Application (MVC) SE 432 Software Engineering for Web Applications
  • 2. 2 Introduction • What we have studied so far is the following: – A request is made to a JSP or a Servlet and then that JSP or Servlet handles all responsibilities for the request, including • processing the request, • validating data, • handling the business logic, • and generating a response • This is known as Model 1 Architecture
  • 3. 3 Model 1 Architecture • Commonly used in small, simple task applications due to its ease of development
  • 4. 4 • Client directly calls a JSP page • The JSP page accesses the JavaBeans (the application model) • The next view to be displayed is determined either: – by hyperlinks selected in the source document or – by request parameters • Control is decentralized, which is bad, Why? – because the current page being displayed determines the next page to display – In addition, each JSP page or servlet processes its own inputs (parameters from GET or POST) • Pros: – Provides a more lightweight design for small, static applications – Suitable for applications that have very simple page flow Model 1 Architecture
  • 5. 5 Model 1 Architecture • Easy and quick to develop web applications, however it has the following disadvantages: – Navigation control is decentralized since every page contains the logic to determine the next page • If a JSP page name is changed that is referred to by other pages, we need to change it in all the pages – that leads to the maintenance problem – Time consuming: you need to spend more time to develop custom tags in JSP • So that we don't need to use scriptlet tag – Hard to extend: it is better for small applications but not for large applications
  • 6. 6 Model 1 Architecture • Possibilities to handle a single request – Servlet only • Output is a binary type • No output (forwarding or redirection to another page) • Format/layout of page is highly variable – JSP only • Output is mostly character data. i.e. HTML • Format/layout mostly fixed – Combination • A single request will result in multiple substantially different-looking results • Complicated data processing, but relatively fixed layout
  • 7. 7 JSP in Model 1 • Typical picture: – use JSP to make it easier to develop and maintain the HTML content – For simple dynamic code, use scripting elements – For slightly more complex applications, use custom classes called from scripting elements – For moderately complex applications, use beans and custom tags
  • 8. 8 Model 2 Architecture • Model 2 solves the problems in Model 1 Enterprise information system (EIS) refers to any system that holds the data of an organization. It can be a mainframe, a messaging system, a database system, or an application.
  • 9. 9 Model-2 Architecture • Introduces a controller servlet between the browser and the JSP pages being delivered • The controller centralizes the logic for dispatching requests – to the next view based on the request URL, input parameters, and application state • The controller also handles view selection, – which decouples JSP pages and servlets from one another • Easier to maintain and extend, because views do not refer to each other directly • Controller servlet provides a single point of control for security and logging, and often encapsulates incoming data into a form usable by the back-end MVC model – For these reasons, the Model 2 architecture is recommended for most interactive applications
  • 10. 10 Model-View-Controller (MVC) • MVC is an architectural pattern • Consists of three modules – Model (bean): • represents the state (data) and business logic of the application – View (JSP): • responsible to display data (presentation) – Controller (servlet): • acts as an interface between view and model (intercepts all requests) • In a typical Model-View-Control (MVC) application, servlets are often used for the Controller (C), which involves complex programming logic. JSPs are often used for the View (V), which mainly deals with presentation. The Model (M) is usually implemented using JavaBean or EJB.
  • 11. 11 MVC • The model, as usual, does all the computational work, and no I/O – The model can consist of multiple classes • The servlet class acts as the controller – The servlet gives any relevant information from the user request to the model – The servlet takes the results and passes them on to the view • The view—that is, the HTML page that is returned to the user —is frequently created by JSP
  • 12. 12 Advantages of MVC • Separation of concerns – Computation is not intermixed with I/O – Consequently, code is cleaner and easier to understand • Flexibility – The GUI (if one is used) can be completely redone/modified without touching the model in any way • Reusability – The same model used for a servlet can equally be used for an application or an applet (or by another process)
  • 13. 14 Model • The model represents business data and business logic • Operations that govern access and modification of the business data • Often the model serves as a software approximation to real-world functionality • It notifies views when it changes and provides the ability for the view to query the model about its state • It also provides the ability for the controller to access application functionality encapsulated by the model
  • 14. 15 View • The view renders the contents of the model • It accesses data from the model and specifies how that data should be presented • It updates data presentation when the model changes. • The view also forwards user input to the controller.
  • 15. 16 Controller • The controller defines the application behavior • Dispatches user requests and selects views for presentation • Interprets user inputs and maps them into actions to be performed by the model • In a stand-alone GUI client, user inputs include button clicks and menu selections • In a Web application, they are HTTP GET and POST requests to the Web tier • The controller selects the next view to display based on the user interactions and the outcome of the model operations • An application typically has one controller for each set of related functionality
  • 17. 18 RequestDispatcher • The RequestDispatcher interface provides the facility of dispatching the request to another resource it may be html, servlet or jsp. • This interface can also be used to include the content of another resource also. • There are two methods defined in the RequestDispatcher interface: – public void forward(ServletRequest req, ServletResponse resp) throws ServletException, java.io.IOException • Forwards a request from a servlet to another resource (servlet, JSP file, or HTML file) on the server. – public void include(ServletRequest req, ServletResponse resp) throws ServletException,java.io.IOException • Includes the content of a resource (servlet, JSP page, or HTML file) in the response.
  • 18. 19
  • 20. 21 Implementing MVC with RequestDispatcher 1. Define beans to represent the data 2. Use a servlet to handle requests • Servlet reads request parameters, checks for missing and malformed data, etc. 3. Populate the beans • The servlet invokes business logic (application-specific code) or data-access code to obtain the results. • Results are placed in the beans that were defined in step 1. 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 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 • 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 (the JSP page does not create or modify the bean)
  • 21. 22 Request Forwarding Example public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 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); }
  • 22. 23 jsp:useBean in MVC vs. in Standalone JSP Pages • In MVC, 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.
  • 23. 24 jsp:useBean Scope Alternative • request – <jsp:useBean id="..." type="..." scope="request" /> • session – <jsp:useBean id="..." type="..." scope="session" /> • application – <jsp:useBean id="..." type="..." scope="application" /> • page <jsp:useBean id="..." type="..." scope="page" /> or just <jsp:useBean id="..." type="..." /> – This scope is not used in MVC (Model 2) architecture
  • 24. 25 Request-based Data Sharing • In the Servlet, you create the bean and then dispatch the request: ValueObject value = new ValueObject(...); request.setAttribute("key", value); RequestDispatcher disp = request.getRequestDispatcher ("/WEB-INF/SomePage.jsp"); disp.forward(request, response); • In JSP 1.2: <jsp:useBean id="key" type=“somePackage.ValueObject” scope="request" /> <jsp:getProperty name="key" property="someProperty" /> • In JSP 2.0, you can also use the expression language as follows: ${key.someProperty} This expression is equivalent to <% = key.getSomeProperty()%> • Exercise: Write the above code for session and application scopes!
  • 25. 26 RequestDispatcher.forward vs Response.SendRedirect • Response.SendRedirect: response.sendRedirect("http://www.se432.com/form1"); • RequestDispatcher.forward: RequestDispatcher disp = request.getRequestDispatcher ("/WEB-INF/SomePage.jsp"); disp.forward(request, response); • Distinctions: with sendRedirect: – User sees JSP URL (user sees only servlet URL with RequestDispatcher.forward) – Two round trips to client (only one with forward) • Advantages of sendRedirect – User can visit JSP page separately – User can bookmark JSP page • Disadvantages of sendRedirect – Since user can visit JSP page without going through servlet first, JSP data might not be available • So, JSP page needs code to detect this situation
  • 26. 27 MVC Example – Bank Account Balances • Bean – BankCustomer • Servlet that populates bean and forwards to appropriate JSP page – Reads customer ID, calls data-access code to populate 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
  • 27. 28 Servlet Code public class ShowBalance extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { BankCustomer c = BankCustomer.getCustomer (request.getParameter("id")); String address; if (c == null) { address = "/WEB-INF/bank-account/UnknownCustomer.jsp"; } else if (c.getBalance() < 0) { address = "/WEB-INF/bank-account/NegativeBalance.jsp"; request.setAttribute("badCustomer", c); } RequestDispatcher dispatcher = request.getRequestDispatcher(address); dispatcher.forward(request, response); }
  • 28. 29 NegativeBalance.jsp <HTML> <BODY> <TABLE BORDER=5 ALIGN="CENTER"> <TR><TH CLASS="TITLE"> We Know Where You Live!</TABLE> <P> <IMG SRC="/bank-support/Club.gif" ALIGN="LEFT"> <jsp:useBean id="badCustomer“ type="coreservlets.BankCustomer“ scope="request" /> Watch out, <jsp:getProperty name="badCustomer“ property="firstName" />, we know where you live. <P> Pay us the $<jsp:getProperty name="badCustomer“ property="balanceNoSign" /> you owe us before it is too late! </BODY> </HTML>
  • 29. 30 JSP 2.0 Code (NegativeBalance.jsp) <BODY> <TABLE BORDER=5 ALIGN="CENTER"> <TR><TH CLASS="TITLE"> We Know Where You Live!</TABLE> <P> <IMG SRC="/bank-support/Club.gif" ALIGN="LEFT"> Watch out, ${badCustomer.firstName}, we know where you live. <P> Pay us the $${badCustomer.balanceNoSign} you owe us before it is too late! </BODY></HTML>