Advanced Java Programming

Slides:



Advertisements
Similar presentations
JSP1 Java Server Pages (JSP) Introducing JavaServer Pages TM (JSP TM ) JSP scripting elements.
Advertisements

Chapter 81 JavaBeans JavaServer Pages By Xue Bai.
 Copyright Wipro Technologies JSP Ver 1.0 Page 1 Talent Transformation Java Server Pages.
Chapter 91 Scopes of Variables and JavaBeans JavaServer Pages By Xue Bai.
Chapter 51 Scripting With JSP Elements JavaServer Pages By Xue Bai.
JSP: JavaServer Pages Juan Cruz Kevin Hessels Ian Moon.
CS320 Web and Internet Programming Java Beans and Expression Language (EL) Chengyu Sun California State University, Los Angeles.
DT228/3 Web Development Java Beans. Intro A major problem with JSP is tendency to mix java code with HTML  -  web designer write the HTML and programmer.
ASP.NET Programming with C# and SQL Server First Edition
Java Enterprise Edition Java Web Development Structure of a web project Introduction to Web Applications The first project Introduction to Java Web Development.
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.
Using JavaBeans Components in JSP Documents. Contents 1. Why using beans? 2. What are beans? 3. Using Beans: Basic Tasks 4. Sharing Beans 5. Practice.
1 Chapter 2 The Web Tier  Web Applications and Web ContainersWeb Applications and Web Containers  Dynamic Content CreationDynamic Content Creation 
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.
Introduction to JSP Based on: Marty Hall, Larry Brown, Core Servlets and JavaServer Pages.
What Are Beans? beans are simply Java classes that are written in a standard format. A bean class must have a zero-argument (default) constructor. A bean.
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)
Jordan Anastasiade. All rights reserved.
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,
Mark Dixon 1 12 – Java Beans. Mark Dixon 2 Session Aims & Objectives Aims –To cover the use of Java Beans Objectives, by end of this week’s sessions,
JAVA SERVER PAGES CREATING DYNAMIC WEB PAGES USING JAVA James Faeldon CS 119 Enterprise Systems Programming.
Slides © Marty Hall, book © Sun Microsystems Press 1 JSP Scripting Elements Core Servlets & JSP book:
16-Oct-15 JSP Implicit Objects. 2 JSP Implicit Objects are the Java objects that the JSP Container makes available to developers in each page and developer.
Fall 2007cs4201 Advanced Java Programming Umar Kalim Dept. of Communication Systems Engineering
CS320 Web and Internet Programming Java Beans and Expression Language (EL) Chengyu Sun California State University, Los Angeles.
Writing Enterprise Applications with J2EE (Fourth lesson) Alessio Bechini June 2002 (based on material by Monica Pawlan)
J2EE training: 1 Course Material Usage Rules PowerPoint slides for use only in full-semester, for-credit courses at degree-granting.
Java Server Pages (JSP) Provide a cross-platform framework for creating dynamic web contents JSP Components: Static HTML/XML parts Special JSP Tags Snippets.
JSP Tag Libraries Lec Last Lecture Example We incorporated JavaBeans in “Course Outline” Example But still have to write java code inside java.jsp.
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.
Fall 2007cs4201 Advanced Java Programming Umar Kalim Dept. of Communication Systems Engineering
1 Processing phase Translation phase JSP page translation and processing phases Client Server Request Response Hello.jsp helloServlet.class helloServlet.java.
CourseOutline Example & JavaBeans Lec Start with Example Displaying Course Outlines User will select either course “web design & development” or.
Web Technologies Java Beans & JSP By Praveen Kumar G.
Slides © Marty Hall, book © Sun Microsystems Press 1 Using JavaBeans with JSP Core Servlets & JSP book:
JSP BASICS AND ARCHITECTURE. Goals of JSP Simplify Creation of dynamic pages. Separate Dynamic and Static content.
COMP9321 Web Application Engineering Semester 2, 2015 Dr. Amin Beheshti Service Oriented Computing Group, CSE, UNSW Australia Week 3 1COMP9321, 15s2, Week.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 43 JavaServer Page.
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.
1 Chapter 27 JavaServer Page. 2 Objectives F To know what is a JSP page is processed (§27.2). F To comprehend how a JSP page is processed (§27.3). F To.
INVOKING JAVA CODE WITH JSP SCRIPTING ELEMENTS. Creating Template Text A large percentage of your JSP document consists of static text (usually HTML),
Chapter 6 Chapter 6 Server Side Programming (JSP) Part 1 1 (IS 203) WebProgramming (IS 203) Web Programming.
Java Programming: Advanced Topics 1 Building Web Applications Chapter 13.
JSP in Action. JSP Standard Actions forward, include, useBean, setProperty, getProperty, text, element, and plugin Additional actions param, params,
Chapter 14 Using JavaBeans Components in JSP Documents.
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.
JSP Java Server Pages. Hello, !
Introduction to Server-Side Web Development Introduction to Server-Side Web Development Introduction to Server-Side Web JavaBeans; basic concepts and syntax.
JSP Action Elements Lec - 37.
JSP java server pages.
Java Server Pages By: Tejashri Udavant..
Scripted Page Web App Development (Java Server Pages)
USING JAVABEANS COMPONENTS IN JSP DOCUMENTS K. Phani Sirisha
Scope and State Handling in JSPs
Pre-assessment Questions
JavaBeans and JSP CS-422.
Introduction to Java Bean
Invoking Java Code from JSP
Java Server Pages JSP 11/11/2018.
Introduction to Java Bean
Java Server Pages B.Ramamurthy.
CS320 Web and Internet Programming Java Beans
Scope and State Handling in Java Server Pages
Introduction to JSP Dept. of B.Voc Software Development and System Administration St. Joseph’s College(Autonomous) Trichy-02 By Dr. J. Ronald Martin Introduction.
Scripted Page Web Application Development (Java Server Pages)
Web Technologies Java Beans & JSP
Presentation transcript:

