Using JavaBeans
in JSP
Agenda
• Creating beans
• Installing bean classes on your server
• Accessing bean properties
• Explicitly setting bean properties
• Automatically setting bean properties from
• request parameters
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)
• You should 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 may use isXxx instead of getXxx
• It is the name of the method, not instance var that matters!
– For more on beans, see http://java.sun.com/beans/docs/
More on Bean Properties
• Usual rule to turn method name into property name
– Drop the word “get” or “set” and change the next letter to
lowercase. Again, instance var name is irrelevant.
• Method name: getUserFirstName
• Property name: userFirstName
• Exception 1: boolean properties
– If getter returns boolean or Boolean
• Method name: getPrime or isPrime
• Property name: prime
• Exception 2: consecutive uppercase letters
– If two uppercase letters in a row after “get” or “set”
• Method name: getURL
• Property name: URL (not uRL)
Bean Properties: Examples
Method Names Property
Name
Example JSP Usage
getFirstName
setFirstName
firstName <jsp:getProperty … property="firstName"/>
<jsp:setProperty … property="firstName"/>
${customer.firstName}
isExecutive
setExecutive
(boolean property)
executive <jsp:getProperty … property="executive"/>
<jsp:setProperty … property="executive"/>
${customer.executive}
getExecutive
setExecutive
(boolean property)
executive <jsp:getProperty … property="executive"/>
<jsp:setProperty … property="executive"/>
${customer.executive}
getZIP
setZIP
ZIP <jsp:getProperty … property="ZIP"/>
<jsp:setProperty … property="ZIP"/>
${address.ZIP}
Note 1: property name does not exist anywhere in your code. It is just a shortcut for the method name.
Note 2: property name is derived only from method name. Instancevariablename is irrelevant.
Why You Should Use
Accessors, Not Public Fields
• Bean rules
– To be a bean, you should not have public fields.
– Wrong
public double speed;
– Right
private double speed; // Var need not match method name
public double getSpeed() {
return(speed);
}
public void setSpeed(double speed) {
this.speed = speed;
}
Note: in Eclipse, after you create instance variable, if
you R-clickand choose“Source”, it gives you option
to generate getters and setters for you.
Why You Should Use
Accessors, Not Public Fields
1) 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.
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 setSpeed(double newSpeed) {
speedInKPH = convert(newSpeed);
}
public void setSpeedInKPH(double newSpeed) {
speedInKPH = newSpeed;
}
Why You Should Use
Accessors, Not Public Fields
• 3) 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.
Bottom Line
• It is no onerous requirement to be a “bean”
– You are probably following most of the conventions
already anyhow
• Zero arg constructor (not required in MVC!)
• No public instance variables
• Use getBlah/setBlah or isBlah/setBlah naming conventions
• JSP provides many places where you refer
to “bean properties”
– Which are shortcuts for getter/setter methods
• getFirstName method: refer to “firstName”
• isMyThingCool method (boolean): refer to “myThingCool”
• getHTMLString method: refer to “HTMLString”
Using Beans: Basic Tasks
• jsp:useBean
– In the simplest case, this element builds a new bean.
It is normally used as follows:
• <jsp:useBean id="beanName" class="package.Class" />
• jsp:setProperty
– This element modifies a bean property (i.e., calls a
setBlah method). It is normally used as follows:
• <jsp:setProperty name="beanName“ property="propertyName"
value="propertyValue" />
• jsp:getProperty
– This element reads and outputs the value of a bean
property. It is used as follows:
• <jsp:getProperty name="beanName“ property="propertyName" />
General Approach with
Standalone
Pages and jsp:useBean Tags
• Input form
– User submits form that refers to a JSP page
• <FORM ACTION="SomePage.jsp">
• JSP Page
– JSP page instantiates a bean
• <jsp:useBean id="myBean" class="…"/>
– You pass some request data to the bean
• <jsp:setProperty name="myBean" …/>
– There are several ways to use jsp:setProperty, but the best is with property="*", as we
will see shortly.
– You output some value(s) derived from the request data
• <jsp:getProperty name="myBean“ property="bankAccountBalance"/>
Building 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
Setting Simple Bean 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"); %>
Accessing Bean 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() %>
Example: StringBean
package cservlets;
public class StringBean {
private String message = "No message
specified";
public String getMessage() {
return(message);
}
Beans installed in normal Java directory
– MyEclipse: src/folderMatchingPackage
– Deployment: WEB-INF/classes/folderMatchingPackage
• Beans must always be in packages!
JSP Page That Uses StringBean
(Code)
<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:
<I><jsp:getProperty name="stringBean"
property="message" /></I>
<LI><% stringBean.setMessage
("My favorite: Kentucky Wonder"); %>
Value after setting property with scriptlet:
<I><%= stringBean.getMessage() %></I>
</OL>
Associating Individual
Properties with Input Parameters
• Use the param attribute of jsp:setProperty
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.
Associating Individual
Properties with Input Parameters
<jsp:useBean id="entry"
class="cservlets.SaleEntry" />
<jsp:setProperty name="entry“ property="itemID“
param="itemID" />
<jsp:setProperty
name="entry“ property="numItems"
param="numItems" />
<jsp:setProperty
name="entry“ property="discountCode"
param="discountCode" />
Associating All Properties
with Input Parameters
• Use "*" for the value of the property attribute of
jsp:setProperty to indicate that
– Value should come from request parameter whose name matches
property name
– Simple automatic type conversion should be performed
Associating All Properties
with Input Parameters
<jsp:useBean id="entry"
class="cservlets.SaleEntry" />
<jsp:setProperty 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.
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="…" />
• Benefits
– Lets multiple servlets or JSP pages share data
– Also permits conditional bean creation
• Creates new object only if it can't find existing one
Sharing Beans: Example
• page1.jsp
<jsp:useBean id="foo" class="…" scope="application"/>
<jsp:setProperty name="foo" property="message“ value="Hello"/>
<jsp:getProperty name="foo" property="message"/>
• page2.jsp
<jsp:useBean id="foo" class="…" scope="application"/>
<jsp:getProperty name="foo" property="message"/>
• Possible scenario 1
– Joe goes to page 2 (output is "Default Message")
– Jane goes to page 1 (output is "Hello")
• Possible scenario 2
– Joe goes to page 1 (output is "Hello")
– Jane goes to page 2 (output is "Hello")
Values of the 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).

