Slides © Marty Hall, book © Sun Microsystems Press 1 Using JavaBeans with JSP Core Servlets & JSP book:

Slides:



Advertisements
Similar presentations
J2EE training: 1 Course Material Usage Rules PowerPoint slides for use only in full-semester, for-credit courses at degree-granting.
Advertisements

JSP1 Java Server Pages (JSP) Introducing JavaServer Pages TM (JSP TM ) JSP scripting elements.
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.
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.
COMP201 Java Programming Part III: Advanced Features Topic 16: JavaServer Pages (JSP) Servlets and JavaServer Pages (JSP) 1.0: A Tutorial
Object-Oriented Enterprise Application Development Lecture 8 Advanced JavaBeans.
Writing Enterprise Applications with J2EE (Fifth lesson) Alessio Bechini June 2002 (based on material by Monica Pawlan)
Integrating Servlets and JavaServer Pages Vijayan Sugumaran School of Business Administration Oakland University Parts of this presentation provided by.
Q: According to Intel, the Pentium conforms to the IEEE standards 754 and 854 for floating point arithmetic. If you fly in aircraft designed using a Pentium,
Introduction to Server-Side Web Development Introduction to Server-Side Web Development JSP Final Remarks 10 th March 2005 Bogdan L. Vrusias
Web Application: Java Server Pages (JSP) INE2720 Web Application Software Development Essential Materials.
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.
Slides © Marty Hall, book © Sun Microsystems Press 1 Including Files & Applets in JSP Documents Core Servlets & JSP book:
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.
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.
JavaServer Faces Jeff Schmitt October 5, Introduction to JSF Presents a standard framework for building presentation tiers for web applications.
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.
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,
® IBM Software Group © 2007 IBM Corporation JSP Expression Language
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.
JSTL Lec Umair©2006, All rights reserved JSTL (ni) Acronym of  JavaServer Pages Standard Tag Library JSTL (like JSP) is a specification, not an.
J2EE training: 1 Course Material Usage Rules PowerPoint slides for use only in full-semester, for-credit courses at degree-granting.
CS320 Web and Internet Programming Java Beans and Expression Language (EL) Chengyu Sun California State University, Los Angeles.
J2EE training: 1 Course Material Usage Rules PowerPoint slides for use only in full-semester, for-credit courses at degree-granting.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 27 JavaServer Page.
Java™ How to Program, 10/e © Copyright by Pearson Education, Inc. All Rights Reserved.
1 JSP – Java Server Page DBI – Representation and Management of Data on the Internet.
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
 Obtaining a RequestDispatcher Forwarding requests from servlets to dynamic resources  Forwarding requests from servlets to static resources  Using.
1 Processing phase Translation phase JSP page translation and processing phases Client Server Request Response Hello.jsp helloServlet.class helloServlet.java.
Java Server Pages Introduction. Servlet Drawbacks Web page designer will need to know servlets to design the page. Servlet will have to be compiled for.
JavaServer Page by Antonio Ko. Overview ► Introduction ► What is a servlet? ► What can servlets do? ► Servlets Vs JSP ► Syntax ► Samples ► JavaBean ►
Chapter 11 Invoking Java Code with JSP Scripting Elements.
CSC 2720 Building Web Applications JavaServer Pages (JSP) JSP Directives and Action Elements.
Web Technologies Java Beans & JSP By Praveen Kumar G.
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.
Slides © Marty Hall, book © Sun Microsystems Press 1 Session Tracking Core Servlets & JSP book: More.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 43 JavaServer Page.
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.
Web Application: Java Server Pages (JSP) THETOPPERSWAY.COM.
USING JAVABEANS COMPONENT IN JSP DOCUMENTS. References Marty Hall. Core Servlet and Java Server Page. Sun Micro System. Prentice Hall PTR; 1 edition 2000.
INVOKING JAVA CODE WITH JSP SCRIPTING ELEMENTS. Creating Template Text A large percentage of your JSP document consists of static text (usually HTML),
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.
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.
Advanced Java Programming
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
JavaBeans and JSP CS-422.
Introduction to Java Bean
CS320 Web and Internet Programming Java Beans
Object Oriented Programming in java
Scripted Page Web Application Development (Java Server Pages)
Web Technologies Java Beans & JSP
Presentation transcript:

Slides © Marty Hall, book © Sun Microsystems Press 1 Using JavaBeans with JSP Core Servlets & JSP book: More Servlets & JSP book: Servlet and JSP Training Courses: courses.coreservlets.com

Using Beans2 Agenda Overview of beans in Java Basic use of beans in JSP Creating and accessing beans Setting bean properties explicitly Associating individual bean properties with request parameters Associating all bean properties with request parameters Conditional bean operations Sharing beans among multiple JSP pages and servlets

Using Beans3 Uses of JSP Constructs Scripting elements calling servlet code directly Scripting elements calling servlet code indirectly (by means of utility classes) Beans Custom tags Servlet/JSP combo (MVC), with beans and possibly custom tags Simple Application Complex Application

Using Beans4 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 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

