Presentation is loading. Please wait.

Presentation is loading. Please wait.

Advanced Java Programming

Similar presentations


Presentation on theme: "Advanced Java Programming"— Presentation transcript:

1 Advanced Java Programming
Umar Kalim Dept. of Communication Systems Engineering 12/12/2007 Fall 2007 cs420

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

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

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

5 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 Fall 2007 cs420

6 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

7 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

8 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

9 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

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

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

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

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

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

15 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

16 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

17 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

18 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

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

20 Example Bean Fall 2007 cs420

21 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

22 Output Fall 2007 cs420

23 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)‏

24 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); %>

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

26 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

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

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

29 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

30 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

31 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

32 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

33 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

34 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

35 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

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


Download ppt "Advanced Java Programming"

Similar presentations


Ads by Google