More Related Content

PDF
13 java beans
PPTX
Advance java session 12
PDF
Dexterity in the Wild
PPTX
Art of Javascript
PDF
Lap trinh web [Slide jsp]
PDF
Spring 3.0 dependancy injection
PPT
Ms build – inline task
PDF
Angular Directives from Scratch
13 java beans
Advance java session 12
Dexterity in the Wild
Art of Javascript
Lap trinh web [Slide jsp]
Spring 3.0 dependancy injection
Ms build – inline task
Angular Directives from Scratch

What's hot (20)

PPT
jQuery Objects
PDF
Staying Sane with Drupal NEPHP
PDF
Simpler Core Data with RubyMotion
DOCX
Java beans
PPTX
Hibernate inheritance and relational mappings with examples
PDF
Metaprogramming + Ds Ls
PPTX
Spring Web Views
PDF
14 mvc
PDF
JSP Syntax_1
KEY
Backbone.js Simple Tutorial
PDF
Angular custom directives
PPT
Render API - Pavel Makhrinsky
KEY
Django Pro ORM
PPTX
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
PDF
Scalable JavaScript Design Patterns
PPTX
Real World MVC
PPT
jQuery and_drupal
PDF
Viking academy backbone.js
PPTX
Java beans
KEY
Managing State in Single Page WebApps with Ember.js
jQuery Objects
Staying Sane with Drupal NEPHP
Simpler Core Data with RubyMotion
Java beans
Hibernate inheritance and relational mappings with examples
Metaprogramming + Ds Ls
Spring Web Views
14 mvc
JSP Syntax_1
Backbone.js Simple Tutorial
Angular custom directives
Render API - Pavel Makhrinsky
Django Pro ORM
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
Scalable JavaScript Design Patterns
Real World MVC
jQuery and_drupal
Viking academy backbone.js
Java beans
Managing State in Single Page WebApps with Ember.js
Ad

Viewers also liked (12)