Advanced Java Programming Umar Kalim Dept. of Communication Systems Engineering umar.kalim@niit.edu.pk http://www.niit.edu.pk/~umarkalim 12/12/2007 Fall 2007 cs420

Agenda JavaBeans for JSP Reference www.javapassion.com/j2ee coreservlets.com Fall 2007 cs420

What are JavaBeans? Java classes that can be easily reused and composed together into an application Any Java class that follows certain design conventions can be a JavaBeans component properties of the class public methods to get and set properties Within a JSP page, you can create and initialize beans and get and set the values of their properties JavaBeans can contain business logic or data base access logic JavaBeans components are Java classes that can be easily reused and composed together into applications. Any Java class that follows certain design conventions can be a JavaBeans component. JavaBeans component design conventions govern the properties of the class and govern the public methods that give access to the properties. JavaServer Pages technology directly supports using JavaBeans components with JSP language elements. You can easily create and initialize beans and get and set the values of their properties And JavaBeans can contain business logic or database access logic.

JavaBeans Design Conventions JavaBeans maintain internal properties A property can be Read/write, read-only, or write-only Simple or indexed A JavaBeans component property can be * Read/write, read-only, or write-only * Simple, which means it contains a single value, or indexed, which means it represents an array of values There is no requirement that a property be implemented by an instance variable; the property must simply be accessible using public methods that conform to certain conventions: * For each readable property, the bean must have a method of the form PropertyClass getProperty() { ... } * For each writable property, the bean must have a method of the form setProperty(PropertyClass pc) { ... } In addition to the property methods, a JavaBeans component must define a constructor that takes no parameters. If there are no other constructors, no arg constructor is automatically generated.

What are JavaBeans Java classes that follow certain conventions Must have a zero-argument (empty) constructor You can satisfy this requirement either by explicitly defining such a constructor or by omitting all constructors Should have no public instance variables (fields) I hope you already follow this practice and use accessor methods instead of allowing direct access to fields Persistent values should be accessed through methods called getXxx and setXxx If class has method getTitle that returns a String, class is said to have a String property named title Boolean properties use isXxx instead of getXxx For more on beans, see http://java.sun.com/beans/docs/ Fall 2007 cs420

