Presentation is loading. Please wait.

Presentation is loading. Please wait.

WEB TECHNOLOGIES – Unit VIII

Similar presentations


Presentation on theme: "WEB TECHNOLOGIES – Unit VIII"— Presentation transcript:

1 WEB TECHNOLOGIES – Unit VIII
By B. Ravinder Reddy Assistant Professor Department of CSE UNIT -8 WT

2 LECTURE PLAN UNIT-8 Lecture No. Topic Name Slide No. L1 2 -8 L2 9-15
Introduction to JDBC 2 -8 L2 Types of drivers 9-15 L3 Database Programming using JDBC 16-73 L4 Studying Javax.sql.* package 74-81 L5 Accessing a Database from a JSP Page 82-99 L6 Application – Specific Database Actions L7 Deploying JAVA Beans in a JSP Page L8 Introduction to struts framework. UNIT -8 WT

3 LECTURE-1 UNIT -8 WT

4 Introduction to JDBC SQL is a language used to create, manipulate, examine, and manage relational databases. Because SQL is an application-specific language, a single statement can be very expressive and can initiate high-level actions, such as sorting and merging data. SQL was standardized in 1992 so that a program could communicate with most database systems without having to change the SQL commands. Unfortunately, you must connect to a database before sending SQL commands, and each database vendor has a different interface, as well as different extensions of SQL. Enter ODBC. UNIT -8 WT

5 ODBC, a C-based interface to SQL-based database engines, provides a consistent interface for communicating with a database and for accessing database metadata (information about the database system vendor, how the data is stored, and so on). Individual vendors provide specific drivers or "bridges" to their particular database management system. Consequently, thanks to ODBC and SQL, you can connect to a database and manipulate it in a standard way. It is no surprise that, although ODBC began as a PC standard, it has become nearly an industry standard. UNIT -8 WT

6 There are two reasons for this.
Though SQL is well suited for manipulating databases, it is unsuitable as a general application language and programmers use it primarily as a means of communicating with databases--another language is needed to feed SQL statements to a database and process results for visual display or report generation. Unfortunately, you cannot easily write a program that will run on multiple platforms even though the database connectivity standardization issue has been largely resolved. For example, if you wrote a database client in C++, you would have to totally rewrite the client for each platform; that is to say, your PC version would not run on a Macintosh. There are two reasons for this. First, C++ as a language is not portable for the simple reason that C++ is not completely specified, for example, how many bits does an int hold? Second and more importantly, support libraries such as network access and GUI libraries are different on each platform. Enter Java. UNIT -8 WT

7 You can run a Java program on any Java-enabled platform without even recompiling that program.
The Java language is completely specified and, by definition, a Java-enabled platform must support a known core of libraries. One such library is JDBC, which you can think of as a Java version of ODBC, and is itself a growing standard. Database vendors are already busy creating bridges from the JDBC API to their particular systems. JavaSoft has also provided a bridge driver that translates JDBC to ODBC, allowing you to communicate with legacy databases that have no idea that Java exists. Using Java in conjunction with JDBC provides a truly portable solution to writing database applications. The JDBC-ODBC bridge driver is just one of four types of drivers available to support JDBC connectivity. It comes packaged with the JDK 1.1 (and eventually with 1.1 browsers), or as a separate package for use with 1.0 systems. UNIT -8 WT

8 A Complete Example Running through a simple, but complete, example will help you grasp the overall concepts of JDBC. The fundamental issues encountered when writing any database application are: Creating a database. You can either create the database outside of Java, via tools supplied by the database vendor, or via SQL statements fed to the database from a Java program. Connecting to an ODBC data source. An ODBC data source is a database that is registered with the ODBC driver. In Java you can use either the JDBC to ODBC bridge, or JDBC and a vendor-specific bridge to connect to the datasource. UNIT -8 WT

9 Inserting information into a database
Inserting information into a database. Again, you can either enter data outside of Java, using database-specific tools, or with SQL statements sent by a Java program. Selectively retrieving information. You use SQL commands from Java to get results and then use Java to display or manipulate that data UNIT -8 WT

10 LECTURE-2 UNIT -8 WT

11 JDBC Drivers Type I: “Bridge” Type II: “Native” Type III: “Middleware”
Type IV: “Pure” UNIT -8 WT Copyright © 1997 Alex Chaffee

12 JDBC Drivers JDBC Type I “Bridge” ODBC ODBC Driver Type II “Native”
CLI (.lib) Type III “Middleware” Middleware Server Type IV “Pure” UNIT -8 WT Copyright © 1997 Alex Chaffee

13 Type I Drivers Use bridging technology
Requires installation/configuration on client machines Not good for Web e.g. ODBC Bridge UNIT -8 WT Copyright © 1997 Alex Chaffee

14 Type II Drivers Native API drivers
Requires installation/configuration on client machines Used to leverage existing CLI libraries Usually not thread-safe Mostly obsolete now e.g. Intersolv Oracle Driver, WebLogic drivers UNIT -8 WT Copyright © 1997 Alex Chaffee

15 Type III Drivers Calls middleware server, usually on database host
Very flexible -- allows access to multiple databases using one driver Only need to download one driver But it’s another server application to install and maintain e.g. Symantec DBAnywhere UNIT -8 WT Copyright © 1997 Alex Chaffee

16 Type IV Drivers 100% Pure Java Driver (Thin Driver)
Use Java networking libraries to talk directly to database engines Only disadvantage: need to download a new driver for each database engine e.g. Oracle, mySQL UNIT -8 WT Copyright © 1997 Alex Chaffee

17 LECTURE-3 UNIT -8 WT

18 JDBC and Database Programming in Java
UNIT -8 WT Copyright © 1997 Alex Chaffee

19 Introduction JDBC API JDBC Drivers Database Access in Java UNIT -8 WT
Copyright © 1997 Alex Chaffee

20 Why Java? Write once, run anywhere
Multiple client and server platforms Object-relational mapping databases optimized for searching/indexing objects optimized for engineering/flexibility Network independence Works across Internet Protocol Database independence Java can access any database vendor Ease of administration zero-install client UNIT -8 WT Copyright © 1997 Alex Chaffee

21 Database Architectures
Two-tier Three-tier N-tier UNIT -8 WT Copyright © 1997 Alex Chaffee

22 Two-Tier Architecture
Client connects directly to server e.g. HTTP, Pro: simple client-side scripting offloads work onto the client Con: fat client inflexible UNIT -8 WT Copyright © 1997 Alex Chaffee

23 Three-Tier Architecture
Application Server sits between client and database Three-Tier Pros: flexible: can change one part without affecting others can connect to different databases without changing code specialization: presentation / business logic / data management can cache queries can implement proxies and firewalls UNIT -8 WT Copyright © 1997 Alex Chaffee

24 Three-Tier Cons higher complexity higher maintenance
lower network efficiency more parts to configure (and buy) UNIT -8 WT Copyright © 1997 Alex Chaffee

25 N-Tier Architecture Design your application using as many “tiers” as you need Use Object-Oriented Design techniques Put the various components on whatever host makes sense Java allows N-Tier Architecture, especially with RMI and JDBC UNIT -8 WT Copyright © 1997 Alex Chaffee

26 Relational Databases Joining Tables: invented by Dr. E.F.Codd
data stored in records which live in tables maps row (record) to column (field) in a single table “relation” (as in “relational”) means row to column (not table to table) Joining Tables: you can associate tables with one another allows data to nest allows arbitrarily complicated data structures not object-oriented UNIT -8 WT Copyright © 1997 Alex Chaffee

