Java Server Pages and Java Beans



Similar documents
2. Follow the installation directions and install the server on ccc

Brazil + JDBC Juin 2001, douin@cnam.fr

Web Programming II JSP (Java Server Pages) ASP request processing. The Problem. The Problem. Enterprise Application Development using J2EE

CS412 Interactive Lab Creating a Simple Web Form

Database Access from a Programming Language: Database Access from a Programming Language

Database Access from a Programming Language:

The JAVA Way: JDBC and SQLJ

7 Web Databases. Access to Web Databases: Servlets, Applets. Java Server Pages PHP, PEAR. Languages: Java, PHP, Python,...

About webpage creation

Applets, RMI, JDBC Exam Review

Servlets. Based on Notes by Dave Hollinger & Ethan Cerami Also, the Online Java Tutorial by Sun

Chapter 9 Java and SQL. Wang Yang wyang@njnet.edu.cn

2.8. Session management

SQL and Java. Database Systems Lecture 19 Natasha Alechina

Introduction to Web Design Curriculum Sample

Real SQL Programming 1

CSI 2132 Lab 8. Outline. Web Programming JSP 23/03/2012

HTML Form Widgets. Review: HTML Forms. Review: CGI Programs

CGI Programming. What is CGI?

Mini Project Report ONLINE SHOPPING SYSTEM

Java and Microsoft Access SQL Tutorial

Internet Technologies

Web Development and Core Java Lab Manual V th Semester

Web Container Components Servlet JSP Tag Libraries

<option> eggs </option> <option> cheese </option> </select> </p> </form>

HTML Tables. IT 3203 Introduction to Web Development

Database System Concepts

ACM Crossroads Student Magazine The ACM's First Electronic Publication

HTML Forms and CONTROLS

An introduction to web programming with Java

CS506 Web Design and Development Solved Online Quiz No. 01

Form Validation. Server-side Web Development and Programming. What to Validate. Error Prevention. Lecture 7: Input Validation and Error Handling

Caldes CM12: Content Management Software Introduction v1.9

Java Server Pages (JSP)

Client-side Web Engineering From HTML to AJAX

PHP Tutorial From beginner to master

Development. with NetBeans 5.0. A Quick Start in Basic Web and Struts Applications. Geertjan Wielenga

Web Programming with PHP 5. The right tool for the right job.

Introduction to XHTML. 2010, Robert K. Moniot 1

Web Programming with Java Servlets

Website as Tool for Compare Credit Card Offers

HTML Forms. Pat Morin COMP 2405

CS 377 Database Systems SQL Programming. Li Xiong Department of Mathematics and Computer Science Emory University

Security Code Review- Identifying Web Vulnerabilities

Interactive Data Visualization for the Web Scott Murray

Developing XML Solutions with JavaServer Pages Technology

JavaScript Basics & HTML DOM. Sang Shin Java Technology Architect Sun Microsystems, Inc. sang.shin@sun.com

Glassfish, JAVA EE, Servlets, JSP, EJB

Designing for Dynamic Content

TABLE OF CONTENTS...2 INTRODUCTION...3 APPLETS AND APPLICATIONS...3 JAVABEANS...4 EXCEPTION HANDLING...5 JAVA DATABASE CONNECTIVITY (JDBC)...

AIM: 1. Develop static pages (using Only HTML) of an online Book store. The pages should

07 Forms. 1 About Forms. 2 The FORM Tag. 1.1 Form Handlers

The Google Web Toolkit (GWT): Declarative Layout with UiBinder Basics

InternetVista Web scenario documentation

1 SQL Data Types and Schemas

CS/CE 2336 Computer Science II

Security Module: SQL Injection

JDBC (Java / SQL Programming) CS 377: Database Systems

Hello World RESTful web service tutorial

Java 2 Web Developer Certification Study Guide Natalie Levi

