Download presentation
Presentation is loading. Please wait.
Published byDylan Burke Modified over 9 years ago
1
Chapter 91© copyright Janson Industries 2011 Java Design Concepts ■ JSP’s ■ MVC MVC ■ Beans Beans ■ JSP Tags JSP Tags
2
Chapter 92© copyright Janson Industries 2011 Java Design Concepts ■ How do you like having to type in all that HTML for servlet? ■ Make a few source code entry mistakes? ■ Page Designer and JSP’s make it easier
3
Chapter 93© copyright Janson Industries 2011 JSP Example ▮ Java Server Pages are comprised of HTML with embedded Java statements, JSP tags, or JSTL tags HTML code Java code HTML code Java code HTML code ▮ JSP Java statement types ▮ Scriptlet ▮ Expression ▮ Declaration ▮ Directive
4
Chapter 94© copyright Janson Industries 2011 Java Statement Tags ▮ Java scriptlet syntax: ▮ Java expression syntax: ▮ Java declaration syntax: ▮ Java directive syntax:
5
Chapter 95© copyright Janson Industries 2011 JSP Example JSP Example Howdy from the JSP example. The current date and time is: A lot less code than a servlet! Scriptlet Expression Scriptlet
6
Chapter 96© copyright Janson Industries 2011 Java Statement Tags ▮ Java declaration allows you to define a method: <%! private void error() { System.out.println(“Error, Error!”); } %> ▮ Java directive allows you to specify JSP wide instructions:
7
Chapter 97© copyright Janson Industries 2011 JSP Example ▮ Problem with Java statements – not XML compliant ▮ Use JSP tags: for (int i = 0; i new java.util.Date() private void error() { System.out.println(“Error, Error!”); }
8
Chapter 98© copyright Janson Industries 2011 To Create, click on MyWeb, File, New, Web Page Give JSP a name (JSPEx), click on JSP in the Basic Templates area then click Finish
9
Chapter 99© copyright Janson Industries 2011 Initial code inserted by RAD
10
Chapter 910© copyright Janson Industries 2011 In Navigation Pane, right click JSPEx and select Run on Server Cut and paste example code (from earlier slide) over RAD code
11
Chapter 911© copyright Janson Industries 2011 Do same using JSP tags not Java Statement tags Solution
12
Chapter 912© copyright Janson Industries 2011 JSP ▮ JSP’s are actually converted into Servlets by the JSP container ▮ For instance, in Tomcat, for each.jsp file there is a.java and.class file created in /Tomcat 5.0/work/standalone/localhost/test ▮ I.e. if I created Studio.jsp, Tomcat will create the files Studio$jsp.java & Studio$jsp.class
13
Chapter 913© copyright Janson Industries 2011 So, really, the advantage to JSP’s is ease of construction for the programmer
14
Chapter 914© copyright Janson Industries 2011 JSP ▮ For JSPs, RAD generates a class file with the same name as the JSP preceded by an underscore ▮ _JSPEx.class ▮ The class file is stored in the WAR ▮ RAD doesn't provide access or even display the file (as far as I can tell!)
15
Chapter 915© copyright Janson Industries 2011 JSP But using Computer you can drill into the server and find it
16
Chapter 916© copyright Janson Industries 2011 RAD JSP ▮ Design pane provides a GUI to build JSP’s ▮ Drop and drag Web page GUI components ▮ Property definition panes ▮ Format Java statements ▮ Insert predefined routines (scriptlets) ▮ For example, create a JSP called RAD
17
© copyright Janson Industries 2011Chapter 917 Insert this text RAD JSP
18
Chapter 918© copyright Janson Industries 2011 To Insert a Scriptlet, position cursor on page, click JSP, Insert Scriptlet
19
Chapter 919© copyright Janson Industries 2011 Display the Properties view of the Scriptlet
20
Chapter 920© copyright Janson Industries 2011 In properties pane specify Java code In this example, inserted the beginning of a loop
21
Chapter 921© copyright Janson Industries 2011 Insert another scriptlet with the rest of the for loop
22
Chapter 922© copyright Janson Industries 2011 Run on the server Should have a tag to insert a line in each loop
23
© copyright Janson Industries 2011Chapter 923 RAD JSP Save the code
24
Chapter 924© copyright Janson Industries 2011 Refresh the browser
25
Chapter 925© copyright Janson Industries 2011 ▮ Need to be a Java programmer to implement ▮ Cumbersome syntax ▮ Knowledge of object oriented programming ▮ No coding standards ▮ for (int i = -200 ; i < -100; i=i+20) { ▮ JSTL Tags are the solution (more later) Java Statement Problems
26
Chapter 926© copyright Janson Industries 2011 JSP In Class Assg ▮ Create a JSP that uses a loop to print the system date five times
27
Chapter 927© copyright Janson Industries 2011 Java Design Concepts ■ MVC design pattern for server-based applications ♦ Model ♦ View ♦ Controller
28
Chapter 928© copyright Janson Industries 2011 MVC ■ Model – classes that access/store data and perform business functions ■ View – classes that: ♦ Enable users to input data/instructions ♦ Format and display results ■ Controller – classes that manage the model and view
29
Means creates Chapter 929© copyright Janson Industries 2011 Java MVC Example DB Data and instructions Data View User Data and instructions Application results Data Model Data View Controller
30
Chapter 930© copyright Janson Industries 2011 MVC ■ You can see the MVC pieces in the client app ■ However: ♦ Separation of pieces difficult with client technology ♦ Initially, user must interact directly with Controller
31
Chapter 931© copyright Janson Industries 2011 Customer CustomerApp Model Customer Frame User run CustomerApp instruction EnterCustInfo creates Empty Frame Frame (with data) & Display instruction data CustomerFrame with data Controller 1 2 3 4 5 8 6 View cust Client App MVC Example data 7 ViewController
32
Chapter 932© copyright Janson Industries 2011 Server Side MVC Example Java Bean Java Bean DB Controller Model JSP’s View User HTML (response) Web Pages View Servlet Data Data and instructions
33
Chapter 9 33 © copyright Janson Industries 2011 Employee MVC Example Emp Extractor Employee EmpServlet Controller Model DispEmp InfoJSP View User HTML (response) Request Response DispEmp GrossJSP DispEmp TaxAmtJSP Request Employee View EnterEmp InfoForm Data
34
Chapter 934© copyright Janson Industries 2011 Employee Example ■ EmpServlet acted as the Controller ■ The JSPs and EmpExtractor were the View ■ Employee was the Model ■ The View created the Model
35
Chapter 935© copyright Janson Industries 2011 MyWeb Example Func2 Servlet Customer object FuncServlet co Cust Servlet User Functions.html Sale Servlet Data Cust or Sale.html Cust.html HTML (response) With Cust info Sale.html HTML (response) With Sale info Controller Model View request response co Data
36
Chapter 936© copyright Janson Industries 2011 Java MVC Example ■ The current thinking is to separate the GUI from the programming logic ♦ Have “graphic designers” create the View (e.g. html and html of the JSPs) ♦ Programmers define the controller (servlets) & business logic (Model) as java beans ♦ JSPs access java beans ► No java code in JSPs, use tags to access beans
37
Chapter 937© copyright Janson Industries 2011 MVC Advantages ■ Separating html development from program development cuts down on ♦ Duplicate programming code (in web page, legacy interface, new interfaces, etc.) ♦ Errors ■ Cheaper “resources” develop interface rather than the more expensive programming personnel
38
Chapter 938© copyright Janson Industries 2011 MVC Advantages ■ Separating business logic and controller from interface means: ♦ New interfaces can be easily added ► Web Services ► Text messaging ► EDI ► Telephony ♦ Changes to DBMS only affect Model
39
Chapter 939© copyright Janson Industries 2011 Java MVC Example Data and instructions Data View User Data and instructions Application results Data ModelView Controller User Phone View
40
Chapter 940© copyright Janson Industries 2011 Java MVC Example ■ Many shops make legacy code part of the model and create servlets and JSPs for view and controller portion ■ Some shops recode all the model/legacy in Java
41
Chapter 941© copyright Janson Industries 2011 What is a Java Bean ■ A convention/standard for classes ♦ A public Java class ♦ Has a default null constructor ■ Usually has getter/setter methods for each private bean variable (i.e. each property) defined as follows: ♦ public VariableType getVariableName() ♦ public void setVariableName (VariableType x)
42
Chapter 942© copyright Janson Industries 2011 What is a Java Bean ■ But guess what? ■ On the server, you can define (just about) any class as a bean ♦ Just won’t be able to access the properties if you don’t have getters and setters
43
Chapter 943© copyright Janson Industries 2011 Server Beans ■ Many categories of Server beans: ♦ Entity – associated with a DB table, EJB ♦ Session – last for length of session (duration of browser-server communication) ♦ Request – goes with request ► (Also Page and Application) ■ Can be created/defined by either JSPs or Servlets
44
Chapter 944© copyright Janson Industries 2011 Server Beans ■ The Servlet or JSP has to: ♦ Identify the bean ■ Identifying the bean means ♦ Giving the bean a name ♦ Tying the bean to a Java class/object ♦ Defining a bean type/scope ■ Once created, Servlets or JSPs can: ♦ Set a bean parameter/property ♦ Get a bean result/property
45
Chapter 945© copyright Janson Industries 2011 JSP Tags ■ In servlet, create object and tie to session (or request, or page, or app) by defining object as an attribute of the session: Customer Cust = new Customer(); HttpSession sess = req.getSession(); sess.setAttribute("CustBean", Cust); ■ In JSPs, Bean tags used to work with beans: ■ Identify a bean and tie to a java class file with a useBean tag:
46
Chapter 946© copyright Janson Industries 2011 Accessing a Bean in a Servlet ■ Set: CustBean.setCustName(req. getParameter(“CustNameTF")); ■ Get: CustBean.getContactPerson(); ■ Because it’s a session bean, any servlet invoked during browser sess can access
47
Chapter 947© copyright Janson Industries 2011 ■ Set and get bean properties with the Bean tags getProperty and setProperty ♦ Name is name of bean ♦ Property is property name ■ setProperty used to set property value ■ getProperty used to get results Accessing a Bean in a JSP
48
Chapter 948© copyright Janson Industries 2011 Java Bean Example ■ Servlet code: CustBean.setCustName(req.getParameter (“CustNameTF")); ■ Same as jsp tag: ■ Servlet Code: CustBean.getContactPerson(); ■ Same as jsp tag:
49
Chapter 949© copyright Janson Industries 2011 Java Bean Example ▮ Of course, class must have set/get methods matching the property names ▮ public String getContactPerson(){...}
50
Chapter 950© copyright Janson Industries 2011 Java Bean Sale Example When data entered into Sale.html, want to see....
51
Chapter 951© copyright Janson Industries 2011 Notice the formatting: date & time, line for each item Java Bean Sale Example...total in the Sale.jsp
52
Chapter 952© copyright Janson Industries 2011 Java Bean Sale Example ▮ Need a new class called Tx (transaction) ▮ Stores all sale info ▮ item, qty, price, customer name ▮ Calculates total $ for sale ▮ Returns receipt info (getReceipt method) ▮ The new servlets, bean, and JSPs…
53
Chapter 953© copyright Janson Industries 2011 Sale Example Sale Servlet Tx object FuncServlet TxBean User Functions.html Sale.jsp Creates Cust or Sale.html HTML (response) with receipt info Controller Model View RedirectsReceipt Info Sale info
54
Chapter 954© copyright Janson Industries 2011 Java Beans and Servlets ▮ To create the bean in Sale servlet ▮ Create a Tx object ▮ Get a Session object from the request object ▮ Define the Tx object as a session attribute ▮ TX object is a session bean
55
Chapter 955© copyright Janson Industries 2011 Tx object ▮ Need private variables for properties ▮ Then getters and setters for each property private StringBuffer custName; private StringBuffer itemName; private int qty; private double price;
56
Chapter 956© copyright Janson Industries 2011 Tx object ▮ Will overload all the setters to accept Strings public void setPrice(String d) { this.setPrice(Double.parseDouble(d));} public void setQty(String i) { this.setQty(Integer.parseInt(i));} public void setCustName(String string) { StringBuffer sb = new StringBuffer(string); this.setCustName(sb);} public void setItemName(String string) { StringBuffer sb = new StringBuffer(string); this. setItemName(sb);}
57
Chapter 957© copyright Janson Industries 2011 Java Bean Example ▮ We won’t build the getReceipt method yet ▮ Instead we’ll CALTAL ▮ Create Sale servlet to: ▮ Create Tx object and set the CustName property value (from the request) ▮ Define the bean TxBean ▮ Redirect to Sale.jsp ▮ Create Sale.jsp to ▮ Retrieve the customer name from TxBean (using tags) ▮ Display customer name
58
Chapter 958© copyright Janson Industries 2011 CALTAL Sale Tx object TxBean User Sale.jsp Creates Sale.html (with all info) HTML (response) with CustName Controller Model View CustName Sale (Servlet) Redirects
59
Chapter 959© copyright Janson Industries 2011 Java Bean Example ▮ Sale servlet: ▮ 1: Create Tx object assign to variable txBean ▮ 2: Set the CustName property ▮ 3: Define TxBean as a session bean ▮ 4: Redirect to Sale jsp import javax.servlet.http.HttpSession; Tx txBean = new Tx(); txBean.setCustName(req.getParameter("CustName")); HttpSession sess = req.getSession(); sess.setAttribute("TxBean", txBean); resp.sendRedirect("Sale.jsp"); 3: 1: 2: 3: 4:
60
Chapter 960© copyright Janson Industries 2011 Java Bean Example import java.io.IOException; : : : : : import javax.servlet.http.HttpSession; : : : : : import javax.servlet.http.HttpServletResponse; public class Sale extends HttpServlet implements Servlet { Tx txBean = new Tx(); public void doGet …{…} public void doPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException { txBean.setCustName(req.getParameter("CustName")); HttpSession sess = req.getSession(); sess.setAttribute("TxBean", txBean); resp.sendRedirect("Sale.jsp"); }
61
Chapter 961© copyright Janson Industries 2011 Java Bean Example ▮ In Sale.jsp let RAD generate bean tags to: ▮ Retrieve the cust name from TxBean ▮ Display customer name Create JSP, insert text Then click: JSP, Insert Get Property
62
Chapter 962© copyright Janson Industries 2011 Notice property name begins with a lower case letter
63
Chapter 963© copyright Janson Industries 2011
64
Chapter 964© copyright Janson Industries 2011
65
Chapter 965© copyright Janson Industries 2011 Must tie Sale.html to Sale servlet Select the form In Properties view, click action button Select servlet
66
Chapter 966© copyright Janson Industries 2011 Select Sale
67
Chapter 967© copyright Janson Industries 2011 Time to test Also, make sure Post is selected
68
Chapter 968© copyright Janson Industries 2011 Run Sale.html on server Enter a customer name Click the Submit button
69
Chapter 969© copyright Janson Industries 2011 Connections all work!! Now: Change Sale servlet to set all properties Add methods to Tx to: calc total return formatted receipt Change Sale.jsp to display receipt
70
Chapter 970© copyright Janson Industries 2011 txBean.setItemName(req.getParameter("ItemName")); txBean.setPrice(req.getParameter("Price")); txBean.setQty(req.getParameter("Qty")); ▮ Change Sale servlet to set all properties ▮ Notice Strings are passed for all parms ▮ Add function to Tx to: ▮ calc total: getTotal() ▮ return formatted receipt: getReceipt() Java Bean Example
71
Chapter 971© copyright Janson Industries 2011 Java Bean Example ▮ getTotal() not too tough public double getTotal(){ double total = price * qty * 1.06; return total; }
72
Chapter 972© copyright Janson Industries 2011 Java Bean Example ▮ getReceipt() a little more involved ▮ When this info inserted ▮ Want to see…
73
Chapter 973© copyright Janson Industries 2011 Notice the formatting: date & time, line for each item Java Bean Example
74
Chapter 974© copyright Janson Industries 2011 Java Bean Example ▮ Tx needs: ▮ Date and time formatters ▮ Currency formatter ▮ Date object ▮ Date and time properties w/ setters and getters ▮ Date and time properties must be initialized ▮ getReceipt will generate the HTML for the formatting
75
Chapter 975© copyright Janson Industries 2011 Java Bean Example ▮ Tx needs: ▮ Date and time formatters ▮ Currency formatter ▮ Date object import java.text.DateFormat; import java.text.NumberFormat; import java.util.Date; private Date d = new Date(); private DateFormat dfMedium = DateFormat.getDateInstance(DateFormat.MEDIUM); private DateFormat tfShort = DateFormat.getTimeInstance(DateFormat.SHORT); private NumberFormat cf = NumberFormat.getCurrencyInstance();
76
Chapter 976© copyright Janson Industries 2011 Java Bean Example ▮ Tx needs: ▮ Date and time properties ▮ w/ setters and getters private String date = null; private String time = null; public String getDate() { return date; } public String getTime() { return time; } private void setDate() { date = dfMedium.format(d); } private void setTime() { time = tfShort.format(d); }
77
Chapter 977© copyright Janson Industries 2011 Java Bean Example ▮ Tx needs to: ▮ Initialize the date and time properties ▮ Have a getReceipt method that generates the HTML and info in the correct formatting public Tx() { this.setDate(); this.setTime(); }
78
Chapter 978© copyright Janson Industries 2011 Java Bean Example Easiest way to generate the HTML is to create the page in Page Designer with static text and formatting
79
Chapter 979© copyright Janson Industries 2011 Then copy the HTML source into the bean and modify Java Bean Example
80
Chapter 980© copyright Janson Industries 2011 Java Bean Example public String getReceipt(){ String receipt = null; StringBuffer sb = new StringBuffer(); sb.append(" "); sb.append("TNT Salvage "); sb.append(" "); sb.append(this.getDate() + " "); sb.append(this.getTime() + " "); sb.append(" "); for (int i = 1; i <= this.getQty(); i++){ sb.append(" "); sb.append(" " + this.getItemName() + " " + cf.format(this.getPrice()) + " "); sb.append(" "); } Date/time, item name, and price inserted for static text Loop using getQty inserted Change html " to '
81
Chapter 981© copyright Janson Industries 2011 Java Bean Example sb.append(" "); sb.append(" " + " " + "Total Sale Amount: " + cf.format(this.getTotal()) + " "); sb.append(" "); sb.append(" " + this.getCustName() + " "); sb.append("Thanks for shopping with us "); sb.append(" "); receipt = String.valueOf(sb); return receipt; } Must convert sb to String and return the HTML Sub real data for static text
82
Chapter 982© copyright Janson Industries 2011 Change Sale.jsp to get receipt property and delete static text and formatting
83
Chapter 983© copyright Janson Industries 2011 Java Bean Example
84
Chapter 984© copyright Janson Industries 2011 Sale Bean Example Tx object FuncServlet TxBean Functions.html Sale.jsp Creates Cust or Sale.html HTML (response) with receipt info Controller Model View RedirectsReceipt Info Sale info User Sale (Servlet)
85
Chapter 985© copyright Janson Industries 2011 Sale Example ■ However, we have violated MVC!! ■ The TX class is creating the view ♦ getReceipt returns a web page/html – that’s the view's job! ♦ Should have a JSP get TX properties and format!
86
Chapter 986© copyright Janson Industries 2011 JSPs ▮ Will create new JSP called SaleJSP ▮ SaleJSP will get the info and format the receipt using: ▮ JSP standard action tags ▮ Bean tags
87
Chapter 987© copyright Janson Industries 2011 Sale Example Sale (Servlet) Tx object FuncServlet TxBean User Functions.html SaleJSP Creates Cust or Sale.html HTML (response) with receipt info Controller Model View RedirectsProperty values Sale info
88
Chapter 988© copyright Janson Industries 2011 JSPs ▮ Use JSP getProperty tag to access the bean ▮ Can type in the above code or use Page Designer
89
Chapter 989© copyright Janson Industries 2011 Add a table with 6 rows 1 col with static text More JSP Tags
90
Chapter 990© copyright Janson Industries 2011 Click Get Property and click 2 nd row
91
Chapter 991© copyright Janson Industries 2011 Make sure the bean type is session, then specify Bean and Property names, click OK
92
Chapter 992© copyright Janson Industries 2011 JSP tag icon displayed JSP tag result can be formatted by selecting the tag and clicking Format Then delete static text "date"
93
Chapter 993© copyright Janson Industries 2011 HTML and JSP tags that were generated
94
Chapter 994© copyright Janson Industries 2011 Time to test: Run Sale.html on server Change Sale to redirect to SaleJSP
95
Chapter 995© copyright Janson Industries 2011 More JSP Tags To test, enter info and click submit
96
Chapter 996© copyright Janson Industries 2011 More JSP Tags Need to add tags to get other properties
97
Chapter 997© copyright Janson Industries 2011 More JSP Tags
98
Chapter 998© copyright Janson Industries 2011 Now, when the above is entered:
99
Chapter 999© copyright Janson Industries 2011 There are JSTL tags that allow looping To use the bean property qty (to control the loop) the tag requires EL (Expression Language) Of course, getTotal() & getPrice should be changed to return a formatted value plus there’s no loop
100
Chapter 9100© copyright Janson Industries 2011 ▮ Create CustJSP: ▮ Access the Customer bean ▮ Display the customer info using bean tags ▮ Change Func2Servlet to create CustBean and redirect to CustJSP In class assg 2
101
Chapter 9101© copyright Janson Industries 2011 MyWeb Currently Func2 Servlet Customer object FuncServlet co Cust Servlet User Functions.html Data Cust or Sale.html Cust.html HTML (response) With Cust info Controller Model View request response co Data
102
Chapter 9102© copyright Janson Industries 2011 In class assg 2 Func2 Servlet Customer object FuncServlet CustBean User Functions.html CustJSP Creates Cust or Sale.html Cust.html HTML (response) with receipt info Controller Model View RedirectsProperty values Cust info Solution
103
Chapter 9103© copyright Janson Industries 2011 Looping with JSTL tags ■ The JSTL (Java Standard Tag Library) provides a forEach tag for looping ■ We could cheat and add to SaleJSP... html and/or content to be repeated
104
Chapter 9104© copyright Janson Industries 2011 Since there are multiple items need a at end
105
Chapter 9105© copyright Janson Industries 2011 But, of course, this will always show the item twice regardless of the qty Want to loop the qty number of times
106
Chapter 9106© copyright Janson Industries 2011 Expression Language ■ Created for easy access to beans and properties (don’t need tags) ■ Syntax is: ${beanname.property} ■ EL is part of JSP not JSTL ♦ i.e. EL can be used apart from JSTL tags ■ For example, adding the following : The item qty is: ${TxBean.qty}
107
Chapter 9107© copyright Janson Industries 2011 Then save and refresh the browser
108
Chapter 9108© copyright Janson Industries 2011 Get rid of text and EL then substitute the EL for 2 in the for each tag’s end value Results in...
109
Chapter 9109© copyright Janson Industries 2011 Save and go back in the browser and change quantity to 4 then click Submit
110
Chapter 9110© copyright Janson Industries 2011
111
Chapter 9111© copyright Janson Industries 2011 Other JSP And JSTL Tags ■ There are several useful JSP tags ♦ jsp:include – places a file’s content in a JSP ■ And JSTL tags for conditional logic ♦ body ♦ ► body ♦
112
Chapter 9112© copyright Janson Industries 2011 A file in the project (footer) has an HTML snippet that defines a footer table to appear at the bottom of every page
113
Chapter 9113© copyright Janson Industries 2011... add the include to the JSP, save the source...
114
Chapter 9114© copyright Janson Industries 2011... refresh the browser
115
Chapter 9115© copyright Janson Industries 2011 JSTL Tags and EL ▮ EL allows: ▮ Easy access to beans and implicit objects ▮ pageContext, request, response, param ▮ Implicit objects created and provided by server ▮ Use of all Java comparison operators (==,, etc.) in EL condition definition
116
Chapter 9116© copyright Janson Industries 2011 If tag and EL ▮ Allow JSP to do one thing on GET and another on POST (i.e. when the user responds) ▮ if tag with EL Display initial page with form ▮ Notice no.equals when evaluating string!
117
Chapter 9117© copyright Janson Industries 2011 JSTL if/when & EL Example
118
Chapter 9118© copyright Janson Industries 2011 ▮ Create a CustJSP2 that: ▮ Accesses CustBean bean using EL instead of getProperty bean tags ▮ Change Func2Servlet to redirect to CustJSP2 In class assg 3
119
Chapter 9119© copyright Janson Industries 2011 In class assg Func2 Servlet Customer object FuncServlet CustBean User Functions.html CustJSP2 Creates Cust or Sale.html Cust.html HTML (response) with receipt info Controller Model View RedirectsProperty values Cust info Solution
120
Chapter 9120© copyright Janson Industries 2011 ▮ Customers will be able to order from phones ▮ Of course, need the new phone app with its View ▮ But watch how much we have to change our current app to add that view New Mobile View
121
Chapter 9 121 © copyright Janson Industries 2011 User runs app on phone…
122
Chapter 9 122 © copyright Janson Industries 2011 …enters data, clicks button…
123
Chapter 9 123 © copyright Janson Industries 2011 …gets this “receipt”
124
Chapter 9124© copyright Janson Industries 2011 ▮ The phone app will send a post request (just like our web app) ▮ However, the customer name will be proceeded by the text mobilePhoneOrder: ▮ The controller (Sale) will check for the text and if it is a mobile order will simply return the total New Mobile View
125
Chapter 9125© copyright Janson Industries 2011 Web-based Sale App Sale (Servlet) Tx object FuncServlet TxBean User Functions.html SaleJSP Creates Cust or Sale.html HTML (response) with receipt info Controller Model View RedirectsProperty values Sale info
126
Chapter 9126© copyright Janson Industries 2011 Mobile Sale App Tx object PhoneSale TxBean User Sale info Creates Sale receipt Controller Model Sale info Mobile View Sale info Sale total Sale (Servlet) Sale total post request response
127
Chapter 9127© copyright Janson Industries 2011 Web/Mobile Sale App Tx object PhoneSale TxBean User Sale info SaleJSP Creates Sale receipt Sale.html HTML (response) with receipt info Controller Model Web View RedirectsProperty values Sale info Mobile View Sale info Sale total Sale (Servlet) Sale total
128
Chapter 9128© copyright Janson Industries 2011 New Mobile View import java.io.PrintWriter; : : : : : public class Sale extends HttpServlet implements Servlet { : : : : : public void doPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException { : : : : : sess.setAttribute("TxBean", TxBean); // new code for phone order view StringBuffer custNameSB = new StringBuffer(req.getParameter("CustName")); // checks if it’s a mobile phone order if (custNameSB.length() >= 17 && custNameSB.substring(0, 17).equals("mobilePhoneOrder:"))
129
Chapter 9129© copyright Janson Industries 2011 New Mobile View { // sets Customer name correctly txBean.setCustName(custNameSB.substring(17)); resp.setContentType("text/html"); try { PrintWriter out = new PrintWriter(resp.getOutputStream()); // gets the total from the bean and imbeds into the response out.println(txBean.getTotal()); out.close(); } catch (Exception e) { System.out.println("Sale Servlet failed: "); e.printStackTrace(); } } else { // its not a mobile order so invoke the web view resp.sendRedirect("SaleJSP.jsp"); }
130
Chapter 9130© copyright Janson Industries 2011 New Mobile View TxBean Phone User Creates Post request response (with Total) Controller Model View Sale info Sale (Servlet) Total Tx object ▮ Notice how in the phone architecture the view does not access the model ▮ The controller acts a buffer between the two
131
Chapter 9131© copyright Janson Industries 2011 Mobile App ▮ The Mobile App (PhoneSale) screens defined with XML ▮ For example, this is the receipt screen <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:orientation="horizontal" >
132
Chapter 9132© copyright Janson Industries 2011 Mobile App ▮ The Mobile App (PhoneSale) screens defined with XML ▮ For example, this is the receipt screen <TextView android:id="@+id/nameTV" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="TNT Salvage" /> <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:orientation="horizontal" > <TextView android:id="@+id/itemTV" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="" /> <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:orientation="horizontal" >
133
Chapter 9133© copyright Janson Industries 2011 Mobile App ▮ The Mobile App (PhoneSale) screens defined with XML ▮ For example, this is the receipt screen <TextView android:id="@+id/custTV" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="" /> <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:orientation="horizontal" > <TextView android:id="@+id/footerTV" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:text="Thanks for shopping with us" />
134
Chapter 9134© copyright Janson Industries 2011 Mobile App Java Code ▮ The Mobile App (PhoneSale) screens defined with XML ▮ For example, this is the receipt screen package com.phone.sale; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.TextView;
135
Chapter 9135© copyright Janson Industries 2011 Mobile App ▮ The Mobile App (PhoneSale) screens defined with XML ▮ For example, this is the receipt screen public class PhoneSaleActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Displays the order entry screen setContentView(R.layout.main); } // Called when button clicked public void doClick(View arg0) { // Retrieves the text specified in the EditTexts EditText custNameET = (EditText) findViewById(R.id.nameET); String custName = custNameET.getText().toString(); EditText itemNameET = (EditText) findViewById(R.id.itemET); String itemName = itemNameET.getText().toString(); EditText qtyET = (EditText) findViewById(R.id.qtyET); String qty = qtyET.getText().toString(); EditText priceET = (EditText) findViewById(R.id.priceET); String price = priceET.getText().toString(); BufferedReader in = null;
136
Chapter 9136© copyright Janson Industries 2011 Mobile App ▮ The Mobile App (PhoneSale) screens defined with XML ▮ For example, this is the receipt screen try { // Creates a client and request object HttpClient client = new DefaultHttpClient(); HttpPost request = new HttpPost( "http://sth-radsrv-01.student.fccj.org:9080/MyWeb/Sale"); // Creates a list and populates it with the entered data List postParameters = new ArrayList (); postParameters.add(new BasicNameValuePair("CustName", custName)); postParameters.add(new BasicNameValuePair("ItemName", itemName)); postParameters.add(new BasicNameValuePair("Price", price)); postParameters.add(new BasicNameValuePair("Qty", qty)); // Creates a form and ties the parameter list to the form UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity( postParameters); // Ties the form to the request request.setEntity(formEntity); // Executes the request and captures the response HttpResponse response = client.execute(request); // Creates a reader tied to the response in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
137
Chapter 9137© copyright Janson Industries 2011 Mobile App ▮ The Mobile App (PhoneSale) screens defined with XML ▮ For example, this is the receipt screen // Displays the receipt screen setContentView(R.layout.receipt); TextView itemTV = (TextView) findViewById(R.id.itemTV); // Reads the response and uses the text in the msg itemTV.setText("You've purchased " + qty + " " + itemName + "(s) for a total of $" + in.readLine()); TextView custTV = (TextView) findViewById(R.id.custTV); // Displays the customer name custTV.setText(custName); in.close(); } catch (Exception e) { e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); }
138
Chapter 9 138 © copyright Janson Industries 2011
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.