Why to use accessor methods? To be a bean, you cannot have public fields So, you should replace public double speed; with private double speed; public double getSpeed() { return(speed); } public void setSpeed(double newSpeed) { speed = newSpeed; You should do this in all your Java code anyhow. Why? Fall 2007 cs420

Why to use accessor methods? You can put constraints on values public void setSpeed(double newSpeed) { if (newSpeed < 0) { sendErrorMessage(...); newSpeed = Math.abs(newSpeed); } speed = newSpeed; If users of your class accessed the fields directly, then they would each be responsible for checking constraints. Fall 2007 cs420

Why to use accessor methods? You can change your internal representation without changing interface // Now using metric units (kph, not mph) public void setSpeed(double newSpeed) { setSpeedInKPH = convert(newSpeed); } public void setSpeedInKPH(double newSpeed) { speedInKPH = newSpeed; Fall 2007 cs420

Why to use accessor methods? You can perform arbitrary side effects public double setSpeed(double newSpeed) { speed = newSpeed; updateSpeedometerDisplay(); } If users of your class accessed the fields directly, then they would each be responsible for executing side effects. Too much work and runs huge risk of having display inconsistent from actual values. Fall 2007 cs420

Example: JavaBeans public class Currency { private Locale locale; private double amount; public Currency() { locale = null; amount = 0.0; } public void setLocale(Locale l) { locale = l; public void setAmount(double a) { amount = a; public String getFormat() { NumberFormat nf = NumberFormat.getCurrencyInstance(locale); return nf.format(amount); In the BookStore application, the JSP pages catalog.jsp, showcart.jsp, and cashier.jsp use the util.Currency JavaBeans component to format currency in a locale-sensitive manner. The bean has two writable properties, locale and amount, and one readable property, format. The format property does not correspond to any instance variable, but returns a function of the locale and amount properties.

Why Use JavaBeans in JSP Page? A JSP page can create and use any type of Java programming language object within a declaration or scriptlet like following: <% ShoppingCart cart = (ShoppingCart)session.getAttribute("cart"); // If the user has no cart, create a new one if (cart == null) { cart = new ShoppingCart(); session.setAttribute("cart", cart); } %> Now do we care about JavaBeans in the context of JSP? As was mentioned, a JSP page can create and use any type of Java programming language object within a declaration or scriptlet. The scriptlet above creates the bookstore shopping cart and stores it as a session attribute.

Why Use JavaBeans in JSP Page? JSP pages can use JSP elements to create and access the object that conforms to JavaBeans conventions <jsp:useBean id="cart“ class="cart.ShoppingCart“ scope="session"/> Create an instance of “ShoppingCart” if none exists, stores it as an attribute of the session scope object, and makes the bean available throughout the session by the identifier “cart” If the shopping cart object in the precious page conforms to JavaBeans conventions, JSP pages can use JSP elements to create and access the object. For example, the Duke's Bookstore pages bookdetails.jsp, catalog.jsp, and showcart.jsp replace the scriptlet with the much more concise JSP useBean element:

Compare the Two <% ShoppingCart cart = (ShoppingCart)session.getAttribute("cart"); // If the user has no cart object as an attribute in Session scope // object, then create a new one. Otherwise, use the existing // instance. if (cart == null) { cart = new ShoppingCart(); session.setAttribute("cart", cart); } %> versus <jsp:useBean id="cart" class="cart.ShoppingCart“ scope="session"/> Now compare the two JSP codes. As you can tell JavaBeans based JSP code is a lot more simpler and easy to understand and would be easier to maintain. In other words, for web page authors, using JavaBeans syntax is a lot easier than writing Java code.

Why Use JavaBeans in JSP Page? No need to learn Java programming language for page designers Stronger separation between content and presentation Higher re usability of code Simpler object sharing through built-in sharing mechanism Convenient matching between request parameters and object properties So just to summarize why you want to use JavaBeans over pure Java code, there are several reasons. First, page authors do not have to know Java programming language in order to use JavaBeans in JSP page because usage syntax of JavaBeans is very simple. Because content generation or business logic is captured in the form of JavaBeans component, it provides a stronger separation between content and presentation. And a single JavaBean can be in fact reusable in other JSP pages. JavaBeans also make it easier to share objects among multiple JSP pages or between requests. Finally JavaBeans greatly simplify the process of reading request parameters, converting from strings, and stuffing the resuts inside objects.

Using Beans - Basics jsp:useBean jsp:getProperty jsp:setProperty In the simplest case, this element builds a new bean. It is normally used as follows: <jsp:useBean id="beanName" class="package.Class" /> jsp:getProperty This element reads and outputs the value of a bean property. It is used as follows: <jsp:getProperty name="beanName“ property="propertyName" /> jsp:setProperty This element modifies a bean property (i.e., calls a method of the form setXxx). It is normally used as follows: <jsp:setProperty name=“beanName” property=“propertyName“ value="propertyValue" /> Fall 2007 cs420

Instantiating Beans - jsp:useBean Format <jsp:useBean id="name" class="package.Class" /> Purpose Allow instantiation of Java classes without explicit Java programming (XML-compatible syntax) Notes Simple interpretation: <jsp:useBean id="book1" class="coreservlets.Book" /> can be thought of as equivalent to the scriptlet <% coreservlets.Book book1 = new coreservlets.Book(); %> But jsp:useBean has two additional advantages: It is easier to derive object values from request parameters It is easier to share objects among pages or servlets Fall 2007 cs420

Accessing Properties - jsp:getProperty Format <jsp:getProperty name="name" property="property" /> Purpose Allow access to bean properties (i.e., calls to getXxx methods) without explicit Java programming Notes <jsp:getProperty name="book1" property="title" /> is equivalent to the following JSP expression <%= book1.getTitle() %> Fall 2007 cs420

Setting Properties - jsp:setProperty Format <jsp:setProperty name="name“ property="property“ value="value" /> Purpose Allow setting of bean properties (i.e., calls to setXxx methods) without explicit Java programming Notes <jsp:setProperty name="book1“ property="title“ value="Core Servlets and JavaServer Pages" /> is equivalent to the following scriptlet <% book1.setTitle("Core Servlets and JavaServer Pages"); %> Fall 2007 cs420

Deployment Beans installed in normal Java directory …/WEB-INF/classes/directoryMatchingPackageName Beans (and utility classes) must always be in packages! Fall 2007 cs420

Example Bean Fall 2007 cs420

Example JSP page <jsp:useBean id="stringBean“ class="coreservlets.StringBean" /> <OL> <LI>Initial value (from jsp:getProperty): <I> <jsp:getProperty name="stringBean“ property="message" /> </I> <LI>Initial value (from JSP expression): <I><%= stringBean.getMessage() %></I> <LI> <jsp:setProperty name="stringBean“ property="message" value="Best string bean: Fortex" /> Value after setting property with jsp:setProperty: <jsp:getProperty name="stringBean“ property="message" /></I> <% stringBean.setMessage ("My favorite: Kentucky Wonder"); %> Value after setting property with scriptlet: </OL> Fall 2007 cs420

Output Fall 2007 cs420

Setting JavaBeans Properties jsp:setProperty syntax depends on the source of the property <jsp:setProperty name="beanName" property="propName" value="string constant"/> <jsp:setProperty name="beanName" property="propName" param="paramName"/> <jsp:setProperty name="beanName" property="propName"/> <jsp:setProperty name="beanName" property="*"/> <jsp:setProperty name="beanName" property="propName" value="<%= expression %>"/> The syntax of setting JavaBeans properties depends on the source of the property. (add more explanation here)‏

Example: jsp:setProperty with Request parameter <jsp:setProperty name="bookDB" property="bookId"/> is same as <% //Get the identifier of the book to display String bookId = request.getParameter("bookId"); bookDB.setBookId(bookId); ... %> The Duke's Bookstore application demonstrates how to use the setProperty element and a scriptlet to set the current book for the database helper bean. For example, bookstore3/web/bookdetails.jsp uses the form: <jsp:setProperty name="bookDB" property="bookId"/> whereas bookstore2/web/bookdetails.jsp uses the form: <% bookDB.setBookId(bookId); %>

Example: jsp:setProperty with Expression <jsp:useBean id="currency" class="util.Currency" scope="session"> <jsp:setProperty name="currency" property="locale“ value="<%= request.getLocale() %>"/> </jsp:useBean> <jsp:setProperty name="currency" property="amount" value="<%=cart.getTotal()%>"/> The above fragments from the page bookstore3/web/showcart.jsp(of Java WSDP) illustrate how to initialize a currency bean with a Locale object and amount determined by evaluating request-time expressions. Because the first initialization is nested in a useBean element, it is only executed when the bean is created.

Getting JavaBeans Properties 2 different ways to get a property of a bean Convert the value of the property into a String and insert the value into the current implicit “out” object Retrieve the value of a property without converting it to a String and inserting it into the “out” object There are two ways to get JavaBeans component properties in a JSP page: with the jsp:setProperty element or with a scriptlet

Getting JavaBeans Properties & and Convert into String and insert into out 2 ways via scriptlet <%= beanName.getPropName() %> via JSP:setProperty <jsp:getProperty name="beanName" property="propName"/> Requirements “beanName” must be the same as that specified for the id attribute in a useBean element There must be a “getPropName()” method in a bean There are several ways to retrieve JavaBeans component properties. Two of the methods (the jsp:getProperty element and an expression) convert the value of the property into a String and insert the value into the current implicit out object: * <jsp:getProperty name="beanName" property="propName"/> * <%= beanName.getPropName() %> For both methods, beanName must be the same as that specified for the id attribute in a useBean element, and there must be a getPropName method in the JavaBeans component.

Getting JavaBeans Properties without Converting it to String Must use a scriptlet Format <% Object o = beanName.getPropName(); %> Example <% // Print a summary of the shopping cart int num = cart.getNumberOfItems(); if (num > 0) { %> If you need to retrieve the value of a property without converting it and inserting it into the out object, you must use a scriptlet: <% Object o = beanName.getPropName(); %> Note the differences between the expression and the scriptlet; the expression has an = after the opening % and does not terminate with a semicolon, as does the scriptlet.

Sharing Beans You can use the scope attribute to specify additional places where bean is stored Still also bound to local variable in _jspService <jsp:useBean id="…" class="…” scope="…" /> Lets multiple servlets or JSP pages share data Also permits conditional bean creation Creates new object only if it can't find existing one Fall 2007 cs420

Scope Attribute page (<jsp:useBean … scope="page"/> or <jsp:useBean…>) Default value. Bean object should be placed in the PageContext object for the duration of the current request. Lets methods in same servlet access bean Application (<jsp:useBean … scope="application"/>) Bean will be stored in ServletContext (available through the application variable or by call to getServletContext()). ServletContext is shared by all servlets in the same Web application (or all servlets on server if no explicit Web applications are defined). Fall 2007 cs420

Scope Attribute page (<jsp:useBean … scope="page"/> or <jsp:useBean…>) Default value. Bean object should be placed in the PageContext object for the duration of the current request. Lets methods in same servlet access bean Application (<jsp:useBean … scope="application"/>) Bean will be stored in ServletContext (available through the application variable or by call to getServletContext()). ServletContext is shared by all servlets in the same Web application (or all servlets on server if no explicit Web applications are defined). Fall 2007 cs420

Scope Attribute session (<jsp:useBean … scope="session"/>) Bean will be stored in the HttpSession object associated with the current request, where it can be accessed from regular servlet code with getAttribute and setAttribute, as with normal session objects. request (<jsp:useBean … scope="request"/>) Bean object should be placed in the ServletRequest object for the duration of the current request, where it is available by means of getAttribute Fall 2007 cs420

Conditional Bean Operations Bean conditionally created jsp:useBean results in new bean being instantiated only if no bean with same id and scope can be found. If a bean with same id and scope is found, the preexisting bean is simply bound to variable referenced by id. Bean properties conditionally set <jsp:useBean ... /> replaced by <jsp:useBean ...>statements</jsp:useBean> The statements (jsp:setProperty elements) are executed only if a new bean is created, not if an existing bean is found. Fall 2007 cs420

Example <jsp:useBean id="counter“ class="coreservlets.AccessCountBean" scope="application"> <jsp:setProperty name="counter“ property="firstPage" value="SharedCounts1.jsp" /> </jsp:useBean> Of SharedCounts1.jsp (this page), <A HREF="SharedCounts2.jsp">SharedCounts2.jsp</A>, and <A HREF="SharedCounts3.jsp">SharedCounts3.jsp</A>, <jsp:getProperty name="counter" property="firstPage" /> was the first page accessed. <P> Collectively, the three pages have been accessed <jsp:getProperty name="counter" property="accessCount" /> times. <jsp:setProperty name="counter“ property="accessCountIncrement“ value="1" /> Fall 2007 cs420

Summary Benefits of jsp:useBean jsp:useBean jsp:getProperty Hides the Java syntax Makes it easier to associate request parameters with Java objects (bean properties) Simplifies sharing objects among multiple requests or servlets/JSPs jsp:useBean Creates or accesses a bean jsp:getProperty Puts bean property (i.e. getXxx call) into servlet output jsp:setProperty Sets bean property (i.e. passes value to setXxx) Fall 2007 cs420

Summary & Questions? That’s all for today! Fall 2007 cs420