Why Is This Important? Database Application Development. SQL in Application Code. Overview. SQL in Application Code (Contd.

Database Programming. Week *Some of the slides in this lecture are created by Prof. Ian Horrocks from University of Oxford

Agenda. Summary of Previous Session. Application Servers G Session 3 - Main Theme Page-Based Application Servers (Part II)

By Glenn Fleishman. WebSpy. Form and function

SQL and programming languages

JavaScript and Dreamweaver Examples

Building Web Services with Apache Axis2

Sample HP OO Web Application

CSc31800: Internet Programming, CS-CCNY, Spring 2004 Jinzhong Niu May 9, Java Servlets

BASICS OF WEB DESIGN CHAPTER 2 HTML BASICS KEY CONCEPTS COPYRIGHT 2013 TERRY ANN MORRIS, ED.D

Cover Page. Dynamic Server Pages Guide 10g Release 3 ( ) March 2007

ICT 6012: Web Programming

So we're set? Have your text-editor ready. Be sure you use NotePad, NOT Word or even WordPad. Great, let's get going.

Advanced Java Client API

Application Security

public class ResultSetTable implements TabelModel { ResultSet result; ResultSetMetaData metadata; int num cols;

Form Handling. Server-side Web Development and Programming. Form Handling. Server Page Model. Form data appended to request string

CSc 230 Software System Engineering FINAL REPORT. Project Management System. Prof.: Doan Nguyen. Submitted By: Parita Shah Ajinkya Ladkhedkar

Web Service Caching Using Command Cache

CS 111 Classes I 1. Software Organization View to this point:

WHAT ARE PACKAGES? A package is a collection of related classes. This is similar to the notion that a class is a collection of related methods.

J a v a Quiz (Unit 3, Test 0 Practice)

Web development... the server side (of the force)

XHTML Forms. Form syntax. Selection widgets. Submission method. Submission action. Radio buttons

How to Create a Mobile Responsive Template in ExactTarget

An Overview of Java. overview-1

NGASI AppServer Manager SaaS/ASP Hosting Automation for Cloud Computing Administrator and User Guide

What is ODBC? Database Connectivity ODBC, JDBC and SQLJ. ODBC Architecture. More on ODBC. JDBC vs ODBC. What is JDBC?

Model-View-Controller. and. Struts 2

Chapter 1 Java Program Design and Development

Supplement IV.D: Tutorial for MS Access. For Introduction to Java Programming By Y. Daniel Liang

Example. Represent this as XML

By : Ashish Modi. CRUD USING PHP (Create, Read, Update and Delete on Database) Create Database and Table using following Sql Syntax.

Java Programming. JDBC Spring Framework Web Services

Implementing the Shop with EJB

Transcription:

Java Server Pages and Java Beans Java server pages (JSP) and Java beans work together to create a web application. Java server pages are html pages that also contain regular Java code, which is included between special tags. Java beans are Java programs that follow some specific rules. Together they make up part of a web application. There are several advantages to using Java server pages and beans. One is that the html and the Java code can be kept separate. Another is that the JSP file is a special kind of html file so that it can be placed anywhere on the server and can include any html tags, including references to other pages, images, applets, etc. Java server pages are not only html pages. They are also Java programs, so they must be compiled. This is done the first time that they are accessed. After that, the compiled code resides on the server and can be used as is by any succeeding requests. They are first translated into Java servlets, and then the servlets are compiled into class files. On a stand-alone system, you can find both in the folder work/standalone/localhost/_. Java Server Pages In a JSP file the Java code is contained between tags that begin with <% and end with %>. These tags are also used in active server pages (asp). There are several different kinds of JSP tags depending upon their use. <%= %> is used for expressions. <%! %> is used for declarations. <% %> is used for straight Java code. <%@ %> is used to include another file such as an html file or a package such as java.sql.*. There are some reserved words that may be used by JSP files without further definition. These should be familiar from similar terms used with Java servlets. request an instance of HttpServletRequest. response an instance of HttpServletResponse. out a PrintWriter object for the response. session the HttpSession object associated with the session. Java Beans Java beans are regular Java programs with a few specific restrictions. The constructor may not have any parameters, and the variables all have get and set accessor and mutator methods. The Java server page uses the accessor and mutator methods of the bean to send values to the bean and to get resulting data back from the bean. In a Java bean, you can instantiate other classes, access databases, create lists, tables, and anything else you might want to do. You can also have methods that receive request data from the JSP file. They have the usual request parameter as in the following example: public void processrequest (HttpServletRequest request) } JSP files must declare which bean they are going to use. This is done with tags that follow xml syntax. They are case sensitive and must have closing tags or a closing /. A bean declaration for a simple hello world example follows: <jsp:usebean id = "hello" scope = "session" class = "greetings.hellobean" />

The id for the bean is used in place of a name. The declaration links it to the bean class, HelloBean.class. The Java server page may be located anywhere, but the class file goes in the same classes folder as the servlet classes. HelloBean Example The bean, HelloBean.java, is very simple. We will see more complicated beans later on. It doesn t have a separate constructor, only the default one without parameters. It also does not do anything other than provide a storage place for the data, the name and the email address. Notice it is in a package called greetings. package greetings; public class HelloBean private String name = ""; private String email = ""; public String getname() return name;} public String getemail() return email;} public void setname (String n) name = n;} public void setemail (String e) email = e;} } // HelloBean The Java server page must also set the properties of the bean, i.e. the bean s instance data. This is done with jsp:setproperty tags. These too use xml syntax. <jsp:setproperty name="hello" property="name" value='<%= request.getparameter ("name") %>' /> <jsp:setproperty name="hello" property="email" value='<%= request.getparameter ("email") %>' /> The name attribute is the same as the bean id, hello. The property is the name of the instance variable in the bean. And the value is read from the html input data. The html page used for this example is also very simple. <head><title>hello</title></head> <body bgcolor="white"> <font size=5 color="blue"> <form method="get" action="hello.jsp"> <br />Enter your name and email address: <br /><input type="text" name="name" value="" size="20"> Name <br /><input type="text" name="email" value="" size="20"> Email <p> <input type="submit" name="send" value="send"></p> </form> </font></body></html> The JSP file combines both html and Java code. One that can tie together the html and bean files above follows: <head><title>hello JSP</title></head>