PPTX
Javabeanproperties
PDF
Java Course 14: Beans, Applets, GUI
PDF
Java beans
PDF
javabeans
PPTX
Java Beans
PPT
introduction of Java beans
PDF
Java beans
PPTX
Javabeans
PPT
Java beans
PPT
Code Division Multiple Access- CDMA
PPT
Introduction to java beans
PPTX
IS-95 Cdma
Javabeanproperties
Java Course 14: Beans, Applets, GUI
Java beans
javabeans
Java Beans
introduction of Java beans
Java beans
Javabeans
Java beans
Code Division Multiple Access- CDMA
Introduction to java beans
IS-95 Cdma
Ad

Similar to Using java beans(ii) (20)

PDF
java beans
PPTX
Session 4 - Understanding JAVA Beans.pptx
PPTX
Java beans
PPTX
Java Beans Unit 4(Part 1)
PDF
WEB PROGRAMMING UNIT IV NOTES BY BHAVSINGH MALOTH
PPTX
Java Beans Unit 4(part 2)
PDF
Connect2016 AD1387 Integrate with XPages and Java
PDF
AD1387: Outside The Box: Integrating with Non-Domino Apps using XPages and Ja...
PPTX
Codename BEAN.pptx
PPT
presentation on java server pages vs servlet.ppt
PPT
Jsp Presentation +Mufix "3"
PDF
Jsp examples
PPT
JSP Part 2
PPTX
JAVA_BEAN.pptx
PPT
Spring talk111204
PPTX
Unit4wt
PPTX
Unit4wt
PPT
Presentation
PDF
Spring framework core
java beans
Session 4 - Understanding JAVA Beans.pptx
Java beans
Java Beans Unit 4(Part 1)
WEB PROGRAMMING UNIT IV NOTES BY BHAVSINGH MALOTH
Java Beans Unit 4(part 2)
Connect2016 AD1387 Integrate with XPages and Java
AD1387: Outside The Box: Integrating with Non-Domino Apps using XPages and Ja...
Codename BEAN.pptx
presentation on java server pages vs servlet.ppt
Jsp Presentation +Mufix "3"
Jsp examples
JSP Part 2
JAVA_BEAN.pptx
Spring talk111204
Unit4wt
Unit4wt
Presentation
Spring framework core