27 Join example People Addresses name homeaddress workaddress id street
state zip UNIT -8 WT Copyright © 1997 Alex Chaffee

28 SQL Structured Query Language
Standardized syntax for “querying” (accessing) a relational database Supposedly database-independent Actually, there are important variations from DB to DB UNIT -8 WT Copyright © 1997 Alex Chaffee

29 SQL Syntax inserts a new record into the named table
INSERT INTO table ( field1, field2 ) VALUES ( value1, value2 ) inserts a new record into the named table UPDATE table SET ( field1 = value1, field2 = value2 ) WHERE condition changes an existing record or records DELETE FROM table WHERE condition removes all records that match condition SELECT field1, field2 FROM table WHERE condition retrieves all records that match condition UNIT -8 WT Copyright © 1997 Alex Chaffee

30 Transactions Transaction = more than one statement which must all succeed (or all fail) together If one fails, the system must reverse all previous actions Also can’t leave DB in inconsistent state halfway through a transaction COMMIT = complete transaction ROLLBACK = abort UNIT -8 WT Copyright © 1997 Alex Chaffee

31 JDBC Goals SQL-Level 100% Pure Java Simple High-performance
Use strong, static typing wherever possible Use multiple methods to express multiple functionality UNIT -8 WT Copyright © 1997 Alex Chaffee

32 JDBC Architecture Application JDBC Driver Java code calls JDBC library
JDBC loads a driver Driver talks to a particular database Can have more than one driver -> more than one database Ideal: can change database engines without changing any application code UNIT -8 WT Copyright © 1997 Alex Chaffee

33 JDBC Drivers Type I: “Bridge” Type II: “Native” Type III: “Middleware”
Type IV: “Pure” UNIT -8 WT Copyright © 1997 Alex Chaffee

34 JDBC Drivers JDBC Type I “Bridge” ODBC ODBC Driver Type II “Native”
CLI (.lib) Type III “Middleware” Middleware Server Type IV “Pure” UNIT -8 WT Copyright © 1997 Alex Chaffee

35 Type I Drivers Use bridging technology
Requires installation/configuration on client machines Not good for Web e.g. ODBC Bridge UNIT -8 WT Copyright © 1997 Alex Chaffee

36 Type II Drivers Native API drivers
Requires installation/configuration on client machines Used to leverage existing CLI libraries Usually not thread-safe Mostly obsolete now e.g. Intersolv Oracle Driver, WebLogic drivers UNIT -8 WT Copyright © 1997 Alex Chaffee

37 Type III Drivers Calls middleware server, usually on database host
Very flexible -- allows access to multiple databases using one driver Only need to download one driver But it’s another server application to install and maintain e.g. Symantec DBAnywhere UNIT -8 WT Copyright © 1997 Alex Chaffee

38 Type IV Drivers 100% Pure Java Driver (Thin Driver)
Use Java networking libraries to talk directly to database engines Only disadvantage: need to download a new driver for each database engine e.g. Oracle, mySQL UNIT -8 WT Copyright © 1997 Alex Chaffee

39 JDBC Limitations No scrolling cursors No bookmarks UNIT -8 WT
Copyright © 1997 Alex Chaffee

40 java.sql Loading a Driver Directly:
JDBC is implemented via classes in the java.sql package Loading a Driver Directly: Driver d = new foo.bar.MyDriver(); Connection c = d.connect(...); Not recommended, use DriverManager instead Useful if you know you want a particular driver UNIT -8 WT Copyright © 1997 Alex Chaffee

41 DriverManager DriverManager tries all the drivers
Uses the first one that works When a driver class is first loaded, it registers itself with the DriverManager Therefore, to register a driver, just load it! UNIT -8 WT Copyright © 1997 Alex Chaffee

42 Registering a Driver statically load driver
Class.forName(“foo.bar.MyDriver”); Connection c = DriverManager.getConnection(...); or use the jdbc.drivers system property UNIT -8 WT Copyright © 1997 Alex Chaffee

43 JDBC Object Classes DriverManager Loads, chooses drivers Driver
connects to actual database Connection a series of SQL statements to and from the DB Statement a single SQL statement ResultSet the records returned from a Statement UNIT -8 WT Copyright © 1997 Alex Chaffee

44 JDBC Class Usage DriverManager Driver Connection Statement ResultSet
UNIT -8 WT Copyright © 1997 Alex Chaffee

45 JDBC URLs jdbc:subprotocol:source each driver has its own subprotocol
each subprotocol has its own syntax for the source jdbc:odbc:DataSource e.g. jdbc:odbc:Northwind jdbc:msql://host[:port]/database e.g. jdbc:msql://foo.nowhere.com:4333/accounting UNIT -8 WT Copyright © 1997 Alex Chaffee

46 DriverManager Connection getConnection
(String url, String user, String password) Connects to given JDBC URL with given user name and password Throws java.sql.SQLException returns a Connection object UNIT -8 WT Copyright © 1997 Alex Chaffee

47 Connection A Connection represents a session with a specific database.
Within the context of a Connection, SQL statements are executed and results are returned. Can have multiple connections to a database NB: Some drivers don’t support serialized connections Fortunately, most do (now) Also provides “metadata” -- information about the database, tables, and fields Also methods to deal with transactions UNIT -8 WT Copyright © 1997 Alex Chaffee

48 Obtaining a Connection
String url = "jdbc:odbc:Northwind"; try { Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con = DriverManager.getConnection(url); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) UNIT -8 WT Copyright © 1997 Alex Chaffee

49 Connection Methods Statement createStatement()
returns a new Statement object PreparedStatement prepareStatement(String sql) returns a new PreparedStatement object CallableStatement prepareCall(String sql) returns a new CallableStatement object Why all these different kinds of statements? Optimization. UNIT -8 WT Copyright © 1997 Alex Chaffee

50 Statement A Statement object is used for executing a static SQL statement and obtaining the results produced by it. UNIT -8 WT Copyright © 1997 Alex Chaffee

51 Statement Methods ResultSet executeQuery(String)
Execute a SQL statement that returns a single ResultSet. int executeUpdate(String) Execute a SQL INSERT, UPDATE or DELETE statement. Returns the number of rows changed. boolean execute(String) Execute a SQL statement that may return multiple results. Why all these different kinds of queries? Optimization. UNIT -8 WT Copyright © 1997 Alex Chaffee

52 ResultSet A ResultSet provides access to a table of data generated by executing a Statement. Only one ResultSet per Statement can be open at once. The table rows are retrieved in sequence. A ResultSet maintains a cursor pointing to its current row of data. The 'next' method moves the cursor to the next row. you can’t rewind UNIT -8 WT Copyright © 1997 Alex Chaffee

53 ResultSet Methods boolean next() activates the next row
the first call to next() activates the first row returns false if there are no more rows void close() disposes of the ResultSet allows you to re-use the Statement that created it automatically called by most Statement methods UNIT -8 WT Copyright © 1997 Alex Chaffee

54 ResultSet Methods Type getType(int columnIndex)
returns the given field as the given type fields indexed starting at 1 (not 0) Type getType(String columnName) same, but uses name of field less efficient int findColumn(String columnName) looks up column index given column name UNIT -8 WT Copyright © 1997 Alex Chaffee