<body bgcolor="white"> <font size=5 color="blue"> <%! String name, email; %> <jsp:usebean id="hello" scope="session" class="greetings.hellobean" /> <jsp:setproperty name="hello" property="name" value='<%= request.getparameter ("name") %>' /> <jsp:setproperty name="hello" property="email" value='<%= request.getparameter ("email") %>' /> <% name = hello.getname(); email = hello.getemail(); %> Hello, your name is <% out.println (name); %> <br />And your email address is <% out.println (email); %> </font></body></html> The result looks like: Hello, your name is Alice Lee And your email address is alee@aol.com where the request data sent by the html file was Alice Lee for the name and alee@aol.com for the e-mail address. The setproperty tags in the Java server page can be replaced by <jsp:setproperty name = "hello" property = "*" /> if the names in the JSP and bean files are the same. This doesn t always work, but in most cases it saves a lot of writing. However, when using this shortcut, there are several conventions that must be followed. First, the accessor and mutator methods must be of the form getemail () setemail (String e) where the identifier in the web page and bean is email. If instead, the variable was called email, the get and set methods would be getemail () setemail (String e) The first letter after the get or set must be capitalized. The rest of the letters follow the capitalization in the variable. This also means that all variables should begin with lower case letters. FindBean Example A somewhat more complicated example can be created to find an object in a database. The database access is done in the bean while the html display is created by the Java server page. The following shows a simple Access table.

A small html page can be used to find the product given the product s name. <head><title>find Product</title></head> <body bgcolor="white"> <form method="get" action="find.jsp"> <br> <font size=5 color="blue"> Enter the name of the product: <br> <input type="text" name="name" value="" size="20"> Name <br /> <br /> <input type="submit" name="action" value="send"> </font> </form> </body></html> In a browser, this looks like: Enter the name of the product: Apples Name Send

The Java server page, find.jsp, contains code to both use the bean, FindBean, and to display the results of the search. The bean is in a package called produce, so it is referred to as "produce.findbean". The bean id may be anything, but calling it FindBean makes it clear what bean is meant. The only method in FindBean other than gets and sets is called processrequest. It has no parameters. <head><title> Find Produce JSP. </title></head> <body bgcolor = "white"> <font size = "4" color="blue"> <jsp:usebean id = "findbean" scope = "session" class = "produce.findbean" /> <jsp:setproperty name = "findbean" property = "*" /> <% findbean.processrequest(); %> <% if (findbean.getfound ()) %> <h4>produce Table</h4> <table border = "1" cellspacing = "5"> <tr> <td><% out.println (findbean.getid()); %></td> <td><% out.println (findbean.gettype()); %></td> <td><% out.println (findbean.getname()); %></td> <td><% out.println (findbean.getvariety()); %></td> <td><% out.println (findbean.getprice()); %></td> </tr> </table> <% } else %> <h4>the product is not in the database.</h4> <% } %> <hr> <p><a href = "../market/find.html">return</a></p> </font> </body></html> If the product is in the database, the result is a table row with the results. But if the product was not found, an error message will be displayed. Produce Table The Return reference takes you back to find.html. AF136 Fruit Apples Red Delicious 1.25 Return