Using Beans5 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 getSpeed() { return(speed); } public void setSpeed(double newSpeed) { speed = newSpeed; } You should do this in all your Java code anyhow. Why?

Using Beans6 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.

Using Beans7 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) { setSpeedInKPH = convert(newSpeed); } public void setSpeedInKPH(double newSpeed) { speedInKPH = newSpeed; }

Using Beans8 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.

Using Beans9 Basic Bean Use in JSP Format – Purpose –Allow instantiation of Java classes without explicit Java programming (XML-compatible syntax) Notes –Simple interpretation: JSP action can be thought of as equivalent to the scriptlet –But 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

Using Beans10 Accessing Bean Properties Format – Purpose –Allow access to bean properties (i.e., calls to getXxx methods) without explicit Java programming Notes – is equivalent to the following JSP expression

Using Beans11 Setting Bean Properties: Simple Case Format – Purpose –Allow setting of bean properties (i.e., calls to setXxx methods) without explicit Java programming Notes – is equivalent to the following scriptlet

Using Beans12 Example: StringBean package coreservlets; public class StringBean { private String message = "No message specified"; public String getMessage() { return(message); } public void setMessage(String message) { this.message = message; } Installed in normal servlet directory –Tomcat_install_dir\webapps\ROOT\WEB-INF\classes\coreservlets –JRun_install_dir\servers\default\default-app\WEB-INF\classes\coreservlets Beans (and utility) classes must always be in packages!

Using Beans13 JSP Page That Uses StringBean Initial value (getProperty): <jsp:getProperty name="stringBean" property="message" /> Initial value (JSP expression): <jsp:setProperty name="stringBean" property="message" value="Best string bean: Fortex" /> Value after setting property with setProperty: <jsp:getProperty name="stringBean" property="message" /> Value after setting property with scriptlet:

Using Beans14 JSP Page That Uses StringBean

Using Beans15 Setting Bean Properties Case 1: Explicit Conversion & Assignment... <jsp:setProperty name="entry" property="itemID" value=' ' />

Using Beans16 Setting Bean Properties Case 1: Explicit Conversion & Assignment <% int numItemsOrdered = 1; try { numItemsOrdered = Integer.parseInt(request.getParameter("numItems")); } catch(NumberFormatException nfe) {} %> <jsp:setProperty name="entry" property="numItems" value=" " />

Using Beans17 Setting Bean Properties Case 1: Explicit Conversion & Assignment <% double discountCode = 1.0; try { String discountString = request.getParameter("discountCode"); discountCode = Double.parseDouble(discountString); } catch(NumberFormatException nfe) {} %> <jsp:setProperty name="entry" property="discountCode" value=" " />

Using Beans18 Setting Bean Properties Case 1: Explicit Conversion & Assignment

Using Beans19 Case 2: 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.

Using Beans20 Case 2: Associating Individual Properties with Input Parameters <jsp:useBean id="entry" class="coreservlets.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" />

Using Beans21 Case 3: 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

Using Beans22 Case 3: Associating All Properties with Input Parameters <jsp:useBean id="entry" class="coreservlets.SaleEntry" /> 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.

Using Beans23 Sharing Beans You can use scope attribute to specify additional places where bean is stored –Still also bound to local variable in _jspService – Lets multiple servlets or JSP pages share data Also permits conditional bean creation –Create new object only if you can't find existing one

Using Beans24 Values of the scope Attribute page ( or ) –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 ( ) –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).

Using Beans25 Values of the scope Attribute 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 ( ) –Bean object should be placed in the ServletRequest object for the duration of the current request, where it is available by means of getAttribute

Using Beans26 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 – replaced by statements –The statements (jsp:setProperty elements) are executed only if a new bean is created, not if an existing bean is found.

Using Beans27 Conditional Bean Creation: AccessCountBean public class AccessCountBean { private String firstPage; private int accessCount = 1; public String getFirstPage() { return(firstPage); } public void setFirstPage(String firstPage) { this.firstPage = firstPage; } public int getAccessCount() { return(accessCount); } public void setAccessCountIncrement(int increment) { accessCount = accessCount + increment; }

Using Beans28 Conditional Bean Creation: SharedCounts1.jsp <jsp:useBean id="counter" class="coreservlets.AccessCountBean" scope="application"> <jsp:setProperty name="counter" property="firstPage" value="SharedCounts1.jsp" /> Of SharedCounts1.jsp (this page), SharedCounts2.jsp, and SharedCounts3.jsp, was the first page accessed. Collectively, the three pages have been accessed times. <jsp:setProperty name="counter" property="accessCountIncrement" value="1" />

Using Beans29 Accessing SharedCounts1, SharedCounts2, SharedCounts3 SharedCounts2.jsp was accessed first. Pages have been accessed twelve previous times by an arbitrary number of clients

Using Beans30 Summary Benefits of jsp:useBean –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)

Slides © Marty Hall, book © Sun Microsystems Press 31 Questions? Core Servlets & JSP book: More Servlets & JSP book: Servlet and JSP Training Courses: courses.coreservlets.com