Using java beans(ii)

  • 2. Agenda • Creating beans • Installing bean classes on your server • Accessing bean properties • Explicitly setting bean properties • Automatically setting bean properties from • request parameters
  • 3. 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) • You should 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 may use isXxx instead of getXxx • It is the name of the method, not instance var that matters! – For more on beans, see http://java.sun.com/beans/docs/
  • 4. More on Bean Properties • Usual rule to turn method name into property name – Drop the word “get” or “set” and change the next letter to lowercase. Again, instance var name is irrelevant. • Method name: getUserFirstName • Property name: userFirstName • Exception 1: boolean properties – If getter returns boolean or Boolean • Method name: getPrime or isPrime • Property name: prime • Exception 2: consecutive uppercase letters – If two uppercase letters in a row after “get” or “set” • Method name: getURL • Property name: URL (not uRL)
  • 5. Bean Properties: Examples Method Names Property Name Example JSP Usage getFirstName setFirstName firstName <jsp:getProperty … property="firstName"/> <jsp:setProperty … property="firstName"/> ${customer.firstName} isExecutive setExecutive (boolean property) executive <jsp:getProperty … property="executive"/> <jsp:setProperty … property="executive"/> ${customer.executive} getExecutive setExecutive (boolean property) executive <jsp:getProperty … property="executive"/> <jsp:setProperty … property="executive"/> ${customer.executive} getZIP setZIP ZIP <jsp:getProperty … property="ZIP"/> <jsp:setProperty … property="ZIP"/> ${address.ZIP} Note 1: property name does not exist anywhere in your code. It is just a shortcut for the method name. Note 2: property name is derived only from method name. Instancevariablename is irrelevant.
  • 6. Why You Should Use Accessors, Not Public Fields • Bean rules – To be a bean, you should not have public fields. – Wrong public double speed; – Right private double speed; // Var need not match method name public double getSpeed() { return(speed); } public void setSpeed(double speed) { this.speed = speed; } Note: in Eclipse, after you create instance variable, if you R-clickand choose“Source”, it gives you option to generate getters and setters for you.
  • 7. Why You Should Use Accessors, Not Public Fields 1) 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.
  • 8. 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 setSpeed(double newSpeed) { speedInKPH = convert(newSpeed); } public void setSpeedInKPH(double newSpeed) { speedInKPH = newSpeed; }
  • 9. Why You Should Use Accessors, Not Public Fields • 3) 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.
  • 10. Bottom Line • It is no onerous requirement to be a “bean” – You are probably following most of the conventions already anyhow • Zero arg constructor (not required in MVC!) • No public instance variables • Use getBlah/setBlah or isBlah/setBlah naming conventions • JSP provides many places where you refer to “bean properties” – Which are shortcuts for getter/setter methods • getFirstName method: refer to “firstName” • isMyThingCool method (boolean): refer to “myThingCool” • getHTMLString method: refer to “HTMLString”
  • 11. Using Beans: Basic Tasks • jsp:useBean – In the simplest case, this element builds a new bean. It is normally used as follows: • <jsp:useBean id="beanName" class="package.Class" /> • jsp:setProperty – This element modifies a bean property (i.e., calls a setBlah method). It is normally used as follows: • <jsp:setProperty name="beanName“ property="propertyName" value="propertyValue" /> • jsp:getProperty – This element reads and outputs the value of a bean property. It is used as follows: • <jsp:getProperty name="beanName“ property="propertyName" />
  • 12. General Approach with Standalone Pages and jsp:useBean Tags • Input form – User submits form that refers to a JSP page • <FORM ACTION="SomePage.jsp"> • JSP Page – JSP page instantiates a bean • <jsp:useBean id="myBean" class="…"/> – You pass some request data to the bean • <jsp:setProperty name="myBean" …/> – There are several ways to use jsp:setProperty, but the best is with property="*", as we will see shortly. – You output some value(s) derived from the request data • <jsp:getProperty name="myBean“ property="bankAccountBalance"/>
  • 13. Building 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
  • 14. Setting Simple Bean 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"); %>
  • 15. Accessing Bean 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() %>
  • 16. Example: StringBean package cservlets; public class StringBean { private String message = "No message specified"; public String getMessage() { return(message); } Beans installed in normal Java directory – MyEclipse: src/folderMatchingPackage – Deployment: WEB-INF/classes/folderMatchingPackage • Beans must always be in packages!
  • 17. JSP Page That Uses StringBean (Code) <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: <I><jsp:getProperty name="stringBean" property="message" /></I> <LI><% stringBean.setMessage ("My favorite: Kentucky Wonder"); %> Value after setting property with scriptlet: <I><%= stringBean.getMessage() %></I> </OL>
  • 18. Associating Individual Properties with Input Parameters • Use the param attribute of jsp:setProperty 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.
  • 19. Associating Individual Properties with Input Parameters <jsp:useBean id="entry" class="cservlets.SaleEntry" /> <jsp:setProperty name="entry“ property="itemID“ param="itemID" /> <jsp:setProperty name="entry“ property="numItems" param="numItems" /> <jsp:setProperty name="entry“ property="discountCode" param="discountCode" />
  • 20. Associating All Properties with Input Parameters • Use "*" for the value of the property attribute of jsp:setProperty to indicate that – Value should come from request parameter whose name matches property name – Simple automatic type conversion should be performed
  • 21. Associating All Properties with Input Parameters <jsp:useBean id="entry" class="cservlets.SaleEntry" /> <jsp:setProperty 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.
  • 22. 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="…" /> • Benefits – Lets multiple servlets or JSP pages share data – Also permits conditional bean creation • Creates new object only if it can't find existing one
  • 23. Sharing Beans: Example • page1.jsp <jsp:useBean id="foo" class="…" scope="application"/> <jsp:setProperty name="foo" property="message“ value="Hello"/> <jsp:getProperty name="foo" property="message"/> • page2.jsp <jsp:useBean id="foo" class="…" scope="application"/> <jsp:getProperty name="foo" property="message"/> • Possible scenario 1 – Joe goes to page 2 (output is "Default Message") – Jane goes to page 1 (output is "Hello") • Possible scenario 2 – Joe goes to page 1 (output is "Hello") – Jane goes to page 2 (output is "Hello")
  • 24. Values of the 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).