55 ResultSet Methods String getString(int columnIndex)
boolean getBoolean(int columnIndex) byte getByte(int columnIndex) short getShort(int columnIndex) int getInt(int columnIndex) long getLong(int columnIndex) float getFloat(int columnIndex) double getDouble(int columnIndex) Date getDate(int columnIndex) Time getTime(int columnIndex) Timestamp getTimestamp(int columnIndex) UNIT -8 WT Copyright © 1997 Alex Chaffee

56 ResultSet Methods String getString(String columnName)
boolean getBoolean(String columnName) byte getByte(String columnName) short getShort(String columnName) int getInt(String columnName) long getLong(String columnName) float getFloat(String columnName) double getDouble(String columnName) Date getDate(String columnName) Time getTime(String columnName) Timestamp getTimestamp(String columnName) UNIT -8 WT Copyright © 1997 Alex Chaffee

57 isNull In SQL, NULL means the field is empty Not the same as 0 or “”
In JDBC, you must explicitly ask if a field is null by calling ResultSet.isNull(column) UNIT -8 WT Copyright © 1997 Alex Chaffee

58 Sample Database Employee ID Last Name First Name 1 Davolio Nancy 2 Fuller Andrew 3 Leverling Janet 4 Peacock Margaret 5 Buchanan Steven UNIT -8 WT Copyright © 1997 Alex Chaffee

59 SELECT Example Connection con = DriverManager.getConnection(url, "alex", " "); Statement st = con.createStatement(); ResultSet results = st.executeQuery("SELECT EmployeeID, LastName, FirstName FROM Employees"); UNIT -8 WT Copyright © 1997 Alex Chaffee

60 SELECT Example (Cont.) while (results.next()) { int id = results.getInt(1); String last = results.getString(2); String first = results.getString(3); System.out.println("" + id + ": " + first + " " + last); } st.close(); con.close(); UNIT -8 WT Copyright © 1997 Alex Chaffee

61 Mapping Java Types to SQL Types
SQL type Java Type CHAR, VARCHAR, LONGVARCHAR String NUMERIC, DECIMAL java.math.BigDecimal BIT boolean TINYINT byte SMALLINT short INTEGER int BIGINT long REAL float FLOAT, DOUBLE double BINARY, VARBINARY, LONGVARBINARY byte[] DATE java.sql.Date TIME java.sql.Time TIMESTAMP java.sql.Timestamp UNIT -8 WT Copyright © 1997 Alex Chaffee

62 Database Time Times in SQL are notoriously unstandard
Java defines three classes to help java.sql.Date year, month, day java.sql.Time hours, minutes, seconds java.sql.Timestamp year, month, day, hours, minutes, seconds, nanoseconds usually use this one UNIT -8 WT Copyright © 1997 Alex Chaffee

63 Modifying the Database
use executeUpdate if the SQL contains “INSERT” or “UPDATE” Why isn’t it smart enough to parse the SQL? Optimization. executeUpdate returns the number of rows modified executeUpdate also used for “CREATE TABLE” etc. (DDL) UNIT -8 WT Copyright © 1997 Alex Chaffee

64 Transaction Management
Transactions are not explicitly opened and closed Instead, the connection has a state called AutoCommit mode if AutoCommit is true, then every statement is automatically committed default case: true UNIT -8 WT Copyright © 1997 Alex Chaffee

65 setAutoCommit Connection.setAutoCommit(boolean)
if AutoCommit is false, then every statement is added to an ongoing transaction you must explicitly commit or rollback the transaction using Connection.commit() and Connection.rollback() UNIT -8 WT Copyright © 1997 Alex Chaffee

66 Connection Managers Hint: for a large threaded database server, create a Connection Manager object It is responsible for maintaining a certain number of open connections to the database When your applications need a connection, they ask for one from the CM’s pool Why? Because opening and closing connections takes a long time Warning: the CM should always setAutoCommit(false) when a connection is returned UNIT -8 WT Copyright © 1997 Alex Chaffee

67 Optimized Statements Prepared Statements
SQL calls you make again and again allows driver to optimize (compile) queries created with Connection.prepareStatement() Stored Procedures written in DB-specific language stored inside database accesed with Connection.prepareCall() UNIT -8 WT Copyright © 1997 Alex Chaffee

68 JDBC Class Diagram Whoa! UNIT -8 WT Copyright © 1997 Alex Chaffee

69 Metadata Connection: DatabaseMetaData getMetaData() ResultSet:
ResultSetMetaData getMetaData() UNIT -8 WT Copyright © 1997 Alex Chaffee

70 ResultSetMetaData What's the number of columns in the ResultSet?
What's a column's name? What's a column's SQL type? What's the column's normal max width in chars? What's the suggested column title for use in printouts and displays? What's a column's number of decimal digits? Does a column's case matter? Is the column a cash value? UNIT -8 WT Copyright © 1997 Alex Chaffee

71 Will a write on the column definitely succeed?
Can you put a NULL in this column? Is a column definitely not writable? Can the column be used in a where clause? Is the column a signed number? Is it possible for a write on the column to succeed? and so on... UNIT -8 WT

72 DatabaseMetaData What tables are available?
What's our user name as known to the database? Is the database in read-only mode? If table correlation names are supported, are they restricted to be different from the names of the tables? and so on… UNIT -8 WT Copyright © 1997 Alex Chaffee

73 JDBC 2.0 Scrollable result set Batch updates Advanced data types
Blobs, objects, structured types Rowsets Persistent JavaBeans JNDI Connection Pooling Distributed transactions via JTS UNIT -8 WT Copyright © 1997 Alex Chaffee

74 Where to get more information
Other training sessions Reese, Database Programming with JDBC and Java (O’Reilly) (Author’s site) UNIT -8 WT Copyright © 1997 Alex Chaffee

75 LECTURE-4 UNIT -8 WT

76 Studying javax.sql package
This package provides the APIs for accessing and processing data which is stored in the database especially relational database by using the java programming language. It includes a framework where we different drivers can be installed dynamically to access different databases especially relational databases. This java.sql package contains API for the following : 1. Making a connection with a database with the help of DriverManager class a) DriverManager class: It helps to make a connection with the driver.  UNIT -8 WT

77 b) SQLPermission class: It provides a permission when the code is running within a Security Manager, such as an applet. It attempts to set up a logging stream through the DriverManager class.  c) Driver interface : This interface is mainly used by the DriverManager class for registering and connecting drivers based on JDBC technology. d). DriverPropertyInfo class : This class is generally not used by the general user. UNIT -8 WT

78 2)Sending SQL Parameters to a database : a) Statement interface: It is used to send basic SQL statements.  b) PreparedStatement interface: It is used to send prepared statements or derived SQL statements from the Statement object.  c) CallableStatement interface : This interface is used to call database stored procedures. d) Connection interface : It provides methods for creating statements and managing their connections and properties.  e) Savepoint : It helps to make the savepoints in a transaction. UNIT -8 WT

79 3)Updating and retrieving the results of a query: a) ResultSet interface: This object maintains a cursor pointing to its current row of data. The cursor is initially positioned before the first row. The next method of the resultset interface moves the cursor to the next row and it will return false if there are no more rows in the ResultSet object. By default ResultSet object is not updatable and has a cursor that moves forward only. UNIT -8 WT

