Welcome to Scribd, the world's digital library. Read, publish, and share books and documents. See more ➡
Standard view
Full view
of .
Add note
Save to My Library
Sync to mobile
Look up keyword
Like this
0 of .
Results for:
No results containing your search query
P. 1
JavaBeans and JSP

JavaBeans and JSP



|Views: 3,358|Likes:
Published by api-25930603

More info:

Published by: api-25930603 on Oct 16, 2008
Copyright:Attribution Non-commercial


Read on Scribd mobile: iPhone, iPad and Android.
download as PDF, TXT or read online from Scribd
See More
See less





Session 15 –Java Beans & JSP 3/14/20051©Robert Kelly, 2001-2005
Session 15
JSP and JavaBeans
©Robert Kelly, 2001-2005
Reading & Reference
Head First Chapter 8 (pages 341-365)
Optional readinghttp://www.javaworld.com/javaworld/jw-01-2001/jw-0119-jspframe_p.html
JavaBeans Tutorial - java.sun.com/docs/books/tutorial/javabeans/
Advanced JavaServer Pages by David Geary –Chapter 3
 3©Robert Kelly, 2001-2005
Lecture Objectives
Understand how to set up visibility to a Javabean from a JSP
Understand how the useBeanscope attributedetermines where the bean handle can be found
Understand how to access bean properties from aJSP
Know how to handle special form elements(i.e., radio buttons, checkboxes and menus)
4©Robert Kelly, 2001-2005
JSP Recap
JSP looks like HTML, but includes the ability toinsert dynamic content
Java scriptlets(<% …)
Directives (<%@ …)However, mixing presentationwith business logic is not agood approach to softwarestructure, so
Don’t use scriptletsin your JSP
5©Robert Kelly, 2001-2005
Setting all Bean Values From the Form
A Web module (e.g., servlet) will usually read the formdata set and set the values of the form in a bean so thatthey can be used by other Web modulesservlet
Bean instancevariables arenamed:
itemID,discountCode,and numItems
6©Robert Kelly, 2001-2005
Servlet/JSP Data Sharing
SharedObject (bean) The servlet canforward control toa JSP in order toregenerate theform (if there is aform validationerror)
Session 15 –Java Beans & JSP 3/14/2005©Robert Kelly, 2001-2005
 7©Robert Kelly, 2001-2005
Model / View / Controller Pattern
Web systems are usually decomposed into MVCcomponents
JSPs view
Servlets –controller
Java Beans -model
Data for a Web application areusually stored in objects thatare visible to servlets and JSPs The handleto a bean isusually stored in the relevantshared object (e.g., sessionor ServletContext)
©Robert Kelly, 2001-2005
Bean Class Review
A bean is an instance of a Java class that:
Must have a zero argument constructor
Should have no public instance variables
Should have get and set methods for any instancevariables that are to be accessed (setter argumenttype and getter return type must be identical)
Must support persistence (the bean is serializable)
Usually supports events either by firing events whensome properties change or listening for events
For use within JSPs, theproperty type should be eitherString or a primitive
9©Robert Kelly, 2001-2005
How do we Access a Bean from a JSP?
Before we do anything we need to get the handleto the bean
JSP Page
instantiateset valuesget valuesData sourcesPersistencelayer
10©Robert Kelly, 2001-2005
JSP Counter
11©Robert Kelly, 2001-2005
 public class CountBeanimplements Serializable{ private intcount = 0; public intgetCount() {return (count);} public intfetchAndAdd() {inttemp=count;count++;return (temp);} public void setCount(intnewCount) {this.count= count;}}
Notice that fetchAndAddreturns the pre-incrementedvalue of the counterNotice that the bean is a standard Javaclass, but contains the features of a bean(constructor, private instance variable, andproperly named methods
12 ©Robert Kelly, 2001-2005
Example-Counter (First try)
 <html><head><title>JSP Counter</title>  <%@ page import="lecturecode.CountBean" %>  </head>  <body>  <%ServletContextsc = this.getServletContext();CountBeanb = (CountBean) sc.getAttribute(“b");if (b != null) {}else { b = new CountBean();sc.setAttribute(“b", b);}%>  <h1>JSP Counter</h1>  <p>This JSP will print and increment the value of the counter</p>  <p>The counter is initially: <%= b.getCount() %>  </p>  <p>The counter is now: <%= b.fetchAndAdd() %>  </p>  <p>The counter is now: <%= b.getCount() %>  </p>  <br/>  <a href="http://localhost:8080/WebAp/JSPs/JSPCounter.jsp"Re-count</a>  </body></html> 
