Chapter 91© copyright Janson Industries 2011 Java Design Concepts ■ JSP’s ■ MVC MVC ■ Beans Beans ■ JSP Tags JSP Tags.

Slides:



Advertisements
Similar presentations
8 Copyright © 2005, Oracle. All rights reserved. Creating the Web Tier: JavaServer Pages.
Advertisements

JSP1 Java Server Pages (JSP) Introducing JavaServer Pages TM (JSP TM ) JSP scripting elements.
 Copyright Wipro Technologies JSP Ver 1.0 Page 1 Talent Transformation Java Server Pages.
DT211/3 Internet Application Development
18-Jun-15 JSP Java Server Pages Reference: Tutorial/Servlet-Tutorial-JSP.html.
JSP Java Server Pages Reference:
DT228/3 Web Development JSP: Directives and Scripting elements.
Q: According to Intel, the Pentium conforms to the IEEE standards 754 and 854 for floating point arithmetic. If you fly in aircraft designed using a Pentium,
JSP Architecture  JSP is a simple text file consisting of HTML or XML content along with JSP elements  JSP packages define the interface for the compiled.
Introduction to Java web programming Dr Jim Briggs JWP intro1.
Gayle J Yaverbaum, PhD Professor of Information Systems Penn State Harrisburg.
Struts 2.0 an Overview ( )
Form Handling, Validation and Functions. Form Handling Forms are a graphical user interfaces (GUIs) that enables the interaction between users and servers.
DAT602 Database Application Development Lecture 15 Java Server Pages Part 1.
Chapter 10 EJB Concepts of EJB Three Components in Creating an EJB Starting/Stopping J2EE Server and Deployment Tool Installation and Configuration of.
1 CIS336 Website design, implementation and management (also Semester 2 of CIS219, CIS221 and IT226) Lecture 9 JavaServer Pages (JSP) (Based on Møller.
CSC 2720 Building Web Applications Using Java Beans, Custom Tags and Tag Libraries in JSP pages.
1 Mobile Computing Monetizing An App Copyright 2014 by Janson Industries.
Using JavaBeans and Custom Tags in JSP Lesson 3B / Slide 1 of 37 J2EE Web Components Pre-assessment Questions 1.The _____________ attribute of a JSP page.
Chapter 111© copyright Janson Industries 2011 Custom Tags ▮ Tag Handlers ▮ XML ▮ Tag Libraries ▮ Web Deployment Descriptor.
JSP Java Server Pages Softsmith Infotech.
Introduction to Java Server Pages (JSPs) Robert Thornton.
Chapter 7 Java Server Pages. Objectives Explain how the separation of concerns principle applies to JSP Describe the operation and life-cycle of a JSP.
Introduction to JavaServer Pages (JSP) Slides from Dr. Mark Llewellyn.
Java Server Pages Lecture July Java Server Pages Java Server Pages (JSPs) provide a way to separate the generation of dynamic content (java)
Java Server Pages A JSP page is a text-based document that contains two types of text: static template data, which can be expressed in any text-based format,
 Embeds Java code  In HTML tags  When used well  Simple way to generate dynamic web-pages  When misused (complex embedded Java)  Terribly messy.
COMP 321 Week 7. Overview HTML and HTTP Basics Dynamic Web Content ServletsMVC Tomcat in Eclipse Demonstration Lab 7-1 Introduction.
Chapter 8 Script-free pages. Problem with scripting in JSP When you use scripting (declaration, scriplet, expressions) in your JSP, you actually put Java.
JSP Most of the web developers deploying web applications using servlets mixes the presentation logic and business logic. Separation of business logic.
JAVA SERVER PAGES. 2 SERVLETS The purpose of a servlet is to create a Web page in response to a client request Servlets are written in Java, with a little.
JAVA SERVER PAGES CREATING DYNAMIC WEB PAGES USING JAVA James Faeldon CS 119 Enterprise Systems Programming.
Chapter 3 Servlet Basics. 1.Recall the Servlet Role 2.Basic Servlet Structure 3.A simple servlet that generates plain text 4.A servlet that generates.
Mark Dixon 1 09 – Java Servlets. Mark Dixon 2 Session Aims & Objectives Aims –To cover a range of web-application design techniques Objectives, by end.
 Whether using paper forms or forms on the web, forms are used for gathering information. User enter information into designated areas, or fields. Forms.
SE-2840 Dr. Mark L. Hornick 1 Java Server Pages. HTML/JSPs are intended to be used as the views in an MVC- based web application Model – represents an.
Writing Enterprise Applications with J2EE (Fourth lesson) Alessio Bechini June 2002 (based on material by Monica Pawlan)
JSP Fundamentals Elements of a JSP Using Beans with JSP Integrating Servlets and JSP.
CSC 2720 Building Web Applications JavaServer Pages (JSP) The Basics.
Java server pages. A JSP file basically contains HTML, but with embedded JSP tags with snippets of Java code inside them. A JSP file basically contains.
Copyright © 2002 ProsoftTraining. All rights reserved. JavaServer Pages.
Java Server Pages (JSP)
Java Server Pages An introduction to JSP. Containers and Components Several clients – one system.
CS-4220 Dr. Mark L. Hornick 1 Java Server Pages. HTML/JSPs are intended to be used as the views in an MVC- based web application Model – represents an.
OOSSE Week 8 JSP models Format of lecture: Assignment context JSP models JSPs calling other JSPs i.e. breaking up work Parameter passing JSPs with Add.
JSP BASICS AND ARCHITECTURE. Goals of JSP Simplify Creation of dynamic pages. Separate Dynamic and Static content.
Mark Dixon 1 11 – Java Servlets. Mark Dixon 2 Session Aims & Objectives Aims –To cover a range of web-application design techniques Objectives, by end.
CS562 Advanced Java and Internet Application Introduction to the Computer Warehouse Web Application. Java Server Pages (JSP) Technology. By Team Alpha.
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 JSP Application Models.
Basic JSP Celsina Bignoli Problems with Servlets Servlets contain –request processing, –business logic –response generation all lumped.
COMP9321 Web Application Engineering Semester 2, 2015 Dr. Amin Beheshti Service Oriented Computing Group, CSE, UNSW Australia Week 3 1COMP9321, 15s2, Week.
8 Chapter Eight Server-side Scripts. 8 Chapter Objectives Create dynamic Web pages that retrieve and display database data using Active Server Pages Process.
©SoftMoore ConsultingSlide 1 Overview of Servlets and JavaServer Pages (JSP)
Chapter 12© copyright Janson Industries Java Server Faces ▮ Explain the JSF framework ▮ SDO (service data objects) ▮ Facelets ▮ Pagecode classes.
1 Java Server Pages A Java Server Page is a file consisting of HTML or XML markup into which special tags and code blocks are inserted When the page is.
Chapter 6 Chapter 6 Server Side Programming (JSP) Part 1 1 (IS 203) WebProgramming (IS 203) Web Programming.
 Java Server Pages (JSP) By Offir Golan. What is JSP?  A technology that allows for the creation of dynamically generated web pages based on HTML, XML,
Java Programming: Advanced Topics 1 Building Web Applications Chapter 13.
Java Server Pages. 2 Servlets The purpose of a servlet is to create a Web page in response to a client request Servlets are written in Java, with a little.
Bayu Priyambadha, S.Kom. Static content  Web Server delivers contents of a file (html) 1. Browser sends request to Web Server 3. Web Server sends HTML.
10 Copyright © 2004, Oracle. All rights reserved. Building ADF View Components.
Spell Checker web service (you build a web client that interacts with the service) The client uses a servlet class and a JSP page. The user passes information.
A Presentation Presentation On JSP On JSP & Online Shopping Cart Online Shopping Cart.
JSP (Java Server Page) JSP is server side technology which is used to create dynamic web pages just like Servlet technology. This is mainly used for implementing.
Scripted Page Web App Development (Java Server Pages)
Intro to PHP & Variables
In Class Assg 4 - Solution
In Class Assg 3 - Solution
In Class Assg 2 - solution
© copyright Janson Industries 2011
Presentation transcript:

Chapter 91© copyright Janson Industries 2011 Java Design Concepts ■ JSP’s ■ MVC MVC ■ Beans Beans ■ JSP Tags JSP Tags

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

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

Chapter 94© copyright Janson Industries 2011 Java Statement Tags ▮ Java scriptlet syntax: ▮ Java expression syntax: ▮ Java declaration syntax: ▮ Java directive syntax:

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

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:

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!”); }

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