80 4.) Providing Standard mappings for SQL types to classes and interfaces in Java Programming language. a) Array interface: It provides the mapping for SQL Array. b) Blob interface : It provides the mapping for SQL Blob. c) Clob interface: It provides the mapping for SQL Clob. d) Date class: It provides the mapping for SQL Date.  e) Ref interface: It provides the mapping for SQL Ref. f) Struct interface: It provides the mapping for SQL Struct. g) Time class: It provides the mapping for SQL Time. h) Timestamp: It provides the mapping for SQL Timestamp. i) Types: It provides the mapping for SQL types. UNIT -8 WT

81 b)SQLWarning: This exception is thrown to indicate the warning.
5) Metadata a) DatabaseMetaData interface: It keeps the data about the data. It provides information about the database. b) ResultSetMetaData: It gives the information about the columns of a ResultSet object.  c) ParameterMetaData: It gives the information about the parameters to the PreparedStatement commands. 6) Exceptions a) SQLException: It is thrown by the mehods whenever there is a problem while accessing the data or any other things. b)SQLWarning: This exception is thrown to indicate the warning.  c)BatchUpdateException: This exception is thrown to indicate that all commands in a batch update are not executed successfully. d)DataTruncation: It is thrown to indicate that the data may have been truncated. UNIT -8 WT

82 7). Custom mapping an SQL user- defined type (UDT) to a class in the java programming language. a) SQLData interface: It gives the mapping of a UDT to an intance of this class. b) SQLInput interface: It gives the methods for reading UDT attributes from a stream. c) SQLOutput: It gives the methods for writing UDT attributes back to a stream. UNIT -8 WT

83         LECTURE-5 UNIT -8 WT

84 Accessing database from JSP
we take a example of Books database. This database contains a table named books_details. This table contains three fields- id,book_name& author. we starts from very beginning. First we learn how to create tables in MySQl database after that we write a html page for inserting the values in 'books_details' table in database. After submitting values a table will be showed that contains the book name and author name. Database : The database in example consists of a single table of three columns or fields. The database name is "books" and it contains information about books names & authors. UNIT -8 WT

85 Table:books_details ID Book Name Author 1. 2. 3 Java I/O Tim Ritchey
1.   Java I/O Tim Ritchey 2.   Java & XML,2 Edition     Brett McLaughlin  3  Java Swing, 2nd Edition  Dave Wood, Marc Loy, UNIT -8 WT

86 Start MYSQL prompt and type this SQL statement & press Enter-
MYSQL>CREATE DATABASE `books`; This will create "books" database. Now we create table a table "books_details" in database "books".  MYSQL>CREATE TABLE `books_details` (    `id` INT( 11 ) NOT NULL AUTO_INCREMENT ,    `book_name` VARCHAR( 100 ) NOT NULL ,     `author` VARCHAR( 100 ) NOT NULL ,      PRIMARY KEY ( `id` ) ) TYPE = MYISAM ; This will create a table "books_details" in database "books" UNIT -8 WT

87 JSP Code The following code contains  html for user interface & the JSP backend- page language="java“ import="java.sql.*" %> <% String driver = "org.gjt.mm.mysql.Driver"; Class.forName(driver).newInstance(); Connection con=null; ResultSet rst=null; Statement stmt=null; try { String url="jdbc:mysql://localhost/books?user= <user>&password=<password>"; UNIT -8 WT