The Java bean, FindBean.java, is quite brief. It accesses the database and uses the results to set the values for the instance variables. package produce; import java.sql.*; import java.io.*; // FindBean locates the product in the database and gets values for the instance variables. public class FindBean private String id, type, name, variety, price; private boolean found; // The accessor methods. public String getid() return id;} public String gettype() return type;} public String getname() return name;} public String getvariety() return variety;} public String getprice() return price;} public boolean getfound () return found;} public void setname (String n) name = n;} // The only set method needed. public void processrequest () try // Get a jdbc-odbc bridge and connect to produce.mdb. Class.forName ("sun.jdbc.odbc.jdbcodbcdriver"); Connection con = DriverManager.getConnection ("jdbc:odbc:produce"); // Create a statement to query the database. Statement stmt = con.createstatement (); String query = "Select * From ProduceTable Where Name = '" + name + "'"; ResultSet rs = stmt.executequery (query); // If the result set is not empty, use the result set to get values for the instance variables. if (rs.next ()) id = rs.getstring ("ID"); type = rs.getstring ("Type"); name = rs.getstring ("Name"); variety = rs.getstring ("Variety"); price = rs.getstring ("Price"); found = true; } else found = false; } catch (ClassNotFoundException e)system.out.println ("Class Not Found exception.\n");} catch (SQLException e)system.out.println ("SQL Exception");} } // processrequest } // FindBean

Displaying the Database The result set that a Select query returns cannot be sent to the Java server page. But the data can be stored in a data structure such as an array, list or hashtable. The following example stores it as a two dimensional array where row 0 contains the column names and the data starts in row 1 column 1. This means that column 0 is never used. But that really doesn t matter. The Java bean for this application has to contact the database and then create the table. The table may then be used by the Java server page to display the data in an html table. The Java bean is shown first. DisplayBean.java // DisplayBean gets data from a database and creates a table containing the data. import java.sql.*; import java.io.*; import javax.servlet.http.*; // DisplayBean gets the data from the database and creates a table called tabledata. public class DisplayBean private String [][] tabledata; private int rows; private int columns; private Connection con; public String [][] gettabledata () return tabledata;} public int getrows () return rows;} public int getcolumns () return columns;} public void settabledata (String [][] t) tabledata = t;} public void setrows (int r) rows = r;} public void setcols (int c) columns = c;} public void processrequest () try // Get a jdbc-odbc bridge and connect to produce.mdb. Class.forName ("sun.jdbc.odbc.jdbcodbcdriver"); con = DriverManager.getConnection ("jdbc:odbc:produce"); // Create a statement to query the database. Statement stmt = con.createstatement (); String query = "Select * From ProduceTable"; ResultSet rs = stmt.executequery (query); ResultSetMetaData metadata = rs.getmetadata (); columns = metadata.getcolumncount ();

// Get a new instance of the table and fill it. tabledata = new String [20][columns+1]; for (int count = 1; count <= columns; count ++) tabledata [0][count] = metadata.getcolumnname (count); rows = 1; while (rs.next ()) for (int col = 1; col<= columns; col ++) tabledata [rows][col] = rs.getstring (col); rows ++; } con.close (); } catch (ClassNotFoundException e)system.out.println ("Class Not Found exception.\n");} catch (SQLException e)system.out.println ("SQL Exception\n");} } // processrequest } // class DisplayBean The Java server page receives the table and uses it to display the results on an html page. display.jsp <head><title> Display Products JSP. </title></head> <body bgcolor="white"> <font size=4 color="blue"> <%! String [][] tabledata; int rows, columns, row, col; %> <jsp:usebean id="displaybean" scope="session" class="produce.displaybean" /> <jsp:setproperty name="displaybean" property="*" /> <% displaybean.processrequest(); %> <h4>produce Table</h4> <% %> tabledata = displaybean.gettabledata (); rows = displaybean.getrows (); columns = displaybean.getcolumns (); <table border='1' bordercolor='blue' cellspacing='10'> <% for (int row = 0; row < rows; row ++) %> <tr> <% for (int col = 1; col <= columns; col ++) %> <td> <% out.println (tabledata [row][col]); %></td> <% } %> </tr> <% } %> </table>

<p><a href="../market/index.html">return</a></p> </font></body></html> References 1. Marty Hall & Larry Brown, Core Servlets and Java Server Pages, First Edition, Sun Microsystems Press/Prentice-Hall PTR Book, 2003. 2. W3 Schools Online Web Tutorials, http://www.w3schools.com.