Time Management & Productivity - Best PracticesVit Horky
The six step guide to practical project managementMindGenius
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.
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)
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>