Chapter 99© copyright Janson Industries 2011 Initial code inserted by RAD

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

Chapter 911© copyright Janson Industries 2011 Do same using JSP tags not Java Statement tags Solution

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

Chapter 913© copyright Janson Industries 2011 So, really, the advantage to JSP’s is ease of construction for the programmer

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

Chapter 915© copyright Janson Industries 2011 JSP But using Computer you can drill into the server and find it

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

© copyright Janson Industries 2011Chapter 917 Insert this text RAD JSP

Chapter 918© copyright Janson Industries 2011 To Insert a Scriptlet, position cursor on page, click JSP, Insert Scriptlet

Chapter 919© copyright Janson Industries 2011 Display the Properties view of the Scriptlet

Chapter 920© copyright Janson Industries 2011 In properties pane specify Java code In this example, inserted the beginning of a loop

Chapter 921© copyright Janson Industries 2011 Insert another scriptlet with the rest of the for loop

Chapter 922© copyright Janson Industries 2011 Run on the server Should have a tag to insert a line in each loop

© copyright Janson Industries 2011Chapter 923 RAD JSP Save the code

Chapter 924© copyright Janson Industries 2011 Refresh the browser

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

Chapter 926© copyright Janson Industries 2011 JSP In Class Assg ▮ Create a JSP that uses a loop to print the system date five times

