Session 8. JavaBeans. Reading & Reference. Reading. Reference. Session 8 Java Beans. 2/27/2013 Robert Kelly, Head First Chapter 3 (MVC)

Similar documents
Session 20 Data Sharing Session 20 Data Sharing & Cookies

Session 21. Expression Languages. Reading. Java EE 7 Chapter 9 in the Tutorial. Session 21 Expression Languages 11/7/ Robert Kelly,

Session 11. Expression Language (EL) Reading

Session 9. Data Sharing & Cookies. Reading & Reference. Reading. Reference http state management. Session 9 Data Sharing

Servlets. An extension of a web server runs inside a servlet container

Servlet and JSP Review

Session 10. Form Dataset. Lecture Objectives

Get the cookies from the service request: Cookie[] HttpServletRequest.getCookies() Add a cookie to the service response:

Stateless -Session Bean

Java Enterprise Edition. Java EE Oct Dec 2016 EFREI/M1 Jacques André Augustin Page 1

Session 8. Introduction to Servlets. Semester Project

ServletConfig Interface

Java TM. JavaServer Faces. Jaroslav Porubän 2008

JavaServer Pages (JSP)

Session 9. Introduction to Servlets. Lecture Objectives

To follow the Deitel publishing program, sign-up now for the DEITEL BUZZ ON-

Advanced Internet Technology Lab # 4 Servlets

Advanced Topics in Operating Systems. Manual for Lab Practices. Enterprise JavaBeans

Principles and Techniques of DBMS 6 JSP & Servlet

Welcome To PhillyJUG. 6:30-7:00 pm - Network, eat, find a seat 7:00-7:15 pm - Brief announcements 7:15-8:30 pm - Tom Janofsky's presentation

Enterprise Java Technologies (Part 1 of 3) Component Architecture. Overview of Java EE. Java Servlets

A.1 JSP A.2 JSP JSP JSP. MyDate.jsp page contenttype="text/html; charset=windows-31j" import="java.util.calendar" %>

INTRODUCTION TO SERVLETS AND WEB CONTAINERS. Actions in Accord with All the Laws of Nature

&' () - #-& -#-!& 2 - % (3" 3 !!! + #%!%,)& ! "# * +,

Servlet Basics. Agenda

Advanced Web Technology

Generating the Server Response: HTTP Response Headers

Chapter 2 How to structure a web application with the MVC pattern

Servlets1. What are Servlets? Where are they? Their job. Servlet container. Only Http?

Berner Fachhochschule Haute cole spcialise bernoise Berne University of Applied Sciences 2

JAVA SERVLET. Server-side Programming ADVANCED FEATURES

JAVA SERVLET. Server-side Programming PROGRAMMING

JSP. Common patterns

Introduction. This course Software Architecture with Java will discuss the following topics:

AJP. CHAPTER 5: SERVLET -20 marks

Web based Applications, Tomcat and Servlets - Lab 3 -

Introduction. Literature: Steelman & Murach, Murach s Java Servlets and JSP. Mike Murach & Associates Inc, 2003

sessionx Desarrollo de Aplicaciones en Red A few more words about CGI CGI Servlet & JSP José Rafael Rojano Cáceres

Java4570: Session Tracking using Cookies *

********************************************************************

Three hours UNIVERSITY OF MANCHESTER SCHOOL OF COMPUTER SCIENCE. Date: Friday 21 st May Time:

Demonstration of Servlet, JSP with Tomcat, JavaDB in NetBeans

Servlet. Web Server. Servlets are modules of Java code that run in web server. Internet Explorer. Servlet. Fire Fox. Servlet.

CE212 Web Application Programming Part 3

Database Systems Lab. 11. JSP I 충남대학교컴퓨터공학과 데이타베이스시스템연구실

Integrating Servlets and JavaServer Pages Lecture 13

11.1 Introduction to Servlets

Handout 31 Web Design & Development

Introduction to Servlets. After which you will doget it

a. Jdbc:ids://localhost:12/conn?dsn=dbsysdsn 21. What is the Type IV Driver URL? a. 22.

Java servlets CSCI 470: Web Science Keith Vertanen Copyright 2013

JSP Scripting Elements

Backend. (Very) Simple server examples

CSC309: Introduction to Web Programming. Lecture 11

Generating the Server Response: HTTP Status Codes

COMP9321 Web Application Engineering

Web Programming. Lecture 11. University of Toronto

Handling Cookies. Agenda

CSc31800: Internet Programming, CS-CCNY, Spring 2004 Jinzhong Niu May 9, JSPs 1

2. Follow the installation directions and install the server on ccc. 3. We will call the root of your installation as $TOMCAT_DIR

SDN Community Contribution