But, we are not supposedto use scriptlets
Session 15 –Java Beans & JSP 3/14/2005 3©Robert Kelly, 2001-2005
13©Robert Kelly, 2001-2005
Example-Counter (Second try)
 <%@ page language="java" contentType="text/html" %>  <html>  <head>  <title>JSP Counter</title>  <%@ page import="lecturecode.CountBean" %>  </head>  <body>  <jsp:useBeanid=“b" class="lecturecode.CountBean"scope="application" />  <h1>JSP Counter</h1>  <p>This JSP will print and increment the value of the counter</p>  <p>The counter is initially: <%= b.getCount() %>  </p>  <p>The counter is now: <%= b.fetchAndAdd() %>  </p>  <p>The counter is now: <%= b.getCount() %>  </p>  <br/>  <a href="http://localhost:8080/WebAp/JSPs/JSPCounter2.jsp">Re-count</a>  </body>  </html> 
 This tag has thesame effect as thescriptlet These statements use thebean that was declared above
14©Robert Kelly, 2001-2005
Generated Code
lecturecode.CountBeanb = null;synchronized (application) { b = (lecturecode.CountBean) pageContext.getAttribute("b",PageContext.APPLICATION_SCOPE);if (b == null){try { b = (lecturecode.CountBean) java.beans.Beans.instantiate(this.getClass().getClassLoader(), "lecturecode.CountBean");} catch (ClassNotFoundExceptionexc) {throw new InstantiationException(exc.getMessage());} catch (Exception exc) {throw new ServletException("Cannotcreate bean of class " +"lecturecode.CountBean", exc);} pageContext.setAttribute("b", b, PageContext.APPLICATION_SCOPE);}}out.write("\r\n");out.write("<h1>JSP Counter");out.write("</h1>\r\n");out.write("<p>This JSP will print and increment the value of thecounter");out.write("</p>\r\n");out.write("<p>The counter is initially: ");out.print( b.getCount() );...
Instantiates the bean, if it does not already exist
15©Robert Kelly, 2001-2005
Loading a Bean…
 To instantiate a bean (or bind an existing bean toyour JSP variable):
 <jsp:useBeanid="b" class="lecturecode.CountBean"scope="application" /> 
If the bean does not already exist, this statementis equivalent to
 <% lecturecode.CountBeanb =new lecturecode.CountBean(); %> 
JSP variable nameBean class The scope attributespecifies where a handleto the bean is stored
16©Robert Kelly, 2001-2005
JSP XML Syntax
Bean access is an example of JSP actionJSPtags that transfer control, create and modifyobjects, etc.
Syntax for action tags (e.g., bean usage) withinJSPs is XML, so
Attribute names are case sensitive
Quotes must be used for attributes
Empty elements must use the empty tag syntax
17©Robert Kelly, 2001-2005
XML Namespace
A W3C scheme for building documents from fragmentsdefined in different domains
A single DTD is considered to own a namespace
A namespaceis an environment in which
All element names are unique
All attribute names are unique
URLs are often used as a namespace identifier
A qualified namefor an element or attribute is acombination of namespace and element/attribute name
18 ©Robert Kelly, 2001-2005
Obtaining a Handle to the Bean
 <jsp:useBeanid="b" class="lecturecode.CountBean" /> 
 jsp:usebeanaction specifies that a new object isinstantiated if there is no existing bean with thesame id (name) and scope, otherwise the existingbean is used
Use the type attribute if youwant polymorphic access(i.e., access the bean as asuperclass or interface)

Activity (10)

You've already reviewed this. Edit your review.
1 hundred reads
1 thousand reads
Sunil Soni liked this
kmkesavan7 liked this
grandsunil liked this
eswar_jk liked this
Mike Bavon liked this
hitesh99raj liked this
cripps liked this
ax7_unholy liked this

You're Reading a Free Preview

/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->