Chapter 927© copyright Janson Industries 2011 Java Design Concepts ■ MVC design pattern for server-based applications ♦ Model ♦ View ♦ Controller

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

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

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

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 View cust Client App MVC Example data 7 ViewController

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

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

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

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

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

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

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

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

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

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)

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

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

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

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:

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

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

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:

Chapter 949© copyright Janson Industries 2011 Java Bean Example ▮ Of course, class must have set/get methods matching the property names ▮ public String getContactPerson(){...}

Chapter 950© copyright Janson Industries 2011 Java Bean Sale Example When data entered into Sale.html, want to see....

Chapter 951© copyright Janson Industries 2011 Notice the formatting: date & time, line for each item Java Bean Sale Example...total in the Sale.jsp

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…

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

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

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;

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

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

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

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:

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

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

Chapter 962© copyright Janson Industries 2011 Notice property name begins with a lower case letter

Chapter 963© copyright Janson Industries 2011

Chapter 964© copyright Janson Industries 2011

Chapter 965© copyright Janson Industries 2011 Must tie Sale.html to Sale servlet Select the form In Properties view, click action button Select servlet

Chapter 966© copyright Janson Industries 2011 Select Sale

Chapter 967© copyright Janson Industries 2011 Time to test Also, make sure Post is selected

Chapter 968© copyright Janson Industries 2011 Run Sale.html on server Enter a customer name Click the Submit button

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

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

Chapter 971© copyright Janson Industries 2011 Java Bean Example ▮ getTotal() not too tough public double getTotal(){ double total = price * qty * 1.06; return total; }

Chapter 972© copyright Janson Industries 2011 Java Bean Example ▮ getReceipt() a little more involved ▮ When this info inserted ▮ Want to see…

Chapter 973© copyright Janson Industries 2011 Notice the formatting: date & time, line for each item Java Bean Example

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

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

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

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

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

Chapter 979© copyright Janson Industries 2011 Then copy the HTML source into the bean and modify Java Bean Example

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 '

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

Chapter 982© copyright Janson Industries 2011 Change Sale.jsp to get receipt property and delete static text and formatting

Chapter 983© copyright Janson Industries 2011 Java Bean Example

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)

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!

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

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

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

Chapter 989© copyright Janson Industries 2011 Add a table with 6 rows 1 col with static text More JSP Tags

Chapter 990© copyright Janson Industries 2011 Click Get Property and click 2 nd row

Chapter 991© copyright Janson Industries 2011 Make sure the bean type is session, then specify Bean and Property names, click OK

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"

Chapter 993© copyright Janson Industries 2011 HTML and JSP tags that were generated

Chapter 994© copyright Janson Industries 2011 Time to test: Run Sale.html on server Change Sale to redirect to SaleJSP

Chapter 995© copyright Janson Industries 2011 More JSP Tags To test, enter info and click submit

Chapter 996© copyright Janson Industries 2011 More JSP Tags Need to add tags to get other properties

Chapter 997© copyright Janson Industries 2011 More JSP Tags

Chapter 998© copyright Janson Industries 2011 Now, when the above is entered:

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

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

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

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

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

Chapter 9104© copyright Janson Industries 2011 Since there are multiple items need a at end

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

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}

Chapter 9107© copyright Janson Industries 2011 Then save and refresh the browser

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...

Chapter 9109© copyright Janson Industries 2011 Save and go back in the browser and change quantity to 4 then click Submit

Chapter 9110© copyright Janson Industries 2011

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 ♦

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

Chapter 9113© copyright Janson Industries add the include to the JSP, save the source...

Chapter 9114© copyright Janson Industries refresh the browser

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

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!

Chapter 9117© copyright Janson Industries 2011 JSTL if/when & EL Example

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

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

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

Chapter © copyright Janson Industries 2011 User runs app on phone…

Chapter © copyright Janson Industries 2011 …enters data, clicks button…

Chapter © copyright Janson Industries 2011 …gets this “receipt”

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

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

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

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

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:"))

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

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

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=" 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" >

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: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: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" >

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: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:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:text="Thanks for shopping with us" />

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;

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

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( " // 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()));

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

Chapter © copyright Janson Industries 2011