CSBP 461 Internet Computing: MVC Architecture PDF
Document Details
Uploaded by CoolestOnyx679
2020
Dr. M. Elarbi Badidi
Tags
Summary
This document is a presentation on the Model-View-Controller (MVC) architecture for web applications. It explains the MVC pattern, its benefits, and how it's implemented using servlets and JSP. The presentation includes diagrams, code snippets, and examples.
Full Transcript
CSBP 461 Internet Computing: Integrating Servlets and JSP: The Model View Controller (MVC) Architecture Dr. M. Elarbi Badidi Fall 2020 Outline Understanding the benefits of MVC Using RequestDispatcher to implement MVC Forwarding requests from Servlets to JSP...
CSBP 461 Internet Computing: Integrating Servlets and JSP: The Model View Controller (MVC) Architecture Dr. M. Elarbi Badidi Fall 2020 Outline 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 2 Traditional Applications ▪ Browser directly accesses page. Does not centralize control No content/style separation Easy and fast to produce Difficult to maintain 3 MVC Applications ▪ Browser accesses a “controller” Centralizes control Clean separation of content/style More involved to produce Easier to maintain and expand 4 MVC ▪ MVC is an Architectural Design Pattern ▪ Separates a web application into three different modules. 5 Design Pattern ▪ A pattern that has been developed to help programmers cope with common problems. ▪ Blueprints on how to construct something. 6 Trip to Shakespeare and Co ▪ A Patisserie in Dubai http://www.shakespeareandco.ae/ 7 Typical Bakery Interaction ▪ Request a tasty treat from the baker 8 Baker Gathers Ingredients ▪ Baker gathers raw ingredients to fulfill the request. ▪ Some requests utilize same ingredients. 9 Baker Selects Pan ▪ The pan dictates what the response looks like. 10 Baker responds with your treat 11 Patisserie Flow 12 MVC Diagram 13 Controller (Baker) ▪ Dispatches Requests and controls flow. ▪ Centralizes access. ▪ Interacts with Model and View. 14 Model (Ingredients) ▪ Data representation and business logic. ▪ Can be database/xml/etc ▪ Business Logic 15 View (Pan) ▪ Data presentation and user input. ▪ Renders the Model in to a View. ▪ Can be HTML/PDF/WML/Javascript ▪ No computations, very little logic, display logic i.e. loops 16 MVC Diagram 17 MVC Advantages ▪ Separation of interests. Model centralizes business logic. View centralizes display logic. Controller centralizes application flow. ▪ Clean separation of content/style. ▪ Improved decoupling. ▪ Easier testing. ▪ Allow multiple people to work on different parts. 18 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. 19 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. 19 MVC Flow of Control HTML or JSP Java Code (Business Logic) Results (beans) submit form Servlet Form (URL matches url- (Store beans in pattern of servlet) request, session, or application scope) JSP1 JSP2 JSP3 (Extract data from beans and put in output) 20 20 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 21 Servlet context objects to store a reference to the beans that represent the results of the request. 21 Implementing MVC with RequestDispatcher (Cont.) 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; it merely extracts and displays data that the Servlet created. 22 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"; 23 } RequestDispatcher dispatcher = request.getRequestDispatcher(address); dispatcher.forward(request, response); } 23 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 instead of The JSP page should not modify the objects 24 So, you should use jsp:getProperty but not jsp:setProperty. 24 Reminder: jsp:useBean Scope Alternatives (JSP 1.2 only!) request session application page or just This scope is not used in MVC (Model 2) architecture 25 25 Request-Based Data Sharing Servlet ValueObject value = new ValueObject(...); request.setAttribute("key", value); RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB- INF/SomePage.jsp"); dispatcher.forward(request, response); JSP 1.2 26 JSP 2.0 Name chosen by the servlet. ${key.someProperty} Name of accessor method, minus the word "get", with next letter changed to lower case. 26 Request-Based Data Sharing: Example Servlet Customer myCustomer = new Customer(request.getParameter("customerID")); request.setAttribute("customer", myCustomer); RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB- INF/SomePage.jsp"); dispatcher.forward(request, response); JSP 1.2 … Answer: browser treats them as relative to Servlet URL 31 31 Applying MVC: 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 32 High balance: page with advertisements added Unknown customer ID: error page 32 Bank Account Balances: Servlet Code public class ShowBalance extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { BankCustomer customer = BankCustomer.getCustomer (request.getParameter("id")); String address; if (customer == null) { address = "/WEB-INF/bank-account/UnknownCustomer.jsp"; } else if (customer.getBalance() < 0) { address = "/WEB-INF/bank-account/NegativeBalance.jsp"; request.setAttribute("badCustomer", customer); 33 } … RequestDispatcher dispatcher = request.getRequestDispatcher(address); dispatcher.forward(request, response); 33 Bank Account Balances: JSP 1.2 Code (Negative Balance) … We Know Where You Live! Watch out, , we know where you live. 34 Pay us the $ you owe us before it is too late! 34 Bank Account Balances: JSP 2.0 Code (Negative Balance) … We Know Where You Live! Watch out, ${badCustomer.firstName}, we know where you live. Pay us the $${badCustomer.balanceNoSign} 35 you owe us before it is too late! 35 Bank Account Balances: Results 36 Comparing Data-Sharing Approaches: Request Goal Display a random number to the user Type of sharing Each request should result in a new number, so request- based sharing is appropriate. 37 37 Request-Based Sharing: Bean package coreservlets; public class NumberBean { private double num = 0; public NumberBean(double number) { setNumber(number); } public double getNumber() { return(num); } public void setNumber(double number) { 38 num = number; } } 38 Request-Based Sharing: Servlet public class RandomNumberServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { NumberBean bean = new NumberBean(Math.random()); request.setAttribute("randomNum", bean); String address = "/WEB-INF/mvc-sharing/RandomNum.jsp"; RequestDispatcher dispatcher = 39 request.getRequestDispatcher(address); dispatcher.forward(request, response); } } 39 Request-Based Sharing: JSP 1.2 … Random Number: 40 Request-Based Sharing: JSP 2.0 … Random Number: ${randomNum.number} 41 41 Request-Based Sharing: Results 42 42 Comparing Data-Sharing Approaches: Session Goal Display users’ first and last names. If the users fail to tell us their name, we want to use whatever name they gave us previously. If the users do not explicitly specify a name and no previous name is found, a warning should be displayed. Type of sharing Data is stored for each client, so session-based sharing is 43 appropriate. 43 Session-Based Sharing: Bean public class NameBean implements Serializable { private String firstName = "Missing first name"; private String lastName = "Missing last name"; public NameBean(String firstName, String lastName) { setFirstName(firstName); setLastName(lastName); } public String getFirstName() { return(firstName); } public void setFirstName(String firstName) { if (!isMissing(firstName)) { this.firstName = firstName; } } 44... // getLastName, setLastName private boolean isMissing(String value) { return((value == null) || (value.trim().equals(""))); } } 44 Session-Based Sharing: Servlet public class RegistrationServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); NameBean nameBean = (NameBean)session.getAttribute("nameBean"); if (nameBean == null) { String firstName= request.getParameter("firstName"); String lastName = request.getParameter("lastName"); nameBean = new NameBean(firstName, lastName); session.setAttribute("nameBean", nameBean); } String address = "/WEB-INF/mvc-sharing/ShowName.jsp"; RequestDispatcher dispatcher = 45 request.getRequestDispatcher(address); dispatcher.forward(request, response); } } 45 Session-Based Sharing: JSP 1.2 … Thanks for Registering First Name: Last Name: 46 46 Session-Based Sharing: JSP 2.0 … Thanks for Registering First Name: ${nameBean.firstName} Last Name: ${nameBean.lastName} 47 47 Session-Based Sharing: Results 48 48 Comparing Data-Sharing Approaches: ServletContext Goal Display a prime number of a specified length. If the user fails to tell us the desired length, we want to use whatever prime number we most recently computed for any user. Type of sharing Data is shared among multiple clients, so application-based sharing is appropriate. 49 49 ServletContext-Based Sharing: Bean package coreservlets; import java.math.BigInteger; public class PrimeBean { private BigInteger prime; public PrimeBean(String lengthString) { int length = 150; try { length = Integer.parseInt(lengthString); } catch(NumberFormatException nfe) {} setPrime(Primes.nextPrime(Primes.random(length)) ); } public BigInteger getPrime() { 50 return(prime); } … } 50 ServletContext-Based Sharing: Servlet public class PrimeServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String length = request.getParameter("primeLength"); ServletContext context = getServletContext(); synchronized(this) { if ((context.getAttribute("primeBean") == null) || (length != null)) { PrimeBean primeBean = new PrimeBean(length); context.setAttribute("primeBean", primeBean); } String address = "/WEB-INF/mvc- sharing/ShowPrime.jsp"; 51 RequestDispatcher dispatcher = request.getRequestDispatcher(address); dispatcher.forward (request, response); } } } 51 ServletContext-Based Sharing: JSP 1.2 … A Prime Number 52 ServletContext-Based Sharing: JSP 2.0 … A Prime Number ${primeBean.prime} 53 53 ServletContext-Based Sharing: Results 54 54 Forwarding from JSP Pages 0.5) { destination = "/examples/page1.jsp"; } else { destination = "/examples/page2.jsp"; } %> Legal, but bad idea 55 Business and control logic belongs in servlets Keep JSP focused on presentation 55 Including Pages Instead of Forwarding to Them With the forward method of RequestDispatcher: Control is permanently transferred to new page Original page cannot generate any output With the include method of RequestDispatcher: Control is temporarily transferred to new page Original page can generate output before and after the included page Original servlet does not see the output of the included page (for this, see later topic on servlet/JSP filters) Useful for portals: JSP presents pieces, but pieces arranged in 56 different orders for different users 56 Including Pages Instead of Forwarding to Them response.setContentType("text/html"); String firstTable, secondTable, thirdTable; if (someCondition) { firstTable = "/WEB-INF/Sports-Scores.jsp"; secondTable = "/WEB-INF/Stock-Prices.jsp"; thirdTable = "/WEB-INF/Weather.jsp"; } else if (...) {... } RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/Header.jsp"); dispatcher.include(request, response); dispatcher = request.getRequestDispatcher(firstTable); dispatcher.include(request, response); dispatcher = request.getRequestDispatcher(secondTable); dispatcher.include(request, response); dispatcher = request.getRequestDispatcher(thirdTable); 57 dispatcher.include(request, response); dispatcher = request.getRequestDispatcher("/WEB- INF/Footer.jsp"); dispatcher.include(request, response); 57 Summary Use MVC (Model 2) approach when: One submission will result in more than one basic look Several pages have substantial common processing Architecture A servlet answers the original request Servlet does the real processing & stores results in beans o Beans stored in HttpServletRequest, HttpSession, or ServletContext Servlet forwards to JSP page via forward method of RequestDispatcher JSP page reads data from beans by means of jsp:useBean with appropriate scope (request, session, or application) 58 o Or, in JSP 2, with ${beanName.propertyName} 58