JAVA SERVLET. Server-side Programming INTRODUCTION

Construction d Applications Réparties / Master MIAGE

Lab session Google Application Engine - GAE. Navid Nikaein

CS506 Web Design & Development Final Term Solved MCQs with Reference

Servlets and JSP (Java Server Pages)

Generating the Server Response:

Islamic University of Gaza Faculty of Engineering Department of Computer Engineering ECOM Advanced Internet Technology Lab.

Using the JBoss IDE for Eclipse

CSC309: Introduction to Web Programming. Lecture 10

Model View Controller (MVC)

Introduction to Web applications with Java Technology 3- Servlets

1Z Java EE 6 Web Component Developer Certified Expert Exam Summary Syllabus Questions

How to structure a web application with the MVC pattern

Web Fundamentals. Typical Current Web Architecture. Web Server HTTP interface. HTML, Images, cookies, JSON, etc.

Session 12. JSP Tag Library (JSTL) Reading & Reference

To create a view for students, staffs and courses in your departments using servlet/jsp.

HTTP status codes. Setting status of an HTTPServletResponse

CIS 3952 [Part 2] Java Servlets and JSP tutorial

Accessing EJB in Web applications

Handling the Client Request: HTTP Request Headers

Develop an Enterprise Java Bean for Banking Operations

Component Based Software Engineering

COMP9321 Web Application Engineering

Unit 4 - Servlet. Servlet. Advantage of Servlet

Handling Cookies. For live Java EE training, please see training courses at

Module 3 Web Component

MTAT Enterprise System Integration

HTTP. HTTP HTML Parsing. Java

Enterprise Java Unit 1- Chapter 4 Prof. Sujata Rizal Servlet API and Lifecycle

Using JavaBeans with JSP

SERVLET AND JSP FILTERS

One application has servlet context(s).

CREATE A SERVLET PROGRAM TO DISPLAY THE STUDENTS MARKS. To create a servlet program to display the students marks

Unit-4: Servlet Sessions:

Scheme G Sample Question Paper Unit Test 2

Module 4: SERVLET and JSP

Java Server Page (JSP)

Basics of programming 3. Java Enterprise Edition

The Structure and Components of

Transcription:

Session 8 JavaBeans 1 Reading Reading & Reference Head First Chapter 3 (MVC) Reference JavaBeans Tutorialdocs.oracle.com/javase/tutorial/javabeans/ 2 2/27/2013 1

Lecture Objectives Understand how the Model/View/Controller design pattern applies to Web applications Understand how a Java Bean is used to store data in a Web application Know the features a Java class must possess to be considered a Java Bean Know how to use a servlet to move form data into a Java Bean 3 Web Architecture Clients servlet JSP Page JSP Page Web layer Bean Bean Session Other shared objects Web applications are usually constructed with the Model, View, Controller pattern 4 2/27/2013 2

Model / View / Controller Pattern Web systems are usually decomposed into MVC components JSPs view Servlets controller Java Beans (and custom tags) - model The handle to a bean is usually stored in the relevant shared object (e.g., Session and ServletContext) For now, just think of a JSP as an easy way to write a servlet that generates HTML Data and business logic for a Web application are usually stored in objects that are visible to servlets and JSPs 5 JavaBeans and Web Applications A bean is an object that you can easily use within your JSP or servlet You can create a bean within your JSP or servlet You can share a bean with other JSPs and servlets and thereby share data You can get and set properties in the bean Bean data can be persistent 6 2/27/2013 3

MVC Web Architecture Controller Model servlet JSP Page JSP Page Bean Bean Session Other shared objects View 7 What Makes a Bean a Bean? A bean is an instance of a Java class that: Must have a zero argument constructor Should have no public instance variables Should have (properly named) get and set methods for any instance variables that are to be accessed (setter argument type and getter return type must be identical) Must support persistence (the bean is serializable) A bean usually supports events either by firing events when some properties change or listening for events (although we usually do not use this feature) 8 2/27/2013 4

The counter value is stored in a bean along with methods to increment, get, and set the counter Example: Counter 9 Bean Counter Browser servlet CountBean() setcount(int) getcount() fetchandadd() CountBean The ServletContext is a container level object that is used to store a handle to the CountBean ServletContext 10 2/27/2013 5

ServletContext Actually, an interface to the Web container, but you can think of it as a shared object used to store data available to all servlets in the Web application There is one ServletContext per Web application You can obtain a reference (i.e., handle) to the ServletContext object in many ways (e.g., through a call to the getservletcontext method of HttpServlet) 11 Using the ServletContext Includes methods for getting and setting an attribute (name/value pair) as if the ServletContext were a Map Object getattribute(string) void setattribute(string, Object) Enumeration getattributenames() The name/value pairs are of type String/Object 12 2/27/2013 6

