2005 Marty Hall Using Java Beans Components in
© 2005 Marty Hall Using Java. Beans Components in JSP Documents 2 JSP, Servlet, Struts, JSF & Java Training: http: //courses. coreservlets. com J 2 EE Books from Sun Press: http: //www. coreservlets. com
Agenda • • • Understanding the benefits of beans Creating beans Installing bean classes on your server Accessing bean properties Explicitly setting bean properties Automatically setting bean properties from request parameters • Sharing beans among multiple servlets and JSP pages 3 J 2 EE training: http: //courses. coreservlets. com
Uses of JSP Constructs Simple • Application • • Complex Application • 4 Scripting elements calling servlet code directly Scripting elements calling servlet code indirectly (by means of utility classes) Beans Servlet/JSP combo (MVC) MVC with JSP expression language Custom tags J 2 EE training: http: //courses. coreservlets. com
Background: What Are Beans? • 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 get. Xxx and set. Xxx • If class has method get. Title that returns a String, class is said to have a String property named title • Boolean properties use is. Xxx instead of get. Xxx – For more on beans, see http: //java. sun. com/beans/docs/ 5 J 2 EE training: http: //courses. coreservlets. com
Why You Should Use Accessors, Not Public Fields • To be a bean, you cannot have public fields • So, you should replace public double speed; • with private double speed; public double get. Speed() { return(speed); } public void set. Speed(double new. Speed) { speed = new. Speed; } • You should do this in all your Java code anyhow. Why? 6 J 2 EE training: http: //courses. coreservlets. com
Why You Should Use Accessors, Not Public Fields • 1) You can put constraints on values public void set. Speed(double new. Speed) { if (new. Speed < 0) { send. Error. Message(. . . ); new. Speed = Math. abs(new. Speed); } speed = new. Speed; } – If users of your class accessed the fields directly, then they would each be responsible for checking constraints. 7 J 2 EE training: http: //courses. coreservlets. com
Why You Should Use Accessors, Not Public Fields • 2) You can change your internal representation without changing interface // Now using metric units (kph, not mph) public void set. Speed(double new. Speed) { set. Speed. In. KPH = convert(new. Speed); } public void set. Speed. In. KPH(double new. Speed) { speed. In. KPH = new. Speed; } 8 J 2 EE training: http: //courses. coreservlets. com
Why You Should Use Accessors, Not Public Fields • 3) You can perform arbitrary side effects public double set. Speed(double new. Speed) { speed = new. Speed; update. Speedometer. Display(); } – 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. 9 J 2 EE training: http: //courses. coreservlets. com
Using Beans: Basic Tasks • jsp: use. Bean – In the simplest case, this element builds a new bean. It is normally used as follows: <jsp: use. Bean id="bean. Name" class="package. Class" /> • jsp: get. Property – This element reads and outputs the value of a bean property. It is used as follows: <jsp: get. Property name="bean. Name" property="property. Name" /> • jsp: set. Property – This element modifies a bean property (i. e. , calls a method of the form set. Xxx). It is normally used as follows: 10 <jsp: set. Property name="bean. Name" property="property. Name" value="property. Value" /> J 2 EE training: http: //courses. coreservlets. com
Building Beans: jsp: use. Bean • Format – <jsp: use. Bean id="name" class="package. Class" /> • Purpose – Allow instantiation of Java classes without explicit Java programming (XML-compatible syntax) • Notes – Simple interpretation: <jsp: use. Bean id="book 1" class="coreservlets. Book" /> can be thought of as equivalent to the scriptlet <% coreservlets. Book book 1 = new coreservlets. Book(); %> – But jsp: use. Bean has two additional advantages: • It is easier to derive object values from request parameters • It is easier to share objects among pages or servlets 11 J 2 EE training: http: //courses. coreservlets. com
Accessing Bean Properties: jsp: get. Property • Format – <jsp: get. Property name="name" property="property" /> • Purpose – Allow access to bean properties (i. e. , calls to get. Xxx methods) without explicit Java programming • Notes – <jsp: get. Property name="book 1" property="title" /> is equivalent to the following JSP expression <%= book 1. get. Title() %> 12 J 2 EE training: http: //courses. coreservlets. com
Setting Simple Bean Properties: jsp: set. Property • Format – <jsp: set. Property name="name" property="property" value="value" /> • Purpose – Allow setting of bean properties (i. e. , calls to set. Xxx methods) without explicit Java programming • Notes – <jsp: set. Property name="book 1" property="title" value="Core Servlets and Java. Server Pages" /> is equivalent to the following scriptlet <% book 1. set. Title("Core Servlets and Java. Server Pages"); %> 13 J 2 EE training: http: //courses. coreservlets. com
Example: String. Bean package coreservlets; public class String. Bean { private String message = "No message specified"; public String get. Message() { return(message); } } public void set. Message(String message) { this. message = message; } • Beans installed in normal Java directory – …/WEB-INF/classes/directory. Matching. Package. Name • Beans (and utility classes) must always be in packages! 14 J 2 EE training: http: //courses. coreservlets. com
JSP Page That Uses String. Bean (Code) <jsp: use. Bean id="string. Bean" class="coreservlets. String. Bean" /> <OL> <LI>Initial value (from jsp: get. Property): <I><jsp: get. Property name="string. Bean" property="message" /></I> <LI>Initial value (from JSP expression): <I><%= string. Bean. get. Message() %></I> <LI><jsp: set. Property name="string. Bean" property="message" value="Best string bean: Fortex" /> Value after setting property with jsp: set. Property: <I><jsp: get. Property name="string. Bean" property="message" /></I> <LI><% string. Bean. set. Message ("My favorite: Kentucky Wonder"); %> Value after setting property with scriptlet: <I><%= string. Bean. get. Message() %></I> </OL> 15 J 2 EE training: http: //courses. coreservlets. com
JSP Page That Uses String. Bean (Result) 16 J 2 EE training: http: //courses. coreservlets. com
Setting Bean Properties Case 1: Explicit Conversion & Assignment <!DOCTYPE. . . >. . . <jsp: use. Bean id="entry" class="coreservlets. Sale. Entry" /> <%-- set. Item. ID expects a String --%> <jsp: set. Property name="entry" property="item. ID" value='<%= request. get. Parameter("item. ID") %>' /> 17 J 2 EE training: http: //courses. coreservlets. com
Setting Bean Properties Case 1: Explicit Conversion & Assignment <% int num. Items. Ordered = 1; try { num. Items. Ordered = Integer. parse. Int(request. get. Parameter("num. Items")); } catch(Number. Format. Exception nfe) {} %> <%-- set. Num. Items expects an int --%> <jsp: set. Property name="entry" property="num. Items" value="<%= num. Items. Ordered %>" /> 18 J 2 EE training: http: //courses. coreservlets. com
Setting Bean Properties Case 1: Explicit Conversion & Assignment <% double discount. Code = 1. 0; try { String discount. String = request. get. Parameter("discount. Code"); discount. Code = Double. parse. Double(discount. String); } catch(Number. Format. Exception nfe) {} %> <%-- set. Discount. Code expects a double --%> <jsp: set. Property name="entry" property="discount. Code" value="<%= discount. Code %>" /> 19 J 2 EE training: http: //courses. coreservlets. com
Setting Bean Properties Case 1: Explicit Conversion & Assignment 20 J 2 EE training: http: //courses. coreservlets. com
Case 2: Associating Individual Properties with Input Parameters • Use the param attribute of jsp: set. Property to indicate that – Value should come from specified request parameter – Simple automatic type conversion should be performed for properties that expect values of standard types • boolean, Boolean, byte, Byte, char, Character, double, Double, int, Integer, float, Float, long, or Long. 21 J 2 EE training: http: //courses. coreservlets. com
Case 2: Associating Individual Properties with Input Parameters <jsp: use. Bean id="entry" class="coreservlets. Sale. Entry" /> <jsp: set. Property name="entry" property="item. ID" param="item. ID" /> <jsp: set. Property name="entry" property="num. Items" param="num. Items" /> <jsp: set. Property name="entry" property="discount. Code" param="discount. Code" /> 22 J 2 EE training: http: //courses. coreservlets. com
Case 3: Associating All Properties with Input Parameters • Use "*" for the value of the property attribute of jsp: set. Property to indicate that – Value should come from request parameter whose name matches property name – Simple automatic type conversion should be performed 23 J 2 EE training: http: //courses. coreservlets. com
Case 3: Associating All Properties with Input Parameters <jsp: use. Bean id="entry" class="coreservlets. Sale. Entry" /> <jsp: set. Property name="entry" property="*" /> • This is extremely convenient for making "form beans" -- objects whose properties are filled in from a form submission. – You can even divide the process up across multiple forms, where each submission fills in part of the object. 24 J 2 EE training: http: //courses. coreservlets. com
Sharing Beans • You can use the scope attribute to specify additional places where bean is stored – Still also bound to local variable in _jsp. Service – <jsp: use. Bean 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 25 J 2 EE training: http: //courses. coreservlets. com
Values of the scope Attribute • page (<jsp: use. Bean … scope="page"/> or <jsp: use. Bean…>) – Default value. Bean object should be placed in the Page. Context object for the duration of the current request. Lets methods in same servlet access bean • application (<jsp: use. Bean … scope="application"/>) – Bean will be stored in Servlet. Context (available through the application variable or by call to get. Servlet. Context()). Servlet. Context is shared by all servlets in the same Web application (or all servlets on server if no explicit Web applications are defined). 26 J 2 EE training: http: //courses. coreservlets. com
Values of the scope Attribute • session (<jsp: use. Bean … scope="session"/>) – Bean will be stored in the Http. Session object associated with the current request, where it can be accessed from regular servlet code with get. Attribute and set. Attribute, as with normal session objects. • request (<jsp: use. Bean … scope="request"/>) – Bean object should be placed in the Servlet. Request object for the duration of the current request, where it is available by means of get. Attribute 27 J 2 EE training: http: //courses. coreservlets. com
Conditional Bean Operations • Bean conditionally created – jsp: use. Bean 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: use. Bean. . . /> replaced by <jsp: use. Bean. . . >statements</jsp: use. Bean> – The statements (jsp: set. Property elements) are executed only if a new bean is created, not if an existing bean is found. 28 J 2 EE training: http: //courses. coreservlets. com
Conditional Bean Creation: Access. Count. Bean public class Access. Count. Bean { private String first. Page; private int access. Count = 1; public String get. First. Page() { return(first. Page); } public void set. First. Page(String first. Page) { this. first. Page = first. Page; } public int get. Access. Count() { return(access. Count); } } 29 public void set. Access. Count. Increment(int increment) { access. Count = access. Count + increment; } J 2 EE training: http: //courses. coreservlets. com
Conditional Bean Creation: Shared. Counts 1. jsp <jsp: use. Bean id="counter" class="coreservlets. Access. Count. Bean" scope="application"> <jsp: set. Property name="counter" property="first. Page" value="Shared. Counts 1. jsp" /> </jsp: use. Bean> Of Shared. Counts 1. jsp (this page), <A HREF="Shared. Counts 2. jsp">Shared. Counts 2. jsp</A>, and <A HREF="Shared. Counts 3. jsp">Shared. Counts 3. jsp</A>, <jsp: get. Property name="counter" property="first. Page" /> was the first page accessed. <P> Collectively, the three pages have been accessed <jsp: get. Property name="counter" property="access. Count" /> times. <jsp: set. Property name="counter" property="access. Count. Increment" value="1" /> 30 J 2 EE training: http: //courses. coreservlets. com
Accessing Shared. Counts 1, Shared. Counts 2, Shared. Counts 3 • Shared. Counts 2. jsp was accessed first. • Pages have been accessed twelve previous times by an arbitrary number of clients 31 J 2 EE training: http: //courses. coreservlets. com
Sharing Beans in Four Different Ways • • Using unshared (page-scoped) beans. Sharing request-scoped beans. Sharing session-scoped beans. Sharing application-scoped (i. e. , Servlet. Context-scoped) beans. • Note: – Use different names (i. e. , id in jsp: use. Bean) for different beans 32 J 2 EE training: http: //courses. coreservlets. com
Sharing Beans Four Ways: Bean Code package coreservlets; public class Baked. Bean { private String level = "half-baked"; private String goes. With = "hot dogs"; 33 } public String get. Level() { return(level); } public void set. Level(String new. Level) { level = new. Level; } public String get. Goes. With() { return(goes. With); } public void set. Goes. With(String dish) { goes. With = dish; } J 2 EE training: http: //courses. coreservlets. com
Sharing Beans Example 1: Page -Scoped (Unshared) • Create the bean – Use jsp: use. Bean with scope="page" (or no scope at all, since page is the default). • Modify the bean – Use jsp: set. Property with property="*". – Then, supply request parameters that match the bean property names. • Access the bean – Use jsp: get. Property. 34 J 2 EE training: http: //courses. coreservlets. com
Sharing Beans Example 1: Page -Scoped (Unshared) … <BODY> <H 1>Baked Bean Values: page-based Sharing</H 1> <jsp: use. Bean id="page. Bean" class="coreservlets. Baked. Bean" /> <jsp: set. Property name="page. Bean" property="*" /> <H 2>Bean level: <jsp: get. Property name="page. Bean" property="level" /> </H 2> <H 2>Dish bean goes with: <jsp: get. Property name="page. Bean" property="goes. With" /> </H 2> </BODY></HTML> 35 J 2 EE training: http: //courses. coreservlets. com
Sharing Beans Example 1: Result (Initial Request) 36 J 2 EE training: http: //courses. coreservlets. com
Sharing Beans Example 1: Result (Later Request) 37 J 2 EE training: http: //courses. coreservlets. com
Sharing Beans Example 2: Request-Based Sharing • Create the bean – Use jsp: use. Bean with scope="request". • Modify the bean – Use jsp: set. Property with property="*". – Then, supply request parameters that match the bean property names. • Access the bean in the 1 st (main) page – Use jsp: get. Property. – Then, use jsp: include to invoke the second page. • Access the bean in the 2 nd (included) page – Use jsp: use. Bean with the same id as on the first page, again with scope="request". – Then, use jsp: get. Property. 38 J 2 EE training: http: //courses. coreservlets. com
Request-Based Sharing: Code for Main Page … <BODY> <H 1>Baked Bean Values: request-based Sharing</H 1> <jsp: use. Bean id="request. Bean" class="coreservlets. Baked. Bean" scope="request" /> <jsp: set. Property name="request. Bean" property="*" /> <H 2>Bean level: <jsp: get. Property name="request. Bean" property="level" /></H 2> <H 2>Dish bean goes with: <jsp: get. Property name="request. Bean" property="goes. With" /></H 2> <jsp: include page="Baked. Bean. Display-snippet. jsp" /> </BODY></HTML> 39 J 2 EE training: http: //courses. coreservlets. com
Request-Based Sharing: Code for Included Page <H 1>Repeated Baked Bean Values: request-based Sharing</H 1> <jsp: use. Bean id="request. Bean" class="coreservlets. Baked. Bean" scope="request" /> <H 2>Bean level: <jsp: get. Property name="request. Bean" property="level" /> </H 2> <H 2>Dish bean goes with: <jsp: get. Property name="request. Bean" property="goes. With" /> </H 2> 40 J 2 EE training: http: //courses. coreservlets. com
Request-Based Sharing: Result (Initial Request) 41 J 2 EE training: http: //courses. coreservlets. com
Request-Based Sharing: Result (Later Request) 42 J 2 EE training: http: //courses. coreservlets. com
Sharing Beans Example 3: Session-Based Sharing • Create the bean – Use jsp: use. Bean with scope="session". • Modify the bean – Use jsp: set. Property with property="*". – Then, supply request parameters that match the bean property names. • Access the bean in the initial request – Use jsp: get. Property in the request in which jsp: set. Property is invoked. • Access the bean later – Use jsp: get. Property in a request that does not include request parameters and thus does not invoke jsp: set. Property. If this request is from the same client (within the session timeout), the previously modified value is seen. If this request is from a different client (or after the session timeout), a newly created bean is seen. 43 J 2 EE training: http: //courses. coreservlets. com
Session-Based Sharing: Code … <BODY> <H 1>Baked Bean Values: session-based Sharing</H 1> <jsp: use. Bean id="session. Bean" class="coreservlets. Baked. Bean" scope="session" /> <jsp: set. Property name="session. Bean" property="*" /> <H 2>Bean level: <jsp: get. Property name="session. Bean" property="level" /> </H 2> <H 2>Dish bean goes with: <jsp: get. Property name="session. Bean" property="goes. With" /> </H 2></BODY></HTML> 44 J 2 EE training: http: //courses. coreservlets. com
Session-Based Sharing: Result (Initial Request) 45 J 2 EE training: http: //courses. coreservlets. com
Session-Based Sharing: Result (Later Request -- Same Client) 46 J 2 EE training: http: //courses. coreservlets. com
Session-Based Sharing: Result (Later Request -- New Client) 47 J 2 EE training: http: //courses. coreservlets. com
Sharing Beans Example 4: Application-Based Sharing • Create the bean – Use jsp: use. Bean with scope="application". • Modify the bean – Use jsp: set. Property with property="*". – Then, supply request parameters that match the bean property names. • Access the bean in the initial request – Use jsp: get. Property in the request in which jsp: set. Property is invoked. • Access the bean later – Use jsp: get. Property in a request that does not include request parameters and thus does not invoke jsp: set. Property. Whether this request is from the same client or a different client (regardless of the session timeout), the previously modified value is seen. 48 J 2 EE training: http: //courses. coreservlets. com
Application-Based Sharing: Code <BODY> <H 1>Baked Bean Values: application-based Sharing</H 1> <jsp: use. Bean id="application. Bean" class="coreservlets. Baked. Bean" scope="application" /> <jsp: set. Property name="application. Bean" property="*" /> <H 2>Bean level: <jsp: get. Property name="application. Bean" property="level" /> </H 2> <H 2>Dish bean goes with: <jsp: get. Property name="application. Bean" property="goes. With"/> </H 2></BODY></HTML> 49 J 2 EE training: http: //courses. coreservlets. com
Application-Based Sharing: Result (Initial Request) 50 J 2 EE training: http: //courses. coreservlets. com
Application-Based Sharing: Result (Later Request -- Same Client) 51 J 2 EE training: http: //courses. coreservlets. com
Application-Based Sharing: Result (Later Request -- New Client) 52 J 2 EE training: http: //courses. coreservlets. com
Summary • Benefits of jsp: use. Bean – 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: use. Bean – Creates or accesses a bean • jsp: get. Property – Puts bean property (i. e. get. Xxx call) into servlet output • jsp: set. Property – Sets bean property (i. e. passes value to set. Xxx) 53 J 2 EE training: http: //courses. coreservlets. com
© 2005 Marty Hall Questions? 54 JSP, Servlet, Struts, JSF & Java Training: http: //courses. coreservlets. com J 2 EE Books from Sun Press: http: //www. coreservlets. com
- Slides: 53