88 con=DriverManager.getConnection(url); stmt=con.createStatement();
} catch(Exception e) { System.out.println(e.getMessage()); if(request.getParameter("action") != null){  String bookname=request.getParameter("bookname"); String author=request.getParameter("author"); stmt.executeUpdate("insert into books_details(book_name, author) values('"+bookname+"','"+author+"')"); UNIT -8 WT

89 <td><b>S.No</b></td>
rst=stmt.executeQuery("select * from books_details"); %> <html> <body> <center> <h2>Books List</h2> <table border="1" cellspacing="0" cellpadding ="0"> <tr> <td><b>S.No</b></td> <td><b>Book Name</b></td> <td><b>Author</.b></td> </tr> <% int no=1; while(rst.next()) { %> UNIT -8 WT

90 <tr> <td><%=no%></td> <td><%=rst
<tr> <td><%=no%></td> <td><%=rst.getString(" book_name")%></td> <td> <%=rst.getString("author") %> </td> </tr> <% no++; } rst.close(); stmt.close(); con.close(); %> </table> </center> </body> </html> <%}else{%> <html> <head> <title>Book Entry FormDocument</title> <script language="javascript"> UNIT -8 WT

91 function validate(objForm){ if(objForm. bookname. value
function validate(objForm){ if(objForm.bookname.value.length==0){ alert("Please enter Book Name!"); objForm.bookname.focus(); return false; } if(objForm.author.value.length==0){ alert("Please enter Author name!"); objForm.author.focus(); return true; } </script> </head> UNIT -8 WT

92 <body> <center> <form action="BookEntryForm
<body> <center> <form action="BookEntryForm.jsp" method="post" name="entry" onSubmit="return validate(this)"> <input type="hidden" value="list" name="action"> <table border="1" cellpadding="0" cellspacing="0"> <tr> <td> <table> <tr> <td colspan="2" align="center"> <h2>Book Entry Form</h2></td> </tr> <tr> <td colspan="2"> </td> </tr> <tr> <td>Book Name:</td> <td><input name="bookname" type= "text" size="50"></td> </tr> <tr> <td>Author:</td><td><input name= "author" type="text" size="50"></td> UNIT -8 WT

93 </tr> <tr> <td colspan="2" align="center"> <input type="submit" value="Submit"></td> </tr> </table> </td></tr> </form> </center> </body> </html> <%}%> UNIT -8 WT

94 Connection con=null; ResultSet rst=null; Statement stmt=null;
Now we explain the above  codes. Declaring Variables: Java is a strongly typed language which means, that variables must be explicitly declared before use and must be declared with the correct data types. In the above example code we declare some variables for making connection. Theses variables are-  Connection con=null; ResultSet rst=null; Statement stmt=null; The objects of type Connection, ResultSet and Statement are associated with the Java sql. "con" is a Connection type object variable that will hold Connection type object. "rst" is a ResultSet type object variable that will hold a result set returned by a database query. "stmt" is a object variable of Statement .Statement Class methods allow to execute any query.   UNIT -8 WT

95 Connection to database: The first task of this programmer is to load database driver. This is achieved using the single line of code :- String driver = "org.gjt.mm.mysql.Driver"; Class.forName(driver).newInstance(); The next task is to make a connection. This is done using the single line of code :- String url="jdbc:mysql://localhost/books?user=<userName>&password=<password>"; con=DriverManager.getConnection(url); When url is passed into getConnection() method of DriverManager class it  returns connection object.    UNIT -8 WT

96 Executing Query or Accessing data from database:
This is done using following code :-stmt=con.createStatement(); //create a Statement object  rst=stmt.executeQuery("select * from books_details"); stmt is the Statement type variable name and rst is the RecordSet type variable. A query is always executed on a Statement object. A Statement object is created by calling createStatement() method on connection object con.  The two most important methods of this Statement interface are executeQuery() and executeUpdate().  The executeQuery() method executes an SQL statement that returns a single ResultSet object. UNIT -8 WT

97  The executeUpdate() method executes an insert, update, and delete SQL statement.
The method returns the number of records affected by the SQL statement execution. After creating a Statement ,a method executeQuery() or  executeUpdate() is called on Statement object stmt and a SQL query string is passed in method executeQuery() or  executeUpdate(). This will return a ResultSet rst related to the query string. UNIT -8 WT

98 Reading values from aResultSet:
while(rst.next()){ %> <tr><td><%=no%></td><td><%=rst.getString("book_name")%></td><td><%=rst.getString("author")%></td></tr> <%  } The ResultSet  represents a table-like database result set. A ResultSet object maintains a cursor pointing to its current row of data.  Initially, the cursor is positioned before the first row. Therefore, to access the first row in the ResultSet, you use the next()method. This method moves the cursor to the next record and returns true if the next row is valid, and false if there are no more records in the ResultSet object. UNIT -8 WT

99 resultSet.getString(2);
Other important methods are getXXX() methods, where XXX is the data type returned by the method at the specified index, including String, long, and int. The indexing used is 1-based. For example, to obtain the second column of type String, you use the following code: resultSet.getString(2); You can also use the getXXX() methods that accept a column name instead of a column index. For instance, the following code retrieves the value of the column LastName of type String. resultSet.getString("book_name"); UNIT -8 WT

100 The above example shows how you can use the next() method as well as the getString() method.
Here you retrieve the 'book_name' and 'author' columns from a table called 'books_details'. You then iterate through the returned ResultSet and print all the book name and author name in the format " book name | author " to the web page. UNIT -8 WT

101 LECTURE-6 UNIT -8 WT

102 Application – Specific Database Actions
The database providers for the Web Deployment Tool (WebDeploy) give application developers a great deal of flexibility in setting up databases as part of their application installs.  Outside of the Gallery, applications have a variety of methods for setting up databases, tables, users, and starting data: Some applications can do everything necessary, as long as the user can provide administrative credentials during the application setup.  These applications usually have the flexibility to work with any database components that have already been configured, and can work without administrative credentials in those cases. UNIT -8 WT

103 Some applications will use any combination of the above.
Some applications expect the database and the database user to be created before running the application for the first time. Some applications expect all of these steps to be done before running the application for the first time. Some applications will use any combination of the above. The WebDeploy database providers give the application developer the ability to perform whatever database functions are required prior to the application’s first run.  There are three WebDeploy components involved in specifying database installation directives. UNIT -8 WT

104 The provider directive in the manifest. xml file
The provider directive in the manifest.xml file.  This directive tells WebDeploy which database provider to use, and what file to use for the script. The connection string in the parameters.xml file.  This tells Web Deploy what credentials to use, and what database and server to connect to. The SQL Script.  This is a standalone file that can contain any valid database commands for the specific database engine you are using. UNIT -8 WT

105 The minimal provider directive identifies the provider to use and the SQL file to use it on:
</msdeploy.iisapp>    <dbfullsql path="install.sql" />  </msdeploy.iisapp> This example tells WebDeploy to use the MS SQL (dbfullsql) provider and to run a file called "install.sql". The connection string is usually put together from other parameters in the parameters.xml file.  The App Packaging Guide contains a description of the requirements for these parameters, and examples of how to use them and put them together. UNIT -8 WT

106 Database Password - The password for the Database User.
When using one of the database providers, the user will need to provide credentials for WebDeploy to use to communicate with the database.  Even though these credentials are used somewhat differently for the different databases, they are all present in some form for each.  These credentials consist of: Database Server - This can be the hostname or IP address of a server, or the service name for the database server. Database Name  - The name of the database on the server that the application will use Database User - This is the user that is used specifically for WebDeploy to connect to the database and, if necessary, perform database operations. Database Password - The password for the Database User. UNIT -8 WT

107 In addition to these credentials, applications will usually need an ID and password specific to the application.  Application developers can use the WebDeploy tool to prompt the user for these credentials as well.  Then the credentials can be placed in configuration files or SQL scripts to be used by the application. The SQL Script can be any valid SQL or commands that the database engine will accept.  The contents of this file can be parameterized the same way as any other file in the distribution.  UNIT -8 WT

108 Connect to the database server. Authenticate as the database user.
The SQL file can also be empty if you just want to use the provider to ensure that the database already exists.  Most of our current applications use this SQL to create a database user for the application to use. Examples of the syntax for each engine are covered in their respective sections. The providers will follow these steps in communicating with a database: Connect to the database server. Authenticate as the database user. Check to see if the database exists, and if the user has access to it. UNIT -8 WT

109 Execute the contents of the database script.
If the database does not exist, WebDeploy will attempt to create it using the provided credentials. If the database creation fails, then WebDeploy will exit with a message telling the user that the user does not have sufficient privileges for the required tasks. Execute the contents of the database script. UNIT -8 WT

110 LECTURE-7 UNIT -8 WT

111 Deploying JAVA Beans in a JSPPage
Starting WebSphere: The IBM WebSphere documentation includes more information on how to start and stop WebSphere. Here are the basic steps if you are using WebSphere with the IBM HTTP Server: Using the Services control panel applet, start both the IBM HTTP Server and IBM HTTP Administrationservices. The Services control panel applet is located in the Control Panel on Windows NT, and under the Administrative Tools folder under the Control Panel on Windows 2000/XP. Open a command prompt and change directory to the bin directory under your WebSphere installation. By default, this will be C:\WebSphere\AppServer\bin. UNIT -8 WT

112 Execute the batch file startServerBasic
Execute the batch file startServerBasic.bat, this will launch WebSphere using the console window for diagnostic messages, this is more convenient than referring to the log files for stdout and stderr to see messages from WebSphere. You will know that WebSphere has been fully initialized when you see the phrase Server open for e-business in the console window.  UNIT -8 WT

113 Use the following steps to create a New Stateless Session Bean.
Creating a Simple EJB Our Session Bean will be named MySessionEJB, will contain one field called info, and have a corresponding getInfo and setInfo method on the bean. Use the following steps to create a New Stateless Session Bean.  From the Main Menu, choose File | New. In the New dialog that appeared, select the Projects category. Select the Workspace Item on the right side of the dialog and click OK. Accept the defaults for the New Workspace dialog by clicking OK. Accept the defaults for the New Project dialog by clicking OK. UNIT -8 WT

114 Select the Enterprise JavaBeans category on the left of the dialog.
In the navigator, right-click the newly created project node, and select New from the context menu. Select the Enterprise JavaBeans category on the left of the dialog. Select the Stateless Session Bean item on the right of the dialog and click OK. Immediately click Finish. This will create a default Session Bean called MySessionBean. In the navigator, right-click the MySessionEJB node and select EJB Class Editor from the context menu. In the EJB Class Editor, select the Fields tab. Click the Add button at the top of the editor. In the Field Name text field, enter "info", and click OK. Choose File | Save All to save your work. Close the EJB Class Editor. UNIT -8 WT

115 Creating the Test Client for WebSphere
We will create a simple Java Server Page (JSP) to test the Enterprise JavaBean. The JSP will look up an instance of our SessionBean (MySessionBean), and set the "info" property on the bean. It will then display the value of the "info" property using a call to "getInfo". Here are the steps to create a simple JSP to test our EJB: In the navigator, right-click the Project node and choose New. Select the category Web Objects. Select the item JSP. On the New JSP dialog that has appeared, change the name to index.jsp and click the OK button. In the navigator, double click the newly created index.jsp node. Replace the text of the JSP with the following: UNIT -8 WT

116 page contentType="text/html;charset=windows-1252"%> page import="javax.naming.*,mypackage.*" %> <HTML> <HEAD> <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=windows-1252"> <TITLE> Hello World </TITLE> </HEAD> <BODY> UNIT -8 WT

117 <% Context ctx = new InitialContext();
Object ref = ctx.lookup( "MySessionEJB" ); MySessionEJBHome mySessionEJBHome = ( MySessionEJBHome)javax.rmi.PortableRemoteObject.narrow( ref, MySessionEJBHome.class ); MySessionEJB mySessionEJB = mySessionEJBHome.create( ); mySessionEJB.setInfo( "Hello World" ); out.println( mySessionEJB.getInfo() ); %> </BODY> </HTML> UNIT -8 WT

118 Testing the EJB locally with the embedded OC4J
It is quite simple to test our JSP which invokes an EJB in the embedded OC4J that is included with Oracle9iJDeveloper. Here are the steps: In the navigator, right-click the node index.jsp and select Run index.jsp from the context menu. Your web browser should be launched on the URL to see the JSP page. The page will simply display "Hello World". Notice the URL which is used in your web browser. The only difference in this URL and the one to use with WebSphere is the port number. By default the embedded OC4J instance uses port 8988 and WebSphere uses ports80 and 9080 by default for user applications. UNIT -8 WT

119 Creating the Deployment Profiles
We must create three deployment profiles before we can deploy our J2EE application to WebSphere. They are as follows: J2EE EJB Module (EJB JAR file) J2EE Web Module (WAR file) J2EE Application (EAR file) This is not as bad as it seems since the EAR file simply contains the EJB JAR file and the WAR file. The EAR file is just a convenient wrapper to load your entire J2EE application into an Application Server or to a client machine at once. UNIT -8 WT

120 In the Save Deployment Profile dialog, click OK.
We will quickly create all three deployment profiles, here are the steps: In the navigator, right-click the project node and choose New from the context menu. Select the Deployment Profiles category from the right side of the dialog. Select J2EE EJB Module (EJB JAR file) from the items list on the right side of the dialog. In the Save Deployment Profile dialog, click OK. In the J2EE EJB Module Deployment Profile Settings dialog, click OK. Repeat Steps 1 and 2. Select J2EE Web Module (WAR file) from the items list on the right side of the dialog. UNIT -8 WT

121 In the Save Deployment Profile dialog, click OK.
Repeat Steps 4 and 5. Repeat Steps 1 and 2 Select J2EE Application (EAR file) from the items list on the right side of the dialog. In the Save Deployment Profile dialog, click OK. In the J2EE Application Deployment Profile Settings dialog, select the node Application Assembly. In the tree on the right side of the dialog, check both ejb1.deploy and webapp1.deploy. Click OK. Choose File | Save All. In the navigator, right-click the deployment profile application1.deploy, and choose Deploy to EAR from the context menu. This will create a file named application1.ear located in your projects directory. UNIT -8 WT

122 Deploying the EJB jar File to WebSphere
The basic steps to deploy an EJB contained within an EAR file follow the pattern of deploy the archive, save the configuration, and then restart the application server. Here are step-by-step instructions for these activities. Launch the web based administration interface for WebSphere by launching your web browser on the URLhttp://localhost:9090/admin. This is the default port of the IBM HTTP Administration server which contains the web based administration tool. Enter any user name in the text field. This user name is only used for tracking changes to the configuration files for auditing purposes. Click the Submit button. UNIT -8 WT

123 In the tree on the left hand side of the web browser, expand the Nodes node in the tree, and then expand the node for your machine name. (This should be the only item in the tree under the Nodes node) Under the node for your machine name, select the node Enterprise Applications, this will open the editor for your Enterprise Beans and Web Applications on the right side. On the right side, click the Install button. This will invoke the Application Installation Wizard that will be used to deploy your EAR file. Near the top of this page, you will see a text field labeled "Path" with a Browse button to the right. Click theBrowse button and locate the EAR file application1.ear that was created as part of creating the deployment profiles. Click the Next button. UNIT -8 WT

124 Near the top of this page, you will see a text field labeled "Path" with a Browse button to the right. Click theBrowse button and locate the EAR file application1.ear that was created as part of creating the deployment profiles. Click the Next button. In the only text field on the page titled Binding Enterprise Beans to JNDI Names, change the JNDI name from the original value of mypackage/EJSStatelessMySessionEJBHomeBean to MySessionEJB. On the next page which is titled: Specifying Virtual Host names and Precompiled JSP option for Web Modules, leave the values at their default and click the Next button. On the next page that is titled: Confirm the following: just click Finish. UNIT -8 WT

125 Execute the batch file stopServer.bat. This will stop WebSphere.
Look at the console window which executed the startServerBasic batch file, you will see many lines of diagnostic information. When finished, it should end in something like "[ :43:17:185 PST] SystemOut U 0 Errors, 0 Warnings, 0 Informational Messages" Now you must save the configuration of WebSphere, click the Save link at the top of the web browser. Now click the Save button to save your configuration to the original configuration file, and not a secondary copy. Before the EJB and JSP can be invoked WebSphere must be restarted. Open a command prompt and change directories to the bin directory under your WebSphere installation. By default, this will beC:\WebSphere\AppServer\bin. Execute the batch file stopServer.bat. This will stop WebSphere. Now start WebSphere again, following the same steps as before. UNIT -8 WT

126 Now the JSP and EJB are ready to be executed.
Testing the EJB in WebSphere The URL that the web browser uses will be the same as used in the step Testing the EJB locally with the embedded OC4J with the port number changed from 8988 to 80. The default URL is  Launch your web browser. In the address line, type  press Enter. Verify that "Hello World" is displayed in the web browser. UNIT -8 WT

127 LECTURE-8 UNIT -8 WT

128 Struts UNIT -8 WT

129 Agenda Introduction ”C” in MVC ”M” in MVC ”V” in MVC Workflow
Configuring Struts configuration file Struts custom tags Validator framework File upload Pros and Cons UNIT -8 WT

130 Introduction Struts is a framework to develop MVC model 2 applications
Provides its own controller Separates presentation logic and business logic Open source Approximately 300 java classes divided into 8 top level packages Struts resides in the web tier UNIT -8 WT

131 Struts applications are hosted by a web container
Makes heavy use of request and response objects Named in the architectural sense meaning nearly invisible pieces holding up buildings Support different model implementations (Java bean,EJB etc) Supports different view implementations (JSP,XML/XSL UNIT -8 WT

132 Introduction org.apache.struts.action org.apache.struts.actions
Struts packages org.apache.struts.action org.apache.struts.actions org.apache.struts.config org.apache.struts.taglib org.apache.struts.upload org.apache.struts.tiles org.apache.struts.util org.apache.struts.validator Jar struts.jar UNIT -8 WT

133 “C” in MVC Controller component responsibilities
Receive request from client Map request to specific business operation Determine the view to display based on the result of the business operation Controller is implemented by the ActionServlet, RequestProcessor and Action classes ActionServlet Extends HttpServlet Forwards the request to RequestProcessor This in turn forwards the request to helper class (which is a subclass of org.apache.struts.action.Action class) UNIT -8 WT

134 “C” in MVC ActionServlet must be configured in web.xml <servlet> <servlet-name>action</servlet-name> <servlet-class> org.apache.struts.action.ActionServlet </servlet-class> <init-param> <param-name>config</param-name> <param-value> WEB-INF/struts-config.xml </param-value> </init-param> UNIT -8 WT

135 <servlet-mapping>
<servlet-name>action</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> Config parameter should contain the path of the default struts config file. UNIT -8 WT

136 “C” in MVC Container will load the ActionServlet either when starting the server or when the first request arrives for the servlet. Init() method will be called before any request is processed by the servlet. Performs compulsory initializations like initializing the message bundle, struts configuration data, data sources, plug-ins etc. Users can extend the ActionServlet class. One instance of this servlet class receives and processes all requests UNIT -8 WT

137 Delegates the handling of the request to RequestProcessor object
RequestProcessor selects and invokes an Action class to perform the requested business operation Users can extend the RequestProcessor class. UNIT -8 WT

138 “C” in MVC Action class is the heart of the struts framework
Bridge between a client request and a business operation One action class for one business operation Most important method is the execute method which will be called by the controller when a request is received from a client Signature of the execute method: public ActionForward execute(ActionMapping mapping, ActionForm form, javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws java.lang.Exception UNIT -8 WT

139 “C” in MVC Single instance processes many requests, so care should be taken to ensure that they operate properly in multithreaded environment Can create a base action class (which can contain common logic like checking session timeout etc) and let all other action classes extend the base action class. EncorrAction extends Action OutgoingLogAction extends EncorrAction IncomingLogAction extends EncorrAction UNIT -8 WT

140 “C” in MVC DispatchAction class Extends Action class
Used to combine many similar actions into a single action class (to combine add, modify and view actions) Dispatches to a public method whose signature should be exactly same as the execute method For ex we can have 3 three methods in the same action class public ActionForward insert(ActionMapping mapping………… public ActionForward update(ActionMapping mapping………… public ActionForward delete(ActionMapping mapping………… UNIT -8 WT

141 will call the update method. EncorrAction extends DispatchAction
will call the update method. EncorrAction extends DispatchAction OutgoingLogAction extends EncorrAction IncomingLogAction extends EncorrAction UNIT -8 WT

142 “C” in MVC To summarize controller consists of ActionServlet
RequestProcessor Action/DispatchAction Classes in action package Action ActionForm ActionForward ActionMapping UNIT -8 WT

143 “M” in MVC Model consists of data and the functions that operate on data Java bean that we use to store data is a model component EJB can also be used as a model component UNIT -8 WT

144 “V” in MVC View can be a HTML JSP Struts ActionForm
Struts framework automatically collects input from request, passes this data to an Action using a form bean which can then be passed to the business layer. An ActionForm is a JavaBean optionally associated with one or more ActionMappings. Such a bean will have had its properties initialized from the corresponding request parameters before the corresponding Action.execute method is called. UNIT -8 WT

145 “V” in MVC Sample ActionForm bean
public class UploadForm extends ActionForm { protected String myText; protected FormFile myFile; public void setMyText(String text) myText = text; } public String getMyText() return myText; UNIT -8 WT

146 public void setMyFile(FormFile file) { myFile = file; }
public FormFile getMyFile() return myFile; UNIT -8 WT

147 “V” in MVC Struts DynaActionForm
Specialized subclass of ActionForm that allows the creation of form beans with dynamic sets of properties, without requiring the developer to create a Java class for each type of form bean. So to summarize view consists of HTML JSP or XML/XSL ActionForm/ DynaActionForm UNIT -8 WT

148 Workflow MVC UNIT -8 WT

149 Workflow Workflow UNIT -8 WT

150 Workflow Workflow UNIT -8 WT

151 Workflow The ActionServlet receives the request.
Based on the request URI, the ActionServlet retrieves the ActionMapping that defines the request. The ActionServlet populates the ActionForm object from the HTTP request. If the ActionMapping specifies that validation is required, the ActionServlet calls the validate() method on the ActionForm object. UNIT -8 WT

152 back to the browser. The ActionServlet invokes the execute() method of the Action object, providing the ActionForm object as a parameter. The method returns an ActionForward object specifying where to forward the request. The ActionServlet forwards the request to the resource specified in the ActionForward object. This is typically a JSP (the view), but it can send the request to another Action. It sends the response UNIT -8 WT

153 Configuring Struts Configuration File
ApplicationResources.properties Element/Value pairs (multi-lingual support) Easy to change properties referenced in many places in the page Can have multiple files for different languages Sample errors.required={0} is required. errors.minlength={0} can not be less than {1} characters. errors.maxlength={0} can not be greater than {1} characters. exception.outgoinglogcreate.action.error = Internal Server Error in Create Outgoing Log exception.outgoinglogupdate.action.error = Internal Server Error in Update Outgoing Log UNIT -8 WT

154 Configuring Struts Configuration File
Struts config file Core of struts Ties all the components of the struts application together 2 main parts are form bean and action mappings Sections of struts-config.xml Data source Form bean (Form property) Exception Forward Action Controller Message Resources PlugIn UNIT -8 WT

155 Classes in config package ApplicationConfig
Each class in org.apache.struts.config package holds information from the specific section of the configuration file Classes in config package ApplicationConfig Holds configuration information that describes an entire struts application DataSourceConfig Holds information about data source. UNIT -8 WT

156 Configuring Struts Configuration File
FormBeanConfig To configure multiple DynaActionForm classes that are used by the views FormPropertyConfig To configure form properties <form-beans> <form-bean name=“newOutgoingLog“ type="org.apache.struts.action.DynaActionForm"> <form-property name=“ccTo" type="java.lang.String" /> <form-property name=“subject" type="java.lang.Integer" initial=”NewsLetter”/> </form-bean> <form-bean name=“newIncomingLog“ type="org.apache.struts.action.DynaActionForm"> <form-property name=“dueDate" type="java.lang.String" /> <form-property name=“assignee" type="java.lang.Integer" initial=”NewsLetter”/> </form-beans> UNIT -8 WT

157 Configuring Struts Configuration File
In execute method of Action class, import org.apache.commons.beanutils.BeanUtils; DynaActionForm dynaActionForm = (DynaActionForm)form; OutgoingLogBean outgoingLogBean = new OutgoingLogBean(); BeanUtils.copyProperties(outgoingLogBean,dynaActionForm); UNIT -8 WT

158 Configuring Struts Configuration File
ExceptionConfig Describes a mapping between a java exception and a handler which is responsible for dealing with the exception 2 types 1.Global exception 2.Action specific exception Global Exception <global-exceptions> <exception key="exception.nullexception.error" type=“java.lang.NullPointerException" path="jsp/ECError.jsp"/> </global-exceptions> When NullPointerException exception occurs, forward the request to ECError.jsp and build an error message using the key exception.nullexception.error (from resource bundle) UNIT -8 WT

159 Configuring Struts Configuration File
Action specific exception <action path="/outgoing" name="newOutgoingLog" type="org.worldbank.encorr.ecAction.OutgoingLogAction" scope="request" parameter="method"> <exception key="exception.outgoinglogcreate.action.error" type="org.worldbank.encorr.exception.OutgoingTicketCreationException" path="jsp/ECError.jsp"/> </action> UNIT -8 WT

160 Configuring Struts Configuration File
ForwardConfig Every action finishes by forwarding or redirecting to a view. Each view would be given a logical name and the framework will forward to the view by referring the logical name. 2 types 1.Global forward 2.Action specific forward Global forward <global-forwards> <forward name="success" path="/jsp/Success.jsp"></forward> </global-forwards> In action class ActionForward forward = null; forward = mapping.findForward(“success”); return forward; UNIT -8 WT

161 name – Name of the form bean associated with this Action
Attributes path – URI path name – Name of the form bean associated with this Action type – Name of the java class that extends Action/DispatchAction class scope – specifies the scope in which the form bean is placed (request or session) parameter – Name of the request parameter which holds the name of the method to be executed. forward – Name of the servlet/JSP which will be forwarded to instead of calling the Action class include – Name of the servlet/JSP which will be included with the response instead of calling the Action class (type, forward and include are mutually exclusive and exactly one should be specified validate – Boolean value indicating if validate() method should be called before calling Action class method UNIT -8 WT

162 Configuring Struts Configuration File
ActionConfig Describes a mapping between a specific request URI and a corresponding Action class. <action path="/outgoing" name="newOutgoingLog" type="org.worldbank.encorr.ecAction.OutgoingLogAction" scope="request" parameter="callMethod"> <exception ……………../> <forward ………………/> </action> UNIT -8 WT Copyright © 1997 Alex Chaffee

163 Assume in resource bundle,
When OutgoingLogAction exception occurs, forward the request to ECError.jsp and build an error message using the key exception.outgoinglogcreate.action.error (from resource bundle) Assume in resource bundle, exception.outgoinglogcreate.action.error = Internal Server Error in Create Outgoing Log So the error message would be Internal Server Error in Create Outgoing Log when OutgoingTicketCreationException is thrown. UNIT -8 WT

164 Configuring Struts Configuration File
ControllerConfig To declaratively assign the processor class (RequestProcessor) and modify its functionality. MessageResourcesConfig Specifies message resource bundle that contains localized messages for an application <message-resources parameter="org.worldbank.encorr.resources.ApplicationResources”/> UNIT -8 WT

165 Configuring Struts Configuration File
PlugInConfig To discover resources dynamically at startup. <plug-in className="org.apache.struts.validator.ValidatorPlugIn"> <set-property property="pathnames" value="/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml" /> </plug-in> UNIT -8 WT

166 Struts custom tags org.apache.struts.taglib TLDs struts-html.tld
Package org.apache.struts.taglib TLDs struts-html.tld struts-bean.tld struts-logic.tld struts-nested.tld struts-template.tld struts-tiles.tld The "struts-html" tag library contains JSP custom tags useful in creating dynamic HTML user interfaces, including input forms. In JSP, taglib uri="/WEB-INF/struts-html.tld" prefix="html" %> <html:javascript> UNIT -8 WT

167 Struts custom tags <html:javascript> Custom tag that generates JavaScript for client side validation based on the validation rules loaded by the ValidatorPlugIn <html:javascript formName="newOutgoingLog"/> <html:form> Custom tag that represents an input form, associated with a bean whose properties correspond to the various fields of the form. <html:form action="outgoing.do" method="post" onsubmit="return onClickSave(this);"> <html:hidden> Custom tag for input fields of type "hidden". <html:hidden property="ticketStatus" value="C"/> <html:select> Custom tag that represents an HTML select element, associated with a bean property specified by our attributes <html:options> Tag for creating multiple <select> options from a collection. UNIT -8 WT

168 Struts custom tags public class ListData { public String optLabel = null; public String optValue = null; public String getOptLabel() { return optLabel; } public void setOptLabel(String optLabel) { this.optLabel = optLabel; public String getOptValue() { return optValue; public void setOptValue(String optValue) { this.optValue = optValue; }} UNIT -8 WT

169 Struts custom tags ArrayList al = new ArrayList(); ListData ld = new ListData(); ld.setOptValue(“100”); ld.setOptLabel(“English”); al.add(ld); ld = new ListData(); ld.setOptValue(“101”); ld.setOptLabel(“Tamil”); UNIT -8 WT

170 ld.setOptLabel(“Hindi”); al.add(ld);
ld = new ListData(); ld.setOptValue(“102”); ld.setOptLabel(“Hindi”); al.add(ld); request.setAttribute("languageList",al); <html:select property="language"> <html:options collection="languageList" property=“optValue" labelProperty=“optLabel"/> </html:select> UNIT -8 WT

171 Struts custom tags <html:errors> Custom tag that renders error messages if an appropriate request attribute has been created. <html:errors/> <html:file> Custom tag for input fields of type "file". UNIT -8 WT

172 Validator framework For performing data validations on form data.
Purpose For performing data validations on form data. If any validation fails the application redisplays the HTML form so that the invalid data can be corrected Pluggable system of validation routines that can be applied to form beans. 2 XML configuration files 1.validator-rules.xml Declares the validation routines with a logical name for each routine. 2.validation.xml Defines which validation routine should be applied to which form bean property. It uses logical names of form beans from the struts-config.xml filealong with the logical names of validation routines from validator-rules.xml UNIT -8 WT

173 Validator framework Struts-config.xml <form-bean name="newOutgoingLog" type="org.apache.struts.action.DynaActionForm"> <form-property name="subject" type="java.lang.String"></form-property> </form-bean> <action path="/outgoing" name="newOutgoingLog" type="org.worldbank.encorr.ecAction.OutgoingLogAction" scope="request" parameter="method"> </action> UNIT -8 WT

174 Validator framework Validator-rules.xml <validator name="required" classname="org.apache.struts.validator.FieldChecks" method="validateRequired" methodParams="java.lang.Object, org.apache.commons.validator.ValidatorAction, org.apache.commons.validator.Field, org.apache.struts.action.ActionErrors, javax.servlet.http.HttpServletRequest" msg="errors.required"> <javascript><![CDATA[ function validateRequired(form) { ………………………………………………………. }]]> </javascript> </validator> UNIT -8 WT

175 Validator framework Validation.xml <form name="newOutgoingLog"> <field property="subject" depends="required"> <arg0 key=“Subject field" resource="false"/> </field> </form> In resource bundle, errors.required={0} cannot be left blank. UNIT -8 WT

176 File upload In jsp, <html:file name="IncomingLogBean" property="fileAttachment1"/> In struts-config.xml, <form-bean name="newOutgoingLog" type="org.apache.struts.action.DynaActionForm"> <form-property name="fileAttachment1" type="org.apache.struts.upload.FormFile" /> </form-bean> UNIT -8 WT

177 private FormFile fileAttachment1;
In OutgoingLogBean, private FormFile fileAttachment1; public FormFile getFileAttachment1() { return fileAttachment1; } public void setFileAttachment1(FormFile fileAttachment1) { this.fileAttachment1 = fileAttachment1; UNIT -8 WT

178 File upload In Action class, DynaActionForm dynaActionForm = (DynaActionForm)form; OutgoingLogBean outBean = new OutgoingLogBean(); BeanUtils.copyProperties(outBean,dynaActionForm); FormFile fileAttachment = outBean.getFileAttachment1(); String fileName = fileAttachment.getFileName() ; byte b[] = fileAttachment.getFileData(); UNIT -8 WT

179 Pros and Cons Pros: Open source Reduces the development time
No hard codings as struts values are represented in XML or properties file HTML custom tags (Minimize Java code in JSP) Form field validation Cons Bigger learning curve (understanding of servlets,JSPs is required) Less transparent (lot more goes behind the scenes) Rigid approach (suggests only MVC approach.Cant use other approaches) UNIT -8 WT


Download ppt "WEB TECHNOLOGIES – Unit VIII"

Similar presentations


Ads by Google