BeanCounter Generated Page 13 BeanCounter Servlet public class BeanCounter extends HttpServlet { private static final String CONTENT_TYPE = "text/html"; private static final String DOC_TYPE = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n" + " \"http://www.w3.org/tr/xhtml1/dtd/xhtml1-strict.dtd\">"; /**Initialize global variables*/ public void init() throws ServletException { public void doget(httpservletrequest request, HttpServletResponse response) throws ServletException, IOException { int bcount = 0; response.setcontenttype(content_type); PrintWriter out = response.getwriter(); out.println("<html>"); out.println( "<head><title>bean Counter</title></head>"); out.println("<body >"); out.println("<h2>bean Counter</h2>"); 14 2/27/2013 7

BeanCounter Servlet ServletContext sc = this.getservletcontext(); CountBean b = (CountBean) sc.getattribute( b"); if (b == null) { b = new CountBean(); sc.setattribute( b", b); bcount = b.fetchandadd(); out.println("<p>initial value of counter in the bean - "); out.println(bcount + "</p>"); bcount = b.getcount(); out.println("<p>incremented value of counter in the bean - "); out.println(bcount + "</p>"); out.println("<p>return to"); out.println("<a href=\"http://localhost:8080/codecse336/counter.htm\">"); out.println("return to the bean counter servlet</a>"); out.println("</body></html>"); The servlet gets the value of the counter from the CountBean bean Shows that a bean can have methods other than getters and setters 15 CountBean Notice the setter and getter naming conventions public class CountBean implements Serializable { private int count = 0; public int getcount() { return (count); public int fetchandadd() { int temp=count; count++; return (temp); Notice that fetchandadd returns the pre-incremented value of the counter public void setcount(int newcount) { this.count = newcount; Notice that the bean is a standard Java class, but has the features of a bean (constructor, persistence, private instance variable, and properly named methods) 16 2/27/2013 8

Using a Bean to Store Form Data Frequently, you will use a bean to store the values of a form dataset The form values in the bean are available to other modules in your application (e.g., JSPs) You may need to add type conversion You may need to add validation to the bean 17 Setting all Bean Values From the Form Browser itemid=3& discountcode=0& numitems=1 servlet Bean Bean instance variables are named: itemid, discountcode, and numitems A Web module (e.g., servlet) will usually read the form data set and set the values of the form in a bean so that they can be used by other Web modules 18 2/27/2013 9

Typical Bean Setup public void doget(httpservletrequest request, HttpServletResponse response) throws ServletException, IOException { ServletContext sc = this.getservletcontext(); FormBean b = (FormBean) sc.getattribute( OracleForm"); if (b == null) { b = new FormBean(); sc.setattribute( OracleForm", b); b.setemail(request.getparameter("email")); b.setfirstname(request.getparameter("firstname"));... if (b.isvalid()) { display the JSP associated with the data else { redisplay the form with the fields filled in and with the error messages Note the names This is the logic of the class project 19 Form Bean Value Setting Typically, you will set the value of a bean to the value of the associated form element (in the form data set) Allows the form data set to persist Allows the form data set to be shared among a collection of servlets and JSPs b.setdate(request.getparameter( date")); Notice how the same name is used for the bean attribute and the form element <input name= date" size="10" class="nav" type="text" /> 20 2/27/2013 10

Explicit Type Conversion In the previous example, if the last name parameter is of type String it works OK But, there could be some type considerations Remember that each item in a form data set is of type String/String If your bean instance variable is not a String: The value should be explicitly cast to the correct type b.setnumitems( Integer.parseInt(request.getParameter("numItems"))); Explicit type conversion may not always be needed (Java 5 and above) 21 General Forms Processing Define form in HTML (or JSP) Specify initial values of elements Transmit form to server Validate form content (within a bean method) Select page to be displayed, based on validation If form content contains errors Repopulate form with already entered values Include error messages Send form (as HTML) to browser If no errors, display next page in sequence 22 2/27/2013 11

Have You Satisfied the Lecture Objectives? Understand how the Model/View/Controller design pattern applies to Web applications Understand how a Java Bean is used to store data in a Web application Know the features a Java class must possess to be considered a Java Bean Know how to use a servlet to move form data into a Java Bean 23 Assignment 3 Write a servlet and form bean to store the form data The form bean should contain variables for all the form parameters in the project page Add a validation method to the bean that will validate All required fields contain data (* on page denotes required) E-mail address is in correct format (i.e., xxxx@yyyyy) Your servlet should store the data in the bean and display (in a simple HTML page) an error message(s) for any field that is not valid or a message stating that the fields are correct 24 2/27/2013 12