+ All Categories
Home > Documents > Adv Java

Adv Java

Date post: 24-Nov-2014
Category:
Upload: nskumarreddy
View: 151 times
Download: 0 times
Share this document with a friend
Popular Tags:
232
Contents 1. Introduction 2. Architecture of an Enterprise Application 3. JDBC 4. JDBC Architecture 5. Database Connectivity steps 6. Database Connectivity using jdbc-odbc 7. Program, Advantages and Disadvantages of Type 1 Driver(Bridge Driver) 8. Submitting SQL statements to the database 9. Program to insert record into the database 10. Type 4 Driver 11. Program and Advantages of Type 4 Driver 12. Driver Manager, Connection and Statement objects 13. Program on database connectivity using File (Generic) concept 14. Steps in retrieving data from database 15. ResultSet object 16. Differences between Statement and PreparedStatement object 17. Steps to implement PreparedStatement 18. Architecture of Web Application 19. Limitations of a Web Server 20. Types of internet programs 21. Servlets 22. Pre requisites for a servlet execution 23. Difference between Web Container and Web Server 24. Servlet Development 25. Servlet Life Cycle (Protocol Independent) 26. Web Application Development Steps
Transcript
Page 1: Adv Java

Contents

1. Introduction2. Architecture of an Enterprise Application3. JDBC4. JDBC Architecture5. Database Connectivity steps6. Database Connectivity using jdbc-odbc7. Program, Advantages and Disadvantages of Type 1

Driver(Bridge Driver)8. Submitting SQL statements to the database9. Program to insert record into the database10. Type 4 Driver11. Program and Advantages of Type 4 Driver12. Driver Manager, Connection and Statement objects13. Program on database connectivity using File (Generic) concept14. Steps in retrieving data from database15. ResultSet object16. Differences between Statement and PreparedStatement object17. Steps to implement PreparedStatement18. Architecture of Web Application19. Limitations of a Web Server20. Types of internet programs21. Servlets 22. Pre requisites for a servlet execution23. Difference between Web Container and Web Server24. Servlet Development25. Servlet Life Cycle (Protocol Independent)26. Web Application Development Steps27. Web Application Deployment Steps28. Different names and functions of a Servlet29. Program on Servlets30. Background Process after submitting the form31. Initialization Parameters32. Program on Initialization Parameters33. ResultSetMetaData interface34. Stored Procedure35. Program on Callable Statement36. Generic Servlet in depth

Page 2: Adv Java

37. ServletContext38. Program on ServletContext39. HttpServlet Basics40. Difference between GET and POST41. Life Cycle of HttpServlet42. Program on HttpServlet implementation43. Servlet Collaboration44. RequestDispatcher, Forward and Include45. Program on RequestDispatcher46. Filters47. Development and Deployment of Filters48. Program on Filters49. Filters in depth50. JSP Introduction51. Life Cycle of JSP52. JSP constituents53. implicit objects54. Programs on Jsp55. Java Beans56. Using Java Beans in Jsp57. Program on Java Beans58. Various scopes of Java Beans in Jsp59. Jsp architecture60. MVC architecture61. Program on MVC architecture62. Difference between include directive and include standard

action63. Program on Jsp include directive and include standard action64. Session Tracking 65. Cookies66. Program on cookies mechanism67. HttpSession68. URL rewriting69. Difference between Standard action and Custom action70. Custom tag development71. Steps to develop Custom tag72. Custom tag in depth73. Program on Custom tag74. Life Cycle and Flow Chart of Custom tag75. Types of ResultSet

Page 3: Adv Java

76. Batch Updates77. Type 2 and Type 3 Drivers78. Java Server pages Standard Template Library (JSTL)79. Programs on JSTL

Page 4: Adv Java

Topics:

JDBCServletsJSPBeansExpression LanguageJSTL

Introduction:

JAVA:-

It is Object Oriented Programming Language. It is a Platform (Runtime Infra-structure + libraries). It is a Technology.

Three flavors of JAVA:-

J2SE:- Standard Edition- core java J2EE:- Enterprise Edition- advanced java and J2EE J2ME:- Micro Edition

Usage:-

C is used in low-level programming like Systems programming, Compiler designing, etc.

Java is used in Enterprise Application Development

Enterprise Application:-

Any Computer Application that helps in automating day to day operations of a business organization (enterprise) is known as Enterprise Application.Ex: - Banking, Insurance, Super Market, Hospital Management, Hotel Management.

Page 5: Adv Java

Architecture of an Enterprise Application:

Tier: - A logical partition of the components involved in a system (application).

Every Enterprise Application has 4 tiers.

Client tier.(Browser) Presentation tier.(Web-Server) Business tier.((Rules) Data tier.(Data)

Request

Response

Client tier Presentation tier Business tierJDBC

JDBC

Data tierClient tier: - In an Enterprise Application, the client tier is mostly the browser.End-user of the application interacts with the entire Enterprise Application using this tier.Technology used: - HTML, Java Script.

HTMLJava Script

ServletsJSPJava Beans

EJB

Page 6: Adv Java

Presentation tier: - This acts as an interface between client tier and the business tier. Major responsibilities are as follows:-

Receiving the requests from client tier. Authentication and Authorization.

Authentication: - Validation of user.Authorization: - Permissions granted to the user.

Maintaining the sessions. For core business logic execution sake, sending the request to

the business tier. Preparing the output and driving it to the client.

Business tier: - This tier of the Enterprise application holds the core business rules implementation. This tier receives request from the Presentation tier for Business Logic Execution.Major technology used is EJB.

Data tier: - This is the Enterprise’s information storage.Mostly it is the Database server.

Page 7: Adv Java

JDBC (Java Database Connectivity)

JDBC is a Technology provided by Sun Microsystems. JDBC is not a Software Product. JDBC is a Specification. JDBC defines a *Vendor independent way of communication between

any java program and the database.Vendors: - MS-SQL, ORACLE.*Vendor independent: - Java program will not change with the change in database.

Java programs (be a stand-alone client or a servlet / jsp or an EJB) are capable of making only method calls, whereas industry standard database server can understand only SQL.

JDBC Architecture

There are 5 elements in JDBC architecture:

1) Java Client 2) JDBC API3) Driver4) Driver Manager/ Data Source5) Database Server

Page 8: Adv Java

JDBC Architecture

I.Java Client Application : - It is any database aware java program.This can be any of the following:-

a. Stand-alone GUI clientb. AWT/Swings Applicationc. A Servletd. An EJBe. A Java Beanf. A JSP

Client Java Program

JDBC API

DriverManager/Data Source

Driver

Database Server

Page 9: Adv Java

Responsibilities of Client Java Application:- Requesting the database server for connectivity. To make

this request, application uses JDBC API. Server-Socket Programming is involved internally.Without Socket, no client can connect to the server.

Preparing the appropriate SQL statements and submitting them to the database server by using JDBC API.

Define the Storage Areas.Storage Areas are the places to store the data like bringing data from database and store them in RAM.

Process/fetch the data that is stored in the Storage Areas. Error Handling. Controlling Transactions whenever necessary. Transactions

should be ATOMIC (Fully done or not done at all). Closing the connection

II. JDBC API : - It is a set of Interfaces and Classes (few). JDBC API is a collection of library methods that support SQL statements.To every java program JDBC API support is available through two packages.

1. java.sql2. javax.sql

Java libraries are divided into two 1. java- core API2. javax- Extension API

III. Driver : - It is software. It performs the following things: Establishing connection with the Database Server Receiving JDBC method calls from the Client Application Performing translations Submitting the JDBC requests to the database server Providing the Client with the requested data If required, initiating the transformation

IV. DriverManager : - It is an element in the JDBC Architecture whose major role is to provide the connection to the Client Java. Its role ends as soon as connection is established.

V. Database Server : - In the industry strength Enterprise Application, this is mostly RDBMS.Examples:-

Page 10: Adv Java

Oracle Sybase SQL Server Informix DB/2

Informix and DB/2 are IBM databases.

Page 11: Adv Java

Database Connectivity Steps (Approaches)

DriverManager Connectivity Approaches DataSource

Hybrid Approach (jdbc-odbc)Connectivity Approaches

Pure jdbc approach

DataSource is used in real time rather than DriverManager.

Database connectivity using jdbc-odbc:

Step 1: Loading the driver into java environmentStep 2: Preparing the database connection URLStep 3: Requesting for the connectionStep 4: Once done with the database operations closing the connection

Class.forName (“Driver Class”); .

“jdbc: odbc: DSNName”;

DriverManager.getConnection ();

Connection.close ();

Loading the Driver

Preparing the connection URL

Requesting for the connection

After database operations, close the connection

Page 12: Adv Java

Loading the Driver:-

Driver is a java class. It establishes the connection with the database. Therefore, we have to bring this class into java environment. Driver class is not part of JDBC API. In order to load this class into java environment we make use of following method.

Class.forName (“Fully qualified driver class”);

Once this method call is made, 3 things happen

1) Driver class is dynamically loaded into memory.2) Driver class is instantiated.3) Driver instance is registered with the DriverManager.

In case of jdbc-odbc approach of connectivity, the Driver class is as follows:-

“sun.jdbc.odbc.JdbcOdbcDriver”

This Driver is famously known as Bridge Driver. It is Type 1 Driver as far as SUN is concerned.

Note: - Class.forName () throws ClassNotFoundException.

Preparing the Connection URL:-

The general form of URL in case of hybrid approach is

Protocol: subprotocol: dsnname

Data Source Name (DSN): It is a named configuration that comprises of vendor dependent driver, OS, database and few optional settings.This is done external to the java program.DSN does not exist in pure JDBC Approach.

Requesting for the Connection:-

Page 13: Adv Java

Client Application requests the java.sql.DriverManager or javax.sql.DataSource for the sake of connection with the database

The following static method of the DriverManager class is called by the Client Application for the sake of connection.

DriverManager.getConnection (String URL, String user, String pwd);

Closing the Connection:-

Once we are done with database operations we have to close this connection by calling close () on Connection.

Page 14: Adv Java

/* Program to connect to the Oracle database server using Type 1 driver (Bridge Driver) */

import java.sql.*;

class HybridConnectivity{public static void main (String args []) throws Exception{//Step 1:- Loading the Driver

Class.forName (“sun.jdbc.odbc.JdbcOdbcDriver”);System.out.println (“Driver is loaded, instantiated and registered with the DriverManager”);

//Step 2:- Preparing the Connection Url

String URL=”jdbc:odbc:student”;

//Step 3:- Requesting for the Connection.Connection con=DriverManager.getConnection (URL, “Scott”, “tiger”);System.out.println (“Connection is established”);

//Step 4:- Closing the Connection

Con.close ();System.out.println (“Connection closed”);}}

Page 15: Adv Java

`

Advantages of Bridge Driver:-

Using this single driver we can get connected to any database.As it is internally uses ODBC technology which is already a proved technology, connectivity sake SUN need not have experimented.

Disadvantages of Bridge Driver:-

Because of 2 layers and translations, performance is compromised and hence barred in the industry.It cannot be used in the internet and intranet based applications. In every Client machine, database vendor library should be present. It leads to maintenance problems.

Role of interfaces in J2EE Applications

An interface acts as a contract between service provider and service user.

An interface acts as a data type. That means its reference can be created even though its object cannot be created.

An interface can act as a parent to a class.

-- -- -- -- -- -- -- -- -- -- --

Bridge Driver

Vendor dependent ODBC Driver

ODBCfunction calls

JDBC method calls

Database Server callsDatabase ServerClient Java

Application

SQLDatabase Engine

Page 16: Adv Java

In java, super class (interface) reference can reference to subclass object.

An interface is meant for standardization. An interface provides the names of the services (only abstract

methods) whereas a class provides the service by implementing the interface.

In advanced java programming, we encounter methods returning interface objects or methods taking interface objects as arguments. In fact, they are not objects, just they are references.

Note (interview questions):-

Why not directly use ODBC?It is implemented in C, therefore security and portability is at risk and also C is procedure oriented and Java is Object Oriented.

Why Connection is interface not a class?Giving freedom to vendor to implement their own logic. Uniformity is given to programmer (Standardization).

Page 17: Adv Java

Submitting SQL statements to the database

1. Request for the connection:

Class.forName(“Driver class”);DriverManager.getConnection (“jdbc: odbc: DSNName”);

2. Prepare the SQL Statement:

In a Java Program, SQL Statement is a String. As a programmer we should know the SQL syntax for building the DML/DDL/DRL/DCL Statements.

Note: Almost all we never submit DDL Statements from the Java Program to the Database Server.

3. Building the Statement Object:

Requesting for the Connection

Prepare the SQL Statement

Build the Statement object

Submit the SQL statement with the help of Statement object

Close the Statement object

Close the Connection

Page 18: Adv Java

According to JDBC API, we have 3 kinds of Statement Objects. Java.sql.Statement Java.sql.PreparedStatement Java.sql.CallableStatement

Interface

Sub-Interface

Sub-Interface

In order to create Statement Object, we make use of Connection Object.

4. Submitting the SQL Statement:

java.sql.Statement has 2 important methods to submit SQL Statements to the Database.

public int executeUpdate (String dmlsql) throws SQLException:

This method takes DML Statements as arguments i.e., by using this method we can submit INSERT UPDATE and DELETE SQL Statements to the Database. This method returns an integer that represents the number of rows affected in the database table as a result of the database operations.

Public ResultSet executeQuery (String SelectStatement) throws SQLException:

This method takes SELECT SQL Statements as argument and returns Database records in the form of a ResultSet Object.

5. Closing the Statement Object:

Statement

PreparedStatement

CallableStatement

Page 19: Adv Java

st.close ();

In the above statement st is a reference that refers to an Object that implements Statement interface.

6. Closing the Connection:

con.close ();

Write a program to INSERT a record into the database table

import java.sql.*;

public class InsertOperation{public static void main (string args []) throws Exception{Class.forName (“sun.jdbc.odbc.JdbcOdbcDriver”);String Url= “jdbc: odbc: student”;Connection con=DriverManager.getConnection (Url);System.out.println (“Connection is established”);String Sql= “INSERT INTO STUDENT VALUES (1001, ‘adil’, 98);Statement st=con.createStatement ();int r=st.executeupdate (sql);System.out.println(r+“row inserted”);st.close ();con.close ();}}

Note (interview questions):-

Why Statement is an Interface but not a Class?

When Database is changing, we need to change the Class several times.

Why Statement is always produced from Connection Object?

Page 20: Adv Java

Dedicated socket Connection is established with the Database Server and each Statement is given an Address Space in the Database through which all the communication takes place between that Statement Object and the Database Server. For recognizing each client uniquely.

Page 21: Adv Java

JDBC Drivers:

Establishing the connection using pure JDBC approach:

Steps

Pure Driver

JDBC method calls

Database Server callsDatabase ServerClient Java

Application

SQL

-- -- -- -- -- -- -- -- -- -- --

Db engine

Loading the Driver

Preparing the Connection URL

Requesting for the Connection

Close the Connection after the Operations

Page 22: Adv Java

Type 1 Driver is called Bridge Driver

When we use Type 1 Driver (Bridge Driver) to get connected, performance gets down on account of two layers (JDBC and ODBC). Therefore this type of driver cannot be used in the Real time Applications.

To overcome this problem, we have pure JDBC Drivers that eliminate ODBC completely.

When we want to connect to the databases we use ORACLE thin driver. (Type 4 driver). It is pure JDBC driver.

JDBC driver are manufactured by the database vendors but not sun.

JDBC is a specification for the driver manufacturers.

If the driver is manufactured according to JDBC specifications, then only it is called as JDBC Complaint Driver.

JDBC complaint driver implement JDBC API, whatever method calls we make in a program are received by the Driver.

JDBC is a Specification for Driver manufacturers.

JDBC is an API for programmers.

Advantages of pure JDBC driver:

Performance is more. Can by used in Internet and Intranet Application.

// Program on getting connected to Oracle Database Server using thin Driver (Type 4)

import java.sql.*;

class JdbcConnectivity{

Page 23: Adv Java

public static void main (String [] args) throws Exception{

// Loading Driver

Class.forName (“oracle.jdbc.driver.OracleDriver”);System.out.println (“Driver is created, instantiated and registered with DriverManager”);

// Preparing the url

String url = jdbc: oracle: thin:@localhost:1521:server;

// Requesting for the Connection

Connection con = DriverManager.getConnection (url, “scott”,” tiger”); System.out.println (“Connected”);Statement st=con.createStatement ();st.executeUpdate (“CREATE TABLE STUDENT (rollno number (4), name varchar2 (12), marks number (3))”);System.out.println (“Table Created”);// Closing the Connection

st.close ();con.close ();}}

executeUpdate () will return 0 in case of Create Table.

Note:

oracle.jdbc.driver.OracleDriver class is not a part of JDBC libraries. Therefore, existing class path is not sufficient.

We should specify to the JVM where from this class has to be loaded. Otherwise ClassNotFoundException rises.

Page 24: Adv Java

Classpath:-

D:\oracle\ora8i\jdbc\lib\classes111.zip (or)D:\oracle\ora8i\jdbc\lib\classes12.zip

JVM’s Class Loader will take care of the classpath.

%classpath% - Used for appending to already existing classpath.

Search for the following file in our system to prepare for the connection URL for oracle thin driver:D:\oracle\ora8i\network\admin\tsnnames.ora

Syntax for the URL:Protocol: sub-protocol: driver type: machine ip: port no: Server-id

What is the capability of Class.forName ()?

This method can load any java class into memory dynamically. It cannot create the object of that class and cannot register the object to anybody.

In JDBC program, when we say Class.forName (“Driver”), only Driver class is loaded into memory. It is the responsibility of the Driver class Developer to ensure that Driver class object is created and registered with DriverManager automatically whenever the class is loaded into the memory. Static block should be used for this.

//Sample of a Driver Program

class OracleDriver implements Driver{static{Driver d= new OracleDriver ();DriverManager.registerDriver (d);}}

Page 25: Adv Java

What happens in the background when getConnection () is called on the DriverManager?

getConnection () returns a reference of type java.sql.Connection. That reference refers to an object that is the abstraction of networking connections between the client and database server. The kind and type of object will be Driver independent.

What is a Statement in the context of JDBC Programming?

Java.sql.Statement is an interface. Statement is a jdbc object created by the Driver in a vendor dependent manner.

Statement st=con.createStatement ();

Responsibility of Statement object is to submit and return the SQL statements and results respectively within the client connection space in the database server.

Why to close Connection object?

To release the network resources those are consumed by the client to have the Socket connection with Database Server.

Why to close Statement object?

To release jdbc resources.

//Program to perform delete and update operations from the java program:

Import java.sql.*;Class UpdateOperation{Public static void main(String args[]) throws Exception{Class.forName(“oracle.jdbc.driver.OracleDriver”);Connection con=DriverManager.getConnection(“jdbc:oracle:thin:@localhost:1521:Server”, “scott”, “tiger”);Statement st=con.createStatement();

Page 26: Adv Java

int rows;

rows=st.executeUpdate(“Update Student set marks=marks+10 where marks>49”);System.out.println(rows+”rows expected”);St.close();Con.close();

}}

//write a java program to get connected to oracle database.Don’t do hard coding in the program regarding driver, connection url, authentication information:

In industry strength applications javax.sql.DataSource replaces DriverManager. For DataSource implementations to get connected to the Database, Driver details, and Database details are not required at Application level. To implement DataSource, we need JNDI support. In DriverManager approach also we can avoid hard coding by using two things:

File ConceptJava.util.properties object

Page 27: Adv Java

import java.sql.*;import java.util.*;import java.io.*;

class GenericConnectivity{public static void main (String [] args) throws Exception{Properties p=new Properties ();FileInputStream fis=new FileInputStream (“dbprops.txt”);p.load (fis);String driver=p.getProperty (“d”);String url= p.getProperty (“cu);String user= p.getProperty (“u”);String pwd= p.getProperty (“p”);Class.forName (driver);Connection con=DriverManager.getConnection (url, user, pwd);System.out.println (“Connected”);con.close ();

}}

Dbprops.txt file:

D=oracle.jdbc.driver.OracleDriverCu=jdbc:oracle:thin:@localhost:1521:ServerU=”Scott”P=”tiger”

Jar –cvf classes12.jar classes12.zipJar –cvf classes12.jar

Page 28: Adv Java

Retrieving data from the Database:

Get Connection

Prepare the SELECT Statement

Build the Statement Object

Submit the SQL Statement

Fetch the row and column values

More Rows

Close Resultset

Close Statement

Close Connection

YES NO

Page 29: Adv Java

Java.sql.Statement interface has one important method that is used to submit SELECT statements.

public ResultSet executeQuery (String SQL) throws SQLException

This method takes a table of records in an object oriented manner i.e. ResultSet object.

What is ResultSet?

It is an interface.An object of some class that implements ResultSet interface is created by the Driver and its reference is returned to java program.

ResultSet rs=st.executeQuery (“SELECT * FROM STUDENT”);

ResultSet object is an encapsulation of table of records sent by the Database Server.

ResultSet when opened, a logical pointer called cursor is placed at the no record place of ResultSet:

RS

Records

No Record Place

Page 30: Adv Java

It is the responsibility of the Programmer to move the cursor to the record existing location of the ResultSet.

Java.sql.ResultSet interface has 2 kinds of methods

Cursor Moving methodsColumn values getting methods

Next () method is one important method which does two things

It moves the cursor by one record in forward direction Once cursor goes there, column values are there (or) record is empty

is indicated by this method through Boolean value.

To retrieve column values, we have getXXX () methods in the ResultSet interface. These methods are overloaded; we can supply either column name (or) column number to these methods to get data.

//write a program to retrieve data from Database:

import java.sql.*;class RetrieveData{public static void main (String [] args) throws Exception{Class.forName (“oracle.jdbc.driver.OracleDriver”);Connection con=DriverManager.getConnection (“jdbc:oracle:thin:@localhost:1521:Serverid”, “Scott”, “tiger”);System.out.println (“Connected”);Statement st=con.createStetment ();ResultSet rs=st.executeQuery (“Select * from student where rollno=844”);If (rs.next ()){int r=rs.getInt (1);String n=rs.getString (2);int m=rs.getInt (3);System.out.println(r+ ““+n + ““+m);elseSystem.out.println (“Not found”);rs.close ();

Page 31: Adv Java

st.close ();con.close ();}}}

Page 32: Adv Java

Retrieving all the records from the student table:

ResultSet rs=st.executeQuery (“select * from student”);While (rs.next ()){System.out.println (rs.getInt (1) + “ “+rs.getString (2) + “ “+rs.getInt (3));}

Note: for the getXXX () methods of the ResultSet, we have to supply the column numbers based on the records of ResultSet object but not based on database table columns.

What happens in the background when SQL Statement is submitted to the Database engine?

a) Database engine parses the submitted SQL Statement looking for syntactical errors.

b) Query Plan Generationc) SQL Statement is executed

What is ability of Statement object? What are its limitations/drawbacks?Statement object is used to submit SQL Statements to the Database. Whenever the same SQL Statement is required to submit multiple times with different set of values, Statement object reduces the performance.To overcome this problem, we go for java.sql.PreparedStatement

What is the difference between Statement object and PreparedStatement object?

PreparedStatement differs from Statement object in two ways:

It has pre-compiled or already prepared SQL Statements in it whereas Statement object is empty.PreparedStatement has at least one ‘in’ parameters.

Note: ‘In’ parameters are those parameters whose values are not supplied at query compilation time but supplied at execution time. At the time of compilation instead of values, place holders (?) are kept.

Page 33: Adv Java

Steps to implement PreparedStatement:

Request for the Connection

Build the PreparedStatement Object

Set the ‘in’ parameters

Submit the SQL Statement

MoreStatement

s

Close the PreparedStatement

Close the Connection

YES NO

Page 34: Adv Java

1. Request for the Connection:

Class.forName ()DriverManager.getConnection ()

2. Building the PreparedStatement:

PreparedStatement ps= con.prepareStatement (“INSERT INTO STUDENTS VALUES (?,?,? )”);

3. Set the ‘in’ parameters:

Supplying values to the Placeholders of the PreparedStatement object is known as binding of parameters or setting ‘in’ parameters.

In order to set the ‘in’ parameters, we call setXXX () methods in the PreparedStatement.

4. Submitting the SQL Statements:

We call executeXXX () methods on the PreparedStatement to submit the SQL Statement.

5. Close the PreparedStatement:

ps.close ();

6. Close the Connection:

con.close ();

Page 35: Adv Java

Web Application Development:

Technologies:

Servlets, JSP, JAVA BEANS, Expression Language, JSTL, Struts.

Main goal of Web Application Development is to web enable the Business Applications i.e., making Enterprise Application Online.

Once we can develop a Web Application, we are Java Professionals and our main role will be Web-Component Developers.

Web-Application:

Any Business Application that can be accessed from web interactively is known as Web Application.

Architecture of Web:

Web Client:

It is a Browser Software. It is also known as Http Client. The main functionality of web client is to establish Socket Connection with the Web Server & making request for the sake of web resources (mostly web pages).The communication protocol used by the Client is Http.

<Html>-------

<Html>

Web Client Web Server Web Page

Http request

Http response

Related HTML Program fetching from Hard Disk

& sending to Client Program

Page 36: Adv Java

Web Server:

It is Software.The main functionality of the Server:

Accepting the incoming Web Client Connections. Processing the http request made by the browser (http client) Give the http response.

Note:

Browser is a Web Page Requesting Program and Web Server is web page fetching.

Web Page:

It is an html document.

We have two kinds of web pages:

1. Pre-created html files stored in the computer hard disk. These are developed by web designers using tools- flash, dream weaver, etc.These are the passive/static resources an end user want.These are known as static resources because their contents never get changed upon end users interaction.

2. Dynamic Web Pages are not pre-existing html documents i.e., these web pages are programs and on the fly created whenever the request comes from the Client. A Servlet or a JSP creates the Dynamic Web Content Programmatically. They are known as Dynamic because their content changes with end user interaction.

Page 37: Adv Java

Limitations of a Web Server:

A web server provides http connection to the web clients. Its basic limitations are that it can fetch web pages to the clients. If they are present in the system of the server machine i.e., pre existing web pages. It cannot handle complex Client requests that involves end users input with this limitation following scenarios can’t be handled by the Web Server.

User Authentication Online Bill Payments Online Reservations Online Banking

Types of Internet Programs:

Client side Program:

Validating the forms through Java Script / jscript is known as Client.

Server side Program:

Web Server should be able to handle any kind of http request. Whenever the request involves end user’s input on its own it cannot process that request.

To overcome this problem it takes the help of external programs. These external programs are nothing but server side Programs.

Server side technologies:

CGI-Perl Asp Servlets JSP etc.

Drawback of CGI programs:

Number of processes are more Process termination after response Running external to web server process

Page 38: Adv Java

Servlets

Servlet is a Web Technology. Servlet is one of the Components of Java Enterprise Edition. A Servlet is a Server side Program which is a replacement for the CGI

Programs. Servlet API is one of the JAVA API used to web-enable the Business

Application. According to specification (J2EE), a Servlet is known as Web

Component. Servlets Developer is known as Web Component Developer.

A Servlet is a Server Side Program that extends the functionality of a Web-Server.

Servlet produces Dynamic Web Content. Servlet is an active resource in a Web Application. A Web Application has 2 kinds of Web resources:

Static/Passive (Html, Images) Active/Dynamic (Servlet/JSPs)

Q) If I want to write a Servlet and execute it. What are required in my System (Computer)?

A) We need

Servlet API Web Container that provides execution environment for Servlets

Note: A Web Container is Server Software.Ex: Tomcat 5.0.x

Classpath: After loading the Tomcat Server, set the classpath to the following jar file

C:\Apache\tomcat\common\lib\servlet-api.jar

Page 39: Adv Java

Q) What is a Web Container? What is the difference between Web Container and Web Server?

A) It is a Server Software, i.e., Web Server along with Servlet engine and JSP engine.

Web Server cannot alone execute Servlets and JSP.

SERVLET

Http service/Web server

Servlet engine

JSP engineWeb Client/

Browser

Web Container

Database Server

Request

Response

Page 40: Adv Java

Servlet Development

A Servlet is a java class that is written (defined) according to Servlets Specification by using SERVLET API.

Servlet API is made available to java programs through 2 packages:

javax.servlet.* javax.servlet.http

We have 2 kinds of servlets in java:

Protocol independent Protocol dependent

A Servlet is said to be protocol independent. If it is capable of helping (extending the functionality) of any kind of servers irrespective of protocol. i.e., ftp server. Http server or SMTP server.

javax.servlet.GenericServlet class is an example of Protocol Independent servlet.

A Servlet is Protocol Dependent if it is extending the functionality of only one kind of server. We gave sun support only to Http Server.

javax.servlet.http.HttpServlet class is an example of Protocol Dependent servlet.

Page 41: Adv Java

Servlet Life cycle (Protocol Independent):

A Servlet is a Container managed Web Component. That is, Servlet instance creation, initialization, destruction, etc. are done by the Servlet Container (Engine).

Container can manage a Servlet if and only if the Servlet is defined according to Servlet Specification.

According to Servlet Specification, a Servlet is any java class that directly or indirectly implements javax.servlet.Servlet interface.

Indirectly means that calling this interface in our servlet which is already implemented or extended in other classes or interfaces. Ex: GenericServlet implements Servlet interface.

This interface provides 3 life-cycle methods.

Init ()-at the time of initialization Service ()- at the time of processing the request Destroy () - container calls this method at the time of Servlet

destruction.

If we directly implements the Servlet interface, at that time it is mandatory to implement all the above 3 methods.

Therefore to avoid this we need to use or implement indirectly or sub class i.e., Generic classes.

Servlet interface specifies the Component contract between Servlet Engine and our own Servlet.

Servlet

GenericServlet

Our Servlet

Page 42: Adv Java

In Direct we have problem

Override all methodsDefault implementation provided by GenericServlet is lost.

We cannot instantiate GenericServlet as it is abstract class so we should instantiate our own servlet class.

When we write a Protocol Independent servlet our class extends GenericServlet

javax.servlet.GenericServlet class implements Servlet Interface. This class overrides all the abstract methods of Servlet Interface except service () method.

Service () method is declared as abstract in GenericServlet as the programmer should compulsorily override that method.

Therefore GenericServlet class has become abstract class. It contains service () as an abstract method. This enforces our own servlet class to override service () method.

A Servlet life cycle comprises of 4 phases:

1. Instantiation2. Initialization3. Service4. Destruction

Page 43: Adv Java

Our Servlet life cycle

Container loads Servlet class into memory

Servlet engine creates the instance of the Servlet class

Container creates instance of ServletConfig

Container calls init () method

Container creates two objects ServletRequest and ServletResponse

Container calls Service () method

More Requests?

Is Servlet Undeploye

d?

Container calls destroy () method

Instantiation phase

Initialization Phase

ServicePhase

DestructionPhase

YES

YES

NOServlet isRunning

NO

Servlet isRunning

Page 44: Adv Java

1. Instantiation Phase:

According to the instruction given to the container it loads the Servlet class into the memory dynamically.

Class c=Class.forName (“our servlet”);Class.forname (“our servlet”) is used to load into memory dynamically.

Servlet engine creates the servlet instance.

c.newInstance ()

Instance of ordinary class are called as objects but servlet, ejb, Java Bean’s instances are not called as objects, but they are called Components.

Sample Program to create instance of a Class:

Class A{A (){System.out.println (“Instance of class A created”);}}Public class B{Public static void main (String args []) throws Exception {Class c=Class.forName (“A”);c.newInstance ();}}

Page 45: Adv Java

2. Initialization Phase:

When Container creates the instance of the Servlet, that Servlet instance does not possess any Servletness. It cannot process any Client Request because it does not have any idea about the Server environment. It is the responsibility of the Container to provide such information to the Servlet and fetch Servletness to the instance.

Servlet engine creates the proprietary object that implements ServletConfig interface. This object holds initialization and context information.

Servlet engines calls the init () method on Servlet instance by supplying ServletConfig object as argument. Once init () method completes its execution, Servlet instance gets Servletness and it ready to serve any Client Request.

3. Servicing Phase:

Servlet engine receives the request from http service that includes Client info and the data sent by the Client. Based on this information, Servlet engine creates two Proprietary objects that implement ServletRequest and ServletResponse interfaces respectively.Container calls service method as the Servlet instance by supplying these two objects as arguments.

As a Servlet developer, we write Application logic in the service method. This method is executed every time when the request comes to the Servlet.

4. Destruction Phase:

When the Web Application is undeployed by the Administrator, Servlet instance is Garbage Collected. Before Servlet instance is Garbage Collected, Container calls destroy () method on the Servlet instance. In this method, Servlet Programmers write cleanup code.

Page 46: Adv Java

Skeleton structure of a Servlet:

import javax.servlet.*;import java.io.*;

Public class OurServlet extends GenericServlet{Public void init (ServletConfig config) throws ServletException{//code to retrieve initialization info//code to provide resources to the Servlet}Public void service (ServletRequest request, ServletResponse response) throws IOException, ServletException{//Application logic varies from Web Application to Web Application}Public void destroy (){//clean up code}}//OurServlet

Page 47: Adv Java

Web Application Development Steps:

Every Web Application comprises of

Html document Image files Servlets Jsps Other helper classes Xml document(s)

Step 1:

Creation of a hierarchy of directories according to the specification

Root Directory (any name)

WEB-INF

classes

lib

*.html

JSPs

Image filesServlet class files

Bean class files

Helper class files

web.xml

*.jar

Page 48: Adv Java

The root directory acts as Web Application’s root context. It has 2 parts.

I. Public Area: Directly under the root directory all the web resources that can be accessed from the client are placed.

a. Htmlsb. JSPsc. Image files

II. Private Area: Directly under the root directory we should create a directory by the name WEB-INF whose contents are exclusively meant for the container access. These files cannot be accessed from the client.

Step 2:

Defining the Web Component

We need to write a servlet class or a JSP.

This Web Component is primarily responsible to make the Web Application

When we want to generate Dynamic web Component using a Servlet, we have to do the following:

a) write the servlet source code(.java)b) Compile the source code and copy the .class file of the servlet in the

classes’ directory.

Step 3:

Deployment Descriptor (web.xml)

According to specifications, for every Web Application, one (only one) Deployment Descriptor is mandatory. That file name and extension together should be web.xml only.

The need of web.xml in a Web Application is basically to declaratively instruct the container what to do?

Inside the web.xml we do the following things:

1) Servlet registration with the Web Application

Page 49: Adv Java

2) Authentication Configuration3) Session timeout details4) Listeners Configuration5) Initialization parameters supplying6) Filters Configuration7) Servlets pre-initialization8) Welcome files Configuration etc.

Web Application Deployment Steps:

Step 1:

Create the war file. War file is a special kind of jar file. According to specification, every Web Application has to be packaged into a war file.

Currentworkingdir > jar –cvf greeting.war .

Step 2:

Start the Tomcat Server

Step 3:

Open the browser and type the following:

http://localhost:8080/manager/html

Upon that request, we get a web page (Tomcat Web Application Manager)

Step 4:

In the Tomcat Web Application Manager tool, we have to select the war file to deploy. Specify the location of the war file and click on the deploy button.

Page 50: Adv Java

Q) What are the functions of a servlet in general?

A) A servlet in general performs 3 things:

1. Evaluating the ServletRequest object for incoming form data

String value=request.getParameter (“name”);

2. Executing the Application logic

3. Generate the dynamic content and drive the output to the client

Q) How many names does a servlet have in a Web Application?

A) A servlet has three names in a web application

1. Registration/ alias/internal secret name2. Servlet class name3. Public url name

Q) Develop and deploy a Web Application in which when requested by the Client, Server should give one form prompting the end user to enter name. Upon entering name when end user click on the submit button, Server should send the greeting message accordingly?

Step 1:

Creating the hierarchy of directories

GreetingAppGreet.htmlWEB-INF

classes nit servlets GreetingServlet.class

web.xml

Page 51: Adv Java

Step 2:

Defining the web resources

Greet.html

<html><body bgcolor=cyan><form action=”. /gotit”>Name :< input type=”text” name=”t1”><br><input type=”submit”></form></body></html>

GreetingServlet.java

Package nit.servlets;

Import javax.servlet.*;

Public class GreetingServlet extends GenericServlet{Public void service(ServletRequest request,ServletResponse response) throws ServletException,IOException{String name=request.getParameter(“t1”);//evaluating the request object form dataString message=”WELCOME”+name+”TO OUR WEBSITE”;//application logicResponse.setContentType(“text/html”);PrintWriter out=response.getWriter();Out.println(“<html>”);Out.println(“<body bgcolor=wheat>”);Out.println(“<h2>”+message+”</h2>”);Out.println(“</body>”);Out.println(“</html>”);Out.close();

}//service()

Page 52: Adv Java

}//GreetingServlet

Compilation

>javac –d . GreetingServlet.class

Step 3:

Writing the Deployment Descriptor

Web.xml

<web-app><servlet><servlet-name>Greet</servlet-name><servlet-class>nit.servlets.GreetingServlet</servlet-class></servlet><servlet-mapping><servlet-name>Greet</servlet-name><url-pattern>/gotit</url-pattern></servlet-mapping></web-app>

Web Application Deployment

Root Directory

D:\GreetingApp>jar –cvf greetingapp.war .

Step 1: creation of war fileStep 2: start the serverStep 3: open the browserhttp://localhost:8080/manager/htmlStep 4: deploy the war file

Note: As an end user we should get the html formhttp://localhost:8080/greetingapp/greet.html

Page 53: Adv Java

Q) What happens in the background when the form is submitted to Container (Server)?

A) As the part of html form, the action attribute value specifies the address of the web component, to which the form request has to be submitted. In the above example

<form action= “. /gotit” >

The value of the action attribute has got 2 parts:

Dot indicates the current Web Application from which this web-page is retrieved i.e.

http://localhost:8080/greetingapp

The other part indicates the public name of the servlet. This name is specified as <url-pattern>/gotit</url-pattern> in the web.xml. Therefore we used that name in the action attribute.

Upon receiving the request, Http service (Web-Server) transfers (delegates) the control to the servlet engine because the request involves end user’s input and the address also is specified in the request. Servlet engine receives the request and picks up the Web Application name from the request. Once Web Application is matched with the existing installed Application, servlet engine reads the web.xml to resolve the request. In the web.xml as we have already specified the public URL name, the corresponding servlet is assigned the duty of processing the client request.

Url-pattern gives public name to the servlet. This is mapped to alias name.

NOTE: War file is needed only by Tomcat server.

Q) How does the response generated by the servlet reach the Client?

A) Never ever, servlet directly sends the output to the Browser. The dynamic content generated in the servlet i.e., given to the web server via servlet engine. Web-server sends that dynamic content to the Browser.

Page 54: Adv Java

Q) What is the significance of ServletRequest and ServletResponse objects in the Client request processing by the Servlet?

A) Servlet captures the incoming client data and Http header information through request object.

ServletResponse object provides methods to customize the output to be sent to the client.

For example the type of content Multipurpose Internet Mail Extension (MIME) is specified by using the response object.

response.setContentType (“file type/extension”);

Servlet is writing response header between the server and the request sending browser. Stream object is created by using the response object only.

PrintWriter pw=response.getWriter ();

Page 55: Adv Java

Passing initialization parameters to Servlet

Initialization parameters:Name, value pair of strings supplied to the servlet from the descriptor (web.xml) is called as initialization parameters.

Q) How to apply init parameters to the servlet?A) In the web.xml, we make use of the following parameters:

<init-param><param-name>name</param-name><param-value>value</param-value></init-param>

Q) How does a servlet receives initialization parameters supplied from web.xml?A) Servlet engine reads the web.xml as soon as the Web Application is installed. For a particular servlet, how many init programs are there, it calculates and creates those many string objects. During servlet initialization phase of the servlet it supplies them to the servlet via ServletConfig object.0We have two important methods in the javax.servlet.ServletConfig interface to retrieve the init params

String getInitParameter (String name) - this method takes the init param name and returns the corresponding value.

Enumeration getInitParameters () - this method returns all names of the init parameters as an enumeration of String objects.

Q) What are the uses of the init parameters?

They avoid hard coding and there by recompilation and redeployment of servlets can be prevented whenever ceratin values are required to be changed.Basic idea of init parameters is that during the initialization phase itself, we can provide some information to the servlet so that it can use that info during its servicing phase.

<servlet>

Page 56: Adv Java

<servlet-name></servlet-name><servlet-class></servlet-class><init-param><param-name>name</param-name><param-value>value</param-value></init-param></servlet>

Q) Develop and deploy a web application in which servlet should be able to retrieve initialization parameters?

A) InitparamAppemp.htmlWEB-INF classes DatabaseServlet.class lib

Classes12.jar web.xml

http://localhost:8080/InitParamApp/emp.html

emp.html

<html><body><form action=”. /dbs”>Id : <input type=text name=txtId><br>Name: <input type=text name=txtName><br>Salary<input type=text name=txtSalary><br><input type=”submit”><form></body></html>

web.xml

<web-app>

Page 57: Adv Java

<servlet><servlet-name>init</servlet-name><servlet-class>Database Servlet</servlet-class><init-param><param-name>d</param-name><param-value>oracle.jdbc.driver.OracleDriver</param-value></init-param><init-param><param-name>url</param-name><param-value>jdbc:oracle:thin:@localhost:1521:server</param-value></init-param><init-param><param-name>user</param-name><param-value>scott</param-value></init-param>

<init-param><param-name>pwd</param-name><param-value>tiger</param-value></init-param></servlet><servlet-mapping><servlet-name>init</servlet-name><url-pattern>/dbs</url-pattern></servlet-mapping></web-app>

DatabaseServlet.java

import javax.servlet.*;import java.io.*;import java.sql.*;

public class DatabaseServlet extends GenericServlet{Connection con;public void init (ServletConfig config) throws ServletException{

Page 58: Adv Java

String driver=config.getInitParameter (“d”);String url=config.getInitParameter (“url);String u= config.getInitParameter (“user”);String p=config.getInitParameter (“pwd”);try{Class.forName (driver);con=DriverManager.getConnection (url, u, p);

}catch (Exception e){}}public void service (ServletRequest req, ServletResponse res) throws ServletException, IOException {try{res.setContentType ("text/html");PrintWriter pw=res.getWriter();pw.println ("<html>");pw.println ("<body bgcolor=wheat>");pw.println ("<center>");Statement st=con.createStatement ();ResultSet rs=st.executeQuery ("select * from emp where ename="+req.getParameter ("empno"));ResultSetMetaData metadata=rs.getMetaData ();int count=metadata.getColumnCount ();if (rs.next ()){pw.println ("<h2>EMPLOYEE DETAILS</h2>");pw.println ("<table border=1 cellpadding=3 cellspacing=0>");pw.println ("<tr>");for (int i=1;i<=count;i++)pw.println ("<th align=right width=100>"+metadata.getColumnName (i) +"</th>");pw.println("</tr>");pw.println ("<tr>");for (int i=1; i<count; i++)pw.println ("<td align=right width=100>"+rs.getString (i)+"</td>");

Page 59: Adv Java

pw.println ("</tr>");pw.println ("</table>");}elsepw.println ("<h3>Employee record not found</h3>");pw.println ("</center>");pw.println ("</body>");pw.println ("</html>");pw.close ();}//trycatch (Exception e){System.out.println ("Some Exception");System.out.println (e);}}//service ()

Public void destroy (){try{if (con! =null)con.close ();}catch (Exception ex){}}}}

Page 60: Adv Java

Note:

War file creation is not mandatory for tomcat ServerIn such case copy our own web application root directory into D:\tomcat\webapps. Then we start the Server. Container installs the application. This is known as Cold Deployment.

As far as classes12/classes111 files are concerned we can copy one of them in d:\tomcat\common\lib. Once we do this for every web application Oracle Driver is available. Therefore we need to create lib directory in every web application.

Java.sql.ResultSetMetaData interface:

ResultSet interface provides methods to retrieve data from the table of records. But it does not provide ant data about that data i.e., it does not provide any methods to deal with column names, their number, size, etc.

ResultSetMetaData encapsulates the information about the columns. We get the reference to this object as follows:

ResultSetMetaData rsmd=rs.getMetaData ();

Page 61: Adv Java

Calling a Stored Procedure from a java program:

Stored Procedure:

It is a database object that encapsulates business logic in the database server. We can think of Stored Procedure as a java method.

From a java program, in order to call a Stored Procedure, we make use of java.sql.CallableStatement interface which is a sub-interface of PreparedStatement. Making use of CallableStatement to call a Stored Procedure involves the following steps:

Requesting for the Connection

Prepare the special syntax known as Escape Syntax

Building the CallableStatement object

Register the out parameters

Executing the call to the Stored Procedure

Bind the in parameters, if any

Retrieve the out parameters values

Close the CallableStatement

Close the Connection

Page 62: Adv Java

1) Requesting for the connection:Class.forName (“Driver Class”);Connection con=DriverManager.getConnection (“url”,”user”,”pwd”);

2) Preparing the Escape Syntax:In order to call a Stored Procedure, we need to create a CallableStatement object. In order to create that object, we need to prepare special SQL statement known as Escape syntax.String str= “{call proc1 (?,?)}”;

3) Building the CallableStatement object:To create the CallableStatement object, we make the following method call on the connection object.CallableStatement cst =con.prepareCall (String escape-syntax);

4) Binding the in parameters:It is similar to PreaparedStatement process.

5) Registering the out parameters:We should inform to the CallableStatement object about the out parameters to be expected from the Stored Procedure so that while extracting the values we can call appropriate getXXX() on that object.All this is done by calling registerOutParameter () on the CallableStatement object.Whenever a Stored Procedure definition involves out parameters or in-out parameters, this step is mandatory.

6) Executing the call to the Stored Procedure:CallableStatement object contains a call to the Stored Procedure. In order to make a call to the Stored Procedure we should say cst.execute ();

7) Retrieve the out parameters:On the CallableStatement object we make a call to getXXX () methods basing upon the registered out parameters.

8) Closing the CallableStatement:cst.close ();

9) Closing the Connection:con.close ();

Page 63: Adv Java

1) Example program on CallableStatement:

import java.sql.*;class StoredProcedure{public static void main (String args[]){Connection con=null;try{Class.forName ("oracle.jdbc.driver.OracleDriver");System.out.println ("Driver Loaded. ...”);String url="jdbc:oracle:thin:@90.0.0.4:1521:oracle";con=DriverManager.getConnection (url,"scott","tiger");System.out.println ("Connection Established.......");CallableStatement cst=con.prepareCall ("{call proc2 (?,?)}");cst.registerOutParameter (2, Types.VARCHAR);cst.setInt (1, 1001);cst.execute ();String str=cst.getString (2);System.out.println ("Employee Name:"+str);cst.close ();}catch (ClassNotFoundException cfe){System.out.println ("Driver class not found");System.out.println (cfe);}catch (SQLException e){System.out.println ("SQL"+e);}finally{try{if (con!=null){con.close ();}

Page 64: Adv Java

}//trycatch (SQLException e){System.out.println ("SQL final"+e);}}//finally}//main ()}//end of class

SQL Statements needed for Example 1 Program:create table emp10 (id number, name varchar(12));insert into emp10 (1001,'adil');create or replace procedure proc2 (n number, nm out varchar)asbeginselect name into nm from emp10 where id=n;end proc2;/

2) Example program on CallableStatement:

import java.sql.*;class StoredProcedureSample{public static void main (String args []){try{int accno=Integer.parseInt (args[0]);Class.forName ("oracle.jdbc.driver.OracleDriver");System.out.println ("Driver Loaded....");Connection con=DriverManager.getConnection ("jdbc:oracle:thin:@90.0.0.4:1521:oracle","scott","tiger");System.out.println ("Connection Established.....");CallableStatement cst=con.prepareCall ("{call addinterest(?,?}");System.out.println ("Callable Statement created....");cst.registerOutParameter (2, Types.FLOAT);cst.setInt (1, accno);cst.execute ();System.out.println ("Stored procedure executed....");

Page 65: Adv Java

System.out.println ("New Balance of A/c "+ accno+"is: Rs."+cst.getFloat (2));cst.close ();con.close ();

}catch (ArrayIndexOutOfBoundsException aie){System.out.println ("Supply Account number please");System.out.println ("USAGE: java StoredProcedureSample 1001");}catch (Exception e){System.out.println (e);}}//main ()}//class

SQL Statements needed for Example 2 Program:

create table account (id number (4), balance number (7,2));

insert into account values (1001, 5000);

create or replace procedure addinterest (id in number, bal out number)as begin select balance into bal from account where is=id;bal:=bal+bal*0.5;update account set balance =bal where id=id;end;/

Page 66: Adv Java

Q) What is the Servlet init () code that retrieves all the initialization parameters and their corresponding values?

A) Enumeration params=config.getInitParameterNames ();While (params.hasMorElements ()){String pname= (String) params.nextElement ();String pvalue=config.getInitparameters (pname);System.out.println (pname+”:”+pvalue);}

Q) What is wrong with the following code?

public void init (ServletConfig config) throws ServletException{String driver=getInitParameter (“driver”);}

A) We are calling getInitParameter () method on the Servlet instance. It should have been called on config instance.Even then, compiler does not report an error. However, once the Servlet is deployed, we get the NullPointerException.

Q) How many interfaces GenericServlet implements?

A) GenericServlet implements 3 interfaces:

java.io.Serializablejava.servlet.Servletjavax.servlet.ServletConfig

GenericServlet implements Servlet interface to follow the specification

It is implementing Serialization interface to become persistent, if required

It implements for the sake of programmers conveniences.

i.e., whatever methods ServletConfig object possess all those methods can directly be called on the Servlet interface.

Page 67: Adv Java

Q) What is the problem with the following code?

Public class A extends GenericServlet{Public void init (ServletConfig config) throws ServletException{}Public void service (ServletRequest request, ServletResponse response) throws ServletException, IOException{String value=getInitParameters (“d”);}}

A)a) Compile time errorb) No error at compilationc) Runtime errord) No runtime error

The above code generates null pointer exception

ServletConfigSerializable Servlet

GenericServlet

Our Servlet

Page 68: Adv Java

Q) What is the Default implementation of GenericServlet?A) public abstract GenericServlet implements

Servlet,Serializable,ServletConfig{ServletConfig _config;public void init () throws ServletException{}public void init (ServletConfig config) throws ServletException{_config=config;init ();}………………………………public String getInitParameter (String name){returns _config.getInitParameters (name);}………………………………}

Page 69: Adv Java

GenericServlet class provides 2 init methods to the child classes. 1. Dummy implementation in the zero argument init () method.2. In parameterized init() method, it does 2 things :

1) Storing the Container provided ServletConfig object globally within the class

2) Making a call to zero argument init () method.

GenericServlet provides implementation for all the methods of ServletConfig interface. This is done to facilitate the programmers to call any ServletConfig method directly on the Servlet instance without the need of ServletConfig object.

Zero argument init () is not life cycle method.Parameterized init () is part of life cycle method which the Container calls.

Page 70: Adv Java

javax.servlet.ServletContext

Container creates the object of some class that implements ServletContext interface at the time of our Web Application installation. The reference of this object is encapsulated in the ServletConfig object. Therefore if we want to get the reference of ServletContext, we have to call getServletContext () on the ServletConfig object. ServletContext object represents the Web Application Environment i.e., ServletContext is an abstraction of the Web Application itself.

A servlet can view the Web Application and its contents via ServletContext object. Servlet can communicate with the Container via ServletContext object. ServletContext objects is only one per Web Application, where as ServletConfig object is one per Servlet.

ServletContext object acts as Global Memory Area (Shared Information Repository) for all the Servlets and Jsps of the Web Application.Application Level State is stored in the ServletContext object. One servlet can store data in this object and other servlet can share that information.

ServletContext interface provides the following methods:

1) Methods to deal with Application Level State:

I. set Attribute(String name, Object value)II. Object get Attribute(String name)

III. removeAttribute (String name)IV. String getInitParameter (String name)V. Enumeration getInitParameterNames ()

2) Methods to communicate with the environment:

I. String getServerInfo ()II. Log (String information)

III. RequestDisaptcher getRequestDispatcher (String path)

Page 71: Adv Java

Q) Web Application on ServletContext?

A)

ServletContextAppData.htmlWEB-INF Web.xml Classes

StorageServlet.classRetrieveServlet.class

http://localhost:8080/ServletContextApp/data.html

//data.html

<html><body bgcolor=pink><center><h1>PERSONAL DETAILS</h1><form action=”./store”>EMAIL ID<input type=text name= “email”><br>PHONE<input type=text name=”phone”><br><br><input type=submit value=SUBMITDETAILS></form></center></body></html>

//web.xml

<web-app><context-param><param-name>admin</param-name><param-value>[email protected]</param-value></context-param><servlet><servlet-name>storage</servlet-name><servlet-class>StorageServlet</servlet-class></servlet>

Page 72: Adv Java

<servlet><servlet-name>retrieval</servlet-name><servlet-class>RetrieveServlet</servlet-class></servlet><servlet-mapping><servlet-name>storage</servlet-name><url-pattern>/store</url-pattern></servlet-mapping><servlet-mapping><servlet-name>retrieval</servlet-name><url-pattern>/retrieve</url-pattern></servlet-mapping></web-app>

//StorageServlet.java

import javax.servlet.*;import java.io.*;public class StorageServlet extends GenericServlet{public void service (ServletRequest request, ServletResponse response) throws IOException, ServletException{String email=request.getParameter ("email");String phone=request.getParameter ("phone");response.setContentType ("text/html"):PrintWriter pw=response.getWriter ();ServletContext sc=getServletContext ();sc.setAttribute ("mail”, email);sc.setAttribute ("telephone”, phone);String adminmail=sc.getInitParameter ("admin");pw.println ("<html>");pw.println ("<body bgcolor=wheat>");pw.println ("<h3>Web site admin available at "+adminmail+"</h3>");pw.println ("<h2><a href=./retrieve>GET YOUR DETAILS HERE</h2>pw.println ("</body>");pw.println ("</html>");pw.close ();}

Page 73: Adv Java

}

//RetrieveServlet.java

import javax.servlet.*;import java.io.*;public class RetrieveServlet extends GenericServlet{public void service (ServletRequest request, ServletResponse response) throws

IOException, ServletException{response.setContentType ("text/html"):PrintWriter pw=response.getWriter ();ServletContext sc=getServletContext();String mail=(String)sc.getAttribute("mail");String phone=(String)sc.getAttribute("telephone");String adminmail=sc.getInitParameter ("admin");pw.println ("<html>");pw.println ("<body bgcolor=cyan>");pw.println ("<h2>YOUR PERSONAL DETAILS</h2>");pw.println ("<h3>EMAIL ID:"+mail+"</h3>");pw.println ("<h3>TELEPHONE#:"+phone+"</h3>");pw.println ("<h3>Web site admin available at "+adminmail+"</h3>");pw.println ("</body>");pw.println ("</html>");pw.close ();}}

Page 74: Adv Java

HttpServlet Basics:

Web Client and Web Server communicate with each other by using protocol. Therefore they are known as Http Client and Http Server respectively.

Depending upon the way the request is made by the Client to the Server, the request is famously categorized into 2 areas known as HttpRequest methods.

We have 2 important Request methods:1. GET method 2. POST method

Both are HttpRequest methods from Bowser to Server.

Q) Differences between GET and POST methods?A)

GETPOST

It is default methodWe need to explicitly specify it

This request can be made either by typing the url directly or by clicking on hyperlink or through a form

Only with html form this request is possible.

Primary purpose of this method is to get data from the server.Therefore it should not be used for data updations.

It is basically meant for posting data into the server for updations.

Http Client Http Server

HttpRequest

HttpResponse

Page 75: Adv Java

Request headers have no body. Any data should be associated to request line in the form of query string

It has body. Data is not appended to the url

Sensitive information like password and credit card information should not e sent through this method.

We can send

Amount of data transfer from client to server is limited.

No limitations

It is idempotent(no side effects) It is not idempotent(side effects can raise as we update the database)

Side Effects:If due to network delay, we are typing/clicking the same button again and again then the data can have effect repetitively

Q) How to write (create) a form that makes get request/ post request?A) <form action= “ “ method = “post”If we don’t specify the method attribute in the html form tag, by default it is get request method only.

Q) What is the basic functionality of a Servlet?A) To extend the functionality of a web server.GenericServlet is not http protocol specific. Therefore by using GenericServlet we cannot provide the functionality to the http server.For example, session tracking, http request headers reading etc.Therefore we make use of javax.Servlet.http.Httpservlet class.

Servlet

GenericServlet

Our Servlet

HttpServlet

Page 76: Adv Java

Life cycle of HttpServlet

Javax.servlet.http.HttpServlet class extends GenericServlet. As GenericServlet implements Servlet interface. HttpServlet also become eligible to act as a Servlet.

HttpServlet provides http specific behoviour to our own servlet. That is the reason why our servlet can provide complete support for the Web Server(HttpServer)

When we are discussing HttpServlet life cycle means we are discussing our own servlet that extends HttpServlet.

Page 77: Adv Java

HttpServlet Life Cycle:

Loading of Servlet Class

Servlet instance creation

ServletConfig object creation

init () method calling

ServletRequest, ServletResponse object creation

Public service method calling

Calls the protected service (req, res)

Call doGet(),DoPost() methods

More request?

If administrator undeploys Servlet

Call destroy () method

Page 78: Adv Java

Public service method calling

HttpServlet class provides default implementation for the abstract service method of the GenericServlet. In this method implementation only http specificness starts. The following is the implementation.

Public void service(ServletRequest request,ServletResponse response) throws ServletException,IOException{HttpServletRequest req=(HttpServletRequest) request;HttpServletResponse res=(HttpServletResponse) response;Service(req,res);}

Calls the protected service (req, res)

In the public service method a call is made for the protected service () method.Converting ServletRequest and ServletResponse to HttpServletRequest and HttpServletResponseCalls its own protected service(httpServletRequest req,HttpServletResponse res) methods belongs to HttpServlet class only.HttpServlet class has given following default implementation for the protected service method:Protected void service(HttpServletRequest req,HttpServletresponse res) throws ServletException,IOException{String requestmethod=req.getmethod()If(requestmethod.equals(“GET”))doGet(req,res);If(requestmethod.equals(“POST”);doPost(req,res);}

Call doGet() doPost() methods

Depending upon the incoming http request method from the Browser, either doGet() or doPost() method is called.The following is the default implementation for these methods given by the HttpServlet

Page 79: Adv Java

Protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{PrintWriter pw=response.getWriter();Pw.println(“GET REQUEST ISW NOT SUPPORTED”);Pw.close();} Protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{PrintWriter pw=response.getWriter();Pw.println(“POST REQUEST ISW NOT SUPPORTED”);Pw.close();}

Q) public class OurClass extends HttpServlet{}OurClass has how many implemented methods approximately? Name them.

The following methods are inherited from HttpServlet by OurClass

Init()Init(ServletConfig config) Public void service(ServletRequest req,ServletResponse res)Protected void service(HttpServletRequest req,HttpServletResponse res)Calls 2 more service methods-doGet() and dpPost() depending on the evaluating the request object call doGet/doPost

Protected void doGet(HttpServletRequest res,HttpServletResponse res)ServletConfig interface methods as GenericServlet implements this

getInitparametersgetServletNamesgetServlet

other 3 methods of Servlet interface i.e. destroy()

Page 80: Adv Java

From now onwards whenever we write a Servlet class, we extend only HttpServlet and override doGet() or doPost() or both.

Web Application on HttpServlet implementation

LoginApp login.html WEB-INF

web.xml classes LoginServlet.class

http://localhost:8080/LoginApp/login.html

login.html

<html><body bgcolor="pink"><center><h2>LOGIN TO WEB APPLICATION</h2><form action=". /login" method="post">USER NAME : <input type="text" name ="user"><br>PASSWORD : <input type="password" name="pwd"><br><br><input type="submit" value="CLICK HERE"></form></center></body></html>

web.xml

<web-app><servlet><servlet-name>authenticate</servlet-name><servlet-class>LoginServlet</servlet-class></servlet><servlet-mapping><servlet-name>authenticate</servlet-name><url-pattern>/login</url-pattern>

Page 81: Adv Java

</servlet-mapping></web-app>

Page 82: Adv Java

LoginServlet.java

import javax.servlet.http.*;import javax.servlet.*;import java.io.*;public class LoginServlet extends HttpServlet{public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{String user=request.getParameter ("user");String pwd=request.getParameter ("pwd");response.setContentType ("text/html");PrintWriter pw=response.getWriter ();if (user. equals (pwd)){pw.println ("<html>");pw.println ("<body bgcolor=cyan>");pw.println ("<h2>Welcome to our Shopping Mall</h2>");pw.println ("</body>");pw.println ("</html>");}else{pw.println ("<html>");pw.println ("<body bgcolor=pink>");pw.println ("<h3>Invalid user name</h3>");pw.println ("<a href=login.html>TRY AGAIN</a>");pw.println ("</body>");pw.println ("</html>");}pw.close ();}}

Page 83: Adv Java

Web Application on RequestDispatch

Directory Structure

RequestDispatchemp.htmlcaption.html (to use it in second servlet)WEB-INF

web.xmlclasses

GrossServlet.javaNetServlet.java

http://localhost:8080/RequestDispatch/emp.html

emp.html

<html><body bgcolor=”wheat”><center><form action=”. /gross”>Employee Basic <Input type=text name=”basic”> <br><input type=”submit”></form></center></body></html>

caption.html

<html><body bgcolor=”cyan”><marquee><font size=6 color=green> Welcome to HR systems</font></marquee></body></html>

Page 84: Adv Java

GrossServlet.java

import javax.servlet.*;import javax.servlet.http.*;import java.io.*;

public class GrossServlet extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response ) throws

IOException, ServletException {String b= request.getParameter("basic");float basic = Float.parseFloat(b);float da=0.5f*basic;float hra=0.4f*basic;float gross = basic+hra+da;Float f= new Float (gross);request.setAttribute("gross", f);ServletContext sc=getServletContext();RequestDispatcher rd=sc.getRequestDispatcher("/net");rd.forward(request, response);} }NetServlet.java

import javax.servlet.*;import javax.servlet.http.*;import java.io.*;

public class NetServlet extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response ) throws

IOException, ServletException {Float gross=(Float) request.getAttribute("gross");float net = gross.floatValue() - 500;response.setContentType("text/html");PrintWriter out=response.getWriter();

Page 85: Adv Java

getServletContext().getRequestDispatcher("/caption.html").include(request,response);out.println("<html>");out.println("<body bgclor=wheat>");out.println("<h3> Employee net salary is : " + net +"</h3>");out.println("</body");out.println("</html>");out.close();}}web.xml

<web-app><servlet><servlet-name>source</servlet-name><servlet-class>GrossServlet</servlet-class></servlet>

<servlet><servlet-name>target</servlet-name><servlet-class>NetServlet</servlet-class></servlet>

<servlet-mapping><servlet-name>source</servlet-name><url-pattern>/gross</url-pattern></servlet-mapping>

<servlet-mapping><servlet-name>target</servlet-name><url-pattern>/net</url-pattern></servlet-mapping>

</web-app>

Also do: - Convert this to include mechanism in source. Use include instead of forward method in source.

Page 86: Adv Java

Filters

A Filter is a Container Managed Object that acts as interceptor between the Client and the Web Component in the request-response cycle.

A Filter is not a Web Resource by itself i.e., Client never addresses the request to the Filter. For that matter, Client does not know that Filter exists.Similarly Web Component (Servlet/ jsp) also does not know that a Filter exists.

Any request before reaching the Servlet is passed through Filter object.Similarly any response coming from the Servlet passes through the Filter before it is delivered to the Client.

A Filter can do any of the following things:

After receiving the request on its own can give the response back to the Client without forwarding the request to the Servlet.

After receiving the request it can forward the request to the Servlet for processing

It can redirect the request to other Web Component.

SERVLET

Req Req Req

Res Res Res

Client Servlet Container

Filter 1 Filter 2

Page 87: Adv Java

Development and Deployment of Filter in a Web Application:

Any java class that implements javax.servlet.Filter interface can be a Filter class.This interface provides three life cycle methods:

1. init (FilterConfig)2. doFilter (ServletRequest, ServletResponse, FilterChain)3. destroy()

A Filter has life cycle similar to the Servlet life cycle. Servlet Container creates the instance of our own developed Filter class at the time of Web Application installation.

Servlet Engine creates the FilterConfig instance. Container calls the init () method on the Filter instance by supplying the config object. FilterConfig instance is capable of retrieving init parameters and context information (similar to the ServletConfig)

A Filter servicing phase is nothing but performing filtering. Container calls doFilter () method whenever the request comes from the Client to that Web Component (Servlet/jsp) to which this Filter is associated.Container creates 3 instances - request, response and Filter Chain and these objects are passed to the filter via doFilter () method.

FilterChain object is used by the Filter to continue filtering or passing the request to the Web Component.

Deployment of a Filter

Deployment of a filter into a Web Application is a 2 step processCopying the Filter class file into the classes directoryRegistering the Filter with the Web Application in the web.xml and perform mappings with the required web resource to which we want to apply the Filter.

Page 88: Adv Java

Web Application on the implementation of Filter that is associated to a Servlet:

FilterApplogin.htmlrelogin.htmlWEB-INF

classesWelcomeServlet.classAuthenticateFilter.class

web.xml

http://localhost:8080/FilterApp/login.html

Note:Filter should be registered before Servlet.

web.xml

<web-app>

<filter><filter-name>authenticate</filter-name><filter-class>AuthenticateFilter</filter-class></filter>

<filter-mapping><filter-name>authenticate</filter-name><url-pattern>/login</url-pattern></filter-mapping>

<servlet><servlet-name>welcome</servlet-name><servlet-class>WelcomeServlet</servlet-class></servlet>

<servlet-mapping><servlet-name>welcome</servlet-name><url-pattern>/login</url-pattern>

Page 89: Adv Java

</servlet-mapping>

</web-app>

login.html

<html><body bgcolor=cyan><center><form action=". /login" method=POST>User Name : <input type=text name="user"><br> Password : <input type=password name="pwd"><br><input type=submit value="login here"></form></center></body></html>

relogin.html

<html><body bgcolor=cyan><center><h2>INVALID USER OR PASSWORD</h2><form action="./login" method=POST>User Name : <input type=text name="user"><br> Password : <input type=password name="pwd"><br><input type=submit value="login here"></form></center></body></html>

AuthenticateFilter.java

import javax.servlet.*;import javax.servlet.http.*;import java.io.*;

Page 90: Adv Java

public class AuthenticateFilter implements Filter{FilterConfig fc;public void init (FilterConfig config) throws ServletException{fc=config;System.out.println("Filter is instantiated and initialized");

}//init()public void doFilter (ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException{String user=request.getParameter ("user");String pwd=request.getParameter ("pwd");if (user. equals (pwd))chain.doFilter (request, response);//forward to Servletelse{response.setContentType ("text/html");ServletContext sc=fc.getServletContext ();RequestDispatcher rd=sc.getRequestDispatcher ("/relogin.html");rd.forward (request, response);}//Filter sending response to client}//doFilterpublic void destroy (){fc=null;}}

WelcomeServlet.java

import javax.servlet.*;import javax.servlet.http.*;import java.io.*;

public class WelcomeServlet extends HttpServlet{

Page 91: Adv Java

public void doPost (HttpServletRequest request, HttpServletresponse response) throws ServletException.IOException{response.setContentType ("text/html");PrintWriter out=response.getWriter ();out.println ("<html>");out.println ("<body bgcolor=cyan>");out.println ("<h2>WELCOME TO THIS SITE</h2>");out.println ("</body>");out.println ("</html>");out.close ();}}

Q) How does a filter work?A)  When ever a request comes to a particular web resource servlet engine pickup the URP pattern and searches for the filter association with the URL patern. If the filters are found for that servlet inside of routing the request to the servlet it routs to the filter. Q) How to supply initialization parameters to t a filter?A)   In the web.xml we make the following entries to initialization parameters:- <filter>            <filter-name>      </filter-name>            <filter-class>                </filter-class>             <init-param>            <param-name>             </param-name>            <param-value> </param-value>            </initparam>

             <init-param>            <param-name>             </param-name>            <param-value> </param-value>            </initparam> </filter> Q) How does a filter receive initialization parameters?

Page 92: Adv Java

 A)      public void init(FilterConfig congig) {String driver = config.getInitParameter(“d”);String URL= config.getInitParameter(‘url”;---------} Q) What is chaining of Filter? How to implement it?A) Associating more than one Filter to a Servlet is known as Filter Chaining.To implement Filter Chaining we need not program anything, either in the Filter class or in the Servlet class.In the web.xml we make following entries:

<filter><filter-name>x </filter-name><filter-class> </filter-class></filter><filter><filter-name>y</filter-name><filter-class> </filter-class></filter><filter-mapping><filter-name>x</filter-name><servlet-name>registration name of servlet</servlet-name>[Can also give url-pattern]</filter-mapping><filter-mapping><filter-name>y</filter-name><servlet-name>registration name of servlet</servlet-name>[Can also give url-pattern]</filter-mapping>

Page 93: Adv Java

Java Server Pages

JSP is a specification. A JSP page is a Web Component. It is as active Web Resource in a Web Application A jsp serves the Web-Client A jsp produces the dynamic Web-Context. A jsp is meant for extending the functionality of Web-Server. A jsp contains html plus java code.

Disadvantages of Servlets:

Servlets are excellent in the execution of application logic and there by generating the dynamic content. But they are very poor in context presentation.Context generation logic and presentation logic is tightly coupled. As a result of such tight coupling, we encounter the following problems:

Tools cannot be used effectively for web page creation nor for servlet java code.

Development and maintenance problems arise for the website.

Advantages of jsp:

Almost all the disadvantages of servlets are addressed in this server side technology.

Key points about jsp programming:

Jsp is not a replacement for servlets but it is only an extension. A jsp cannot serve a client on its own. Web Container converts the jsp

into a servlet in the background and that Container generated servlet only can serve the client request.

We author a jsp. Writing/authoring a jsp page is other way of writing a servlet. Instead

of us writing the servlet, we are instructing the container to write a servlet for us.

Generally saying, a servlet is nothing but writing html code inside java code whereas a simple jsp is nothing but writing java code inside html code.

Page 94: Adv Java

A Web Container that has servlet engine, jsp engine and http service can host jsps and serve client requests.

Life Cycle of JSPLife cycle of JSP is developed in 6 phases and 3 life cycle methods. Life cycle phases are:

Translation phase Compilation phase Instantiation phase Initialization phase Servicing phase Destruction phase

Life cycle methods are:

jsp_Init () _jspService () jspDestroy ()

Whenever client is making a request to the jsp file, jsp engine performs two things:

1) Translating jsp into .java file. This is the source code of container-generated servlet.

2) Compiling the servlet source code into .class file.

Once container generated .class file is created, jsp engine role ends.

First.jsp First_jsp.classFirst_jsp.java

Translation Compilation

Page 95: Adv Java

After translation and compilation phases servlet engine takes the control and the other 4 phases are similar to normal servlet life cycle.

Page 96: Adv Java

Tabular representation of jsp Life Cycle:

Case/context Request# Translation

Compilation

Instantiation

Initialization

Servicing

Jsp first authored

R1 R2 * * * *

Container restarted

R1 * * R2 * * * *

Jsp modified R1 R2 * * * *

Constituents of a jsp

Constituents Ofjsp

html (template text)

jsp tags (elements)

java

scripting element

directives

actions

declaration

expression

scriptlet

includepage

length

custom

standard

include

forward

param

plugin

useBean

setProperty

getProperty

Page 97: Adv Java

1) Scripting elements:

According to JSP specification we have 3 kinds of scripting elements. They are known as scripting elements because inside the jsp, embedding of java code is possible through them.

I. Declaration:

Anything enclosed between <%! and %> is a declaration according to JSP specifications.Inside a declaration we can write any valid java variable declaration/definition and method definition

For example:

<%! int a; //variable declaration int b=10; //variable definition void x () { }//method declaration %>

Whatever we write inside declaration becomes a direct member of the Container generated servlet class.

int a; instance variable

static int b=10; class variable

class c inner class{}

void x () instance method{}

In a declaration if a variable is initialized that initialization happens only in the first request to this jsp.

Page 98: Adv Java

In the subsequent request to the jsp, initialization does not happen again.

II. Expression:

Anything enclosed between <%= %> is an expression. Expression acts as place holders for java expression

An expression is evaluated every time the request comes to jspWhen the expression is executed two things happen in the background:

1. Java expression is evaluated 2. The request of the evaluation is written to the output stream of jsp.

Note:

Inside the jsp expression, java expression statement should not end with a semicolon [;]

For example:<% = a+b %>

Ex: code on declaration and expression

<%! String names [] = {“adil”,”baber”,”mohammad”};String getNames (int index){Return names [index]}%><%= getName (1) %>

III. Scriptlet:

Anything that starts with <% and ends with %> is a scriptlet according to JSP specification.

Inside a scriptlet we can write *free form of java code.

*free form means any logic but no class or method declarations.

Page 99: Adv Java

In a jsp we can have any number of scriptlets.

A scriptlet is inserted into _jspService of the container generated servlet.

Ex: <% for (int i=0;i<0;i++)System.out.println (“hello”);Int a=10;%>

We can declare variables. We cannot declare functions as this goes into service method. Therefore function within function is not acceptable hence do not write method in scriptlet.

Comments in a jsp:

When we author a jsp, we can have 3 kinds of comments:

i. Java comments: Inside declaration, scriptlet but not in the expression.//, /* */

ii. Html comments:<! - -html comments - ->are ignored by jsp engine.

When jsp o/p is sent to the browser and when we view the source from view menu, we can’t see the jsp comments but can see html comments. Jsp comments can’t be sent to the browser. Wherever jsp comments are declared, we can declare the html comments.

Implicit objects in jsp:

As the container converts jsp to servlet it declares and initializes 9 objects to get the request, response, config, context objects, etc. to get the values from form elements.

In the _jspService () method of the container generated servlets, 9 non primitive variables are locally declared and initialized.

Page 100: Adv Java

Non primitive variables means references declared. If references are initialized then they become objects.

These nine objects are by default available to every jsp*.

(*conditions apply)

Q) Can we write here?

<%! void x (){request.getParameter (“hello”);}%>

A) No we can’t as the implicit objects are valuable in expression and scriptlet.

Inservlet class {Void x (){request.getParameter (“-“);}_jspService(){}}}

As declaration falls under the part of initialization but expression and scriptlet falls under the part of _jspService () method where we have 9 implicit objects hence can’t use the statement in declarations.

These objects are known as implicit Objects in a jsp, implicit objects are available only for expressions and scriptlets but not for declarations.

Page 101: Adv Java

9 implicit objects (case sensitive):

1. out: It is the output stream for the jsp. This object is of type javax.servlet.jsp.JspWriter class

<% out.println (“Hello world”); %>

But it is not available as normal text can be included in html only. If any information calculated by servlet and given back to browser in that case we can use this statement.

<%! Void x (){Print (“hai”);}%>

2. request: This is of type HttpSrvletRequest for accessing the client data.

3. response: This is of type HttpServletResponse

4. application: javax.servlet.ServletContext

ServletContext is a global area to Web Application.

Q) How a jsp can retrieve data from ServletContext?

Use <% application.setAttribute %>It is directly available in jsp but in Servlets we need to create an object using getServletContext () method.

5. config: javax.servlet.ServletConfig

config.getInitParameter (-----);

getServletConfig () method is used in servlet to create but this object is directly available in jsp.

6. session: javax.servlet.httpSession

Page 102: Adv Java

request.getSession () in servlet to get session but in jsp it is directly available.

7. page: refers to the current servlet instance. This is of type java.lang.Object

Just like this. refers to current object, a present servlet instance can be referred as page.

8. exception: This is of type java.lang.Throwable

This is available only to those jsp which possibly error thrown while act as error pages. All jsp will not get this object (*conditions apply policy come here).

This object is not available to every jsp. Those jsp which act as error handling pages can get this implicit object.

9. pageContext: This is of type javax.servlet.jsp.pageContext class.It represents entire jsp page environment.

Page 103: Adv Java

Web Application using jsp pages:

WelcomeJspAppwelcome.jspWEB-INF

web.xmlclasses

http://localhost:8080/WelcomeJspApp/welcome.jsp

web.xml

<web-app></web-app>

welcome.jsp

<html><body bgcolor=cyan><h2>First JSP Example</h2><% out.println ("welcome to jsp");%></body></html>

Jsps are placed in the public area of the root directory of the Web Application.Never ever jsp is sent to the client. Jsp is the server side component. The output (html) generated by the jsp is sent to the client.

Tomcat5.0/work -> go on clicking if you will find welcomeJspApp in that you will find container generated servlet.

Page 104: Adv Java

Example Web Application to explore the declarations and expressions of a jsp

SecondJspApptwo.jspWEB-INF

web.xmlclasses

http://localhost:8080/SecondJspApp/two.jsp

two.jsp

<html><body bgcolor = wheat><%! int count=0;String names [] = {"adil","baber"};private String getName (int index){return names [index];}%><h2>Number of times this page visited <%= ++count %> </h2><h3>The user is <%= getName (1) %>< /h3></body></html>

Whatever variables, arrays, and methods we define in a jsp, they become direct members of the Container generated servlet class. Variable initialization occurs only once.

Expression of the jsp is inserted in the service method of the Container generated servlet in the given order. They are evaluated and their output is sent to the client every time the page is requested.

Page 105: Adv Java

Application on scriptlet, expression and implicit variable (object)

third.jsp:

<html><body bgcolor = wheat><h2>DATE AND TIME <%= new java.util.Date () %> </h2><h2>SERVER DETAILS : <%= application.getServerInfo () %>< /h2><% for (int i=1; i<=5; i++){%><h2> WELCOME TO JSP</h2><%}%></body></html>

Web Application in which a jsp captures the form data, generates the dynamic web content and sends the output to the Client

GreetingAppuser.htmlgreet.jspWEB-INF

web.xmlclasses

http://localhost:8080/greetingApp/user.html

user.html

<html><body bgcolor=yellow><form action="./greet.jsp">User : <input type=text name=t><br><input type=submit></body>

Page 106: Adv Java

</html>

greet.jsp

<html><body bgcolor=wheat><h2>hello <%= request.getParameter ("t") %>< /h2></body></html>

Page 107: Adv Java

USING JAVA BEANS IN A JSP

Java Bean: A java bean is a specialized java class with some standard naming conventions.A normal java class becomes a bean class if we define the class according to java bean specifications.

The following are the rules:

1. Class must be public.2. Class should have public default constructor.3. Properties of the class must be private.4. Each property of the class should have public setXXX () and getXXX

() methods.5. The class has to implement java.io.Serializable interface.

Example java bean:

public class Employee implements java.io.Serializable{private int empno;private String name;private float salary;public void setEmpno(int empno){this.empno=empno;}public int getEmpno (){return empno;}public void setName(String nm){this.name=nm;}public int getEmpno (){return name;}public void setSalary(float salary)

Page 108: Adv Java

{this.salary=salary;}public float getSalary(){return salary;}}//bean class

Note:Java beans make use of Servlet or jsp. On its own the beans will not execute.

Important points for a java bean:

A java bean is used in a Web Application by the Web Components.A java bean acts as a model (data holding and data accessing entity) in a Web Application that is developed using MVC architecture.Model-Java beansView-jspController-ServletIn a medium range to large (not very large) range Web Applications, MVC architecture is mandatory and java bean usage is inevitable.In a Web Application, if we are using java beans, it is mandatory that bean class must be under user defined package.A java bean when used in a jsp or in a Servlet, bean instantiation fails if user defined package is not defined.While defining a bean class, for each bean field we write one setter method and one getter method.Setter method is meant for populating the beans instance (giving values to the variables) getter method is to get the state of the bean.A java bean is instantiated and populated by servlets or jsp.When we make use of java bean in a jsp, container takes care of bean instantiation populating it and getting the bean sate.We instruct the container to do so through jsp tags (useBean, setProperty, getProperty).In a Web Application, a bean represents a record in a database.A bean is populated in two waysA Servlet or jsp does it with form data.Bean should contact the database and populate itself.

Page 109: Adv Java

Java Beans

Limiting or eliminating java code form jsp:

A jsp contains java and html. We need to limit the java from directly in jsp and send it to indirectly at background.

A jsp contains template text for presentation and direct java code to provide dynamism for the page. There are some draw backs in this approach:

Tools cannot be used for java code development Error handling and testing is not convenient Code re-usability is not possible.

To minimize or totally eliminate java code from the foreground of the jsp we have many approaches:

Normal java class encapsulating the application logic. Java bean Custom actions Expression language

First approach:

MyAppHtmlJspWEB-INF

ClassesXyz.class- write application logic here

Page 110: Adv Java

Second approach

Using a java bean in a jsp:In a jsp if we make use of a java bean in place of a normal java class, we will have the following benefits:

We can eliminate java code completely from the jsp Data sharing across jsps is more flexible Excellent synchronization between bean fields and html form fields.

Whenever we want to deal with a java bean in a jsp we make use of 3 standard actions.

1) useBean2) setProperty3) getProperty

1) useBean:

It is used to create a java bean instance or to retrieve the existing bean instance. This standard action is in the following form:

<jsp: useBean id=”ref” class=”beanpack.BeanClass” />

The above instruction when received by the jsp engine, 2 things happen:

I. Bean class instance is created and it is bound to the reference referred by the attribute ‘id’.

II. The bean class instance is stored in pageContext object.

2) setProperty:

This is a standard (pre defined by the specification) instruction given by the jsp author to the jsp engine to populate the bean instance. This is of the following form:

<jsp: setProperty name=”ref” property=”beanproperty” value=”anyvalue” />

Once this instruction is received by the jsp engine a particular property of the bean instance with the specified name is populated with the given value.

Page 111: Adv Java

Note: In place of value we can mutually exclusively (either of them but not both) use param attribute.param attribute is used to deal with html form data.

3) getProperty:

This standard action is used to retrieve beans state with an xml kind of syntax without need of writing any java code directly in the jsp. This is of the following form:

<jsp: getProperty name=”ref” property=”beanproperty” />

The above instruction performs 2 things:

I. Retrieving the bean field dataII. Sending the output to the client

Q) Between bean fields ans html form ields god synchronization exists. Exlain?

Html form

Jsp gets data and stores data to object.

Emp No

Name

Salary

CLICK

Page 112: Adv Java

Employee emp =new Employee ();->In the background employee object is created<jsp: useBean id=”emp” class=”mypack.Employee” /><jsp:setProperty name=”emp” param=”ti” /> -> In html form instead of each parameter we get a paramEmployee emp=new Employee();Emp.setEmpno(Integer.parseInt(request.getParameter(“t1”);->In the background the bean instance is cerated and setting the value.

Web Application

BeanAppBook.htmlView.jspWEB-INF

web.xmlClasses

BookpackBook.class

Book.html

<html><body><center><H2>Book Details Form</H2><form action ="View.jsp">ISBN: <input type="text" name="isbn"><br>Title: <input type="text" name="title"><br><input type="submit" value="submit book details"></center></body></html>

Book. java

package Bookpack;public class Book implements Serializable

Page 113: Adv Java

{private int isbn;private String title;public void setIsbn (int isbn){this.isbn=isbn;System.out.println (“Bean is populated”);}public int getIsbn (){return isbn;}public void setTitle (String title){this.title=title;}public String getTitle (){return title;}}web.xml

<web-app></web-app>

View.jsp

<html><body bgcolor=cyan><center><h1>Book details from the bean </h1><%@ page import="Bookpack.Book" %><jsp: setProperty name="b" property ="*" /><h2>Book ISBN: <jsp: getProperty name="b" property ="isbn" /></h2><h2>Book Title: <jsp: getProperty name="b" property ="title" /></h2><br><br><input type="submit"></center></body>

Page 114: Adv Java

</html>Once control went to jsp and bean is instantiated If any constructions will execute when the setProperty are called using * all the setXXX () properties are called.

Note:

In the above jsp we have used page directive. This directive is used here to import the package of the book bean class.

Page 115: Adv Java

Every jsp implicitly imports 4 packages

1. java.lang.*2. javax.servlet.*3. javax.servlet.http.*4. javax.servlet.http.jsp.*

If we need any other package (standard/user defined) to be implemented into the jsp, we make use of page directiveExample:<%@ page import =”java.util.*” %>To include more than one package we can separate them using comma (,)

As far as synchronization of bean fields and html form fields are concerned, we used the following statement in the View.jsp<jsp: setProperty name=”b” property=”*” />The above instruction makes the container implicitly calling all the setter methods of the bean instance whose reference is “b”. But one condition here is that request parameters names (text field name) and bean variable names must match for using *.

In this statement properties “*” can’t be used to normal classes if we want to setProperty use the param or value attribute.

Equivalent jsp code

b.setIsbn (Integer.parseInt (request.getParameter (“isbn”)));b.setTitle (request.getParameter (“title”);If html names and bean variables are not matching “*” will not work in that case we use 3 attributes <jsp: setProperty name=”b” property=”isbn” param =”is” /><jsp: setProperty name=”b” property=”title” param =”ti” />

Sharing a java bean instance across multiple jsp

useBean standard action is capable of performing 2 things:1) Creating new bean instance every time when the request comes to the jsp.2) If the bean instance already exists, it retrieves the existing one and does

not create new one.

Page 116: Adv Java

useBean has one more attribute called scope. We can give 4 possible values to it. This attribute decides whether new bean instance has to be created or existing instance is to be used/ retrieved.

Values:

1. page 2. request 3. application4. session

In the useBean standard action if we don’t mention scope attribute, by default it takes page scope.If scope is page, the bean is non shareable.

Q) Why is the bean not shareable across pages if its scope is page?

A) If the bean scope is page (by default), it is stored in the pageContext object in binding to the reference specified by the id attribute of the useBean standard action.

PageContext object is separate for every jsp and pageContext object is dead as soon as response is given to the client. Therefore, bean stored in this object also will be dead. Therefore bean is not shareable across jsps.

Q) Develop and deploy a Web Application in which two jsps sharing the same bean (state) when the scope is “request”?

Page 117: Adv Java

A) SharingbeanAppEmp.htmlSource.jspTarget.jspWEB-INF

web.xmlClasses

EmppackEmployee. class

http://localhost:8080/sharingbeanApp/emp.html

Source code of Employee bean

Package emppack;Public class Employee implements Serializable{private int empno;private String name;public void setEmpno(int empno){this.empno=empno;}public int getEmpno(){return empno;}public void setName(String name){this.name=name;}public int getName(){return name;}

}//Employee

c:>/javac –d . Employee.java

Page 118: Adv Java

Source code of emp.html

<html><body><center><h1>EMPLOYEE DETAILS FORM</h1><form action=”source.jsp”>EMPLOYEE NO<input type=”text” name=”empno”><br>EMP NAME<input type=”text” name=”name”><br><input type=”submit”></form></center></body></html>

Source code of Source.jsp

<%@ page import =”emppack.Employee” %><jsp:useBean id=”emp” class=”emppack.Employee” scope=”request” /><jsp:setProperty name=”emp” property=”*” /><jsp:forward page=”target.jsp”>

Source code of target.jsp

<html><body bgcolor =”wheat”><%@ page import=”emppack.Employee” %><jsp:useBean id=”emp” class=”emppack.Employee” scope=”request” /><center><h1>EMPLOYEE DATA</h1><h1>EMPLOYEE NUMBER : <jsp:getProperty name=”emp” property=”empno” /></h1><h1>EMPLOYEE NAME : <jsp:getProperty name=”emp” property=”name” /></h1></center></body></html>

web.xml

Page 119: Adv Java

<web-app></web-app>

Note:

When the scope is request, the bean instance is not only bound to the reference variables but also it is stored in the request object. When control is switched to another jsp using forward mechanism, the second jsp gets the same request object in which the bean and the state is stored. In the second jsp when we make use of useBean, new instance is not created; the existing bean is retrieved from the source jsp.

Q) Web Application to explore session scope concept of sharing of beans across multiple jsps?A) In the previous Web Application within the two jsps make the scope as session.When the scope is session, bean instance is stored in the session object. How many jsps are participating in the same session, all those jsps shares the bean instance.

Page 120: Adv Java

Jsp model 1 architecture

In this architecture, jsp is the core element. It is responsible for receiving the client request, instantiating the bean, populating the bean, retrieving the database data from the bean and driving the output to the client.

Jsp model 2 architecture

This is famously known as MVC architecture. In this model of Web Application loose coupling is implemented.It defines separation of concerns (who has to do which job) very clearly.As a result, Web Application development becomes flexible, easier and enhancements of services become cheaper.

DATABASE

jsp

Java Bean

1

2

4

5

3Web Client Web Container

Page 121: Adv Java

Explanation as per the numbers:

1. Servlet receives the Client request, does the preliminary processing.2. Servlet creates the bean instance and populates it with the form data.3. Bean contacts the database gets the necessary data and populates

itself.4. Servlet switches the control to the jsp making it responsible to drive

the output to the client.5. Jsp contacts the bean for the sake of data that is required to prepare

the output.6. Jsp prepares the output and gives to Client.

DATABASE

Servlets

Java Bean

1

6

3Web Client Web Container

jsp

4

2

5

Page 122: Adv Java

In MVC architecture, java bean acts a model, jsp acts as a view, servlets acts as Controller.Model: data holding or data oriented logic holding entity is known as a Model. Java bean play this role.View: For the end user, not only interaction but also appealing web page should be given. Jsp is excellent in giving a beautiful output (it is mixed with html and jsp). Jsp is good at this. Therefore it acts as View.Controller: Servlet plays the role of Controller in the MVC architecture of Web Application because it is excellent in application logic execution, it is responsible for receiving the client request, does preliminary processing, dealing with bean and asking the jsp prepare the output.

Q) Web Application on MVC architecture

A) Refer to Hand-out

MVCAppEmp.htmlView.jspWEB-INF

web.xmlClasses

Nit Servlets

ControllerServlet.classBeanpack Employee.class

http://localhost:8080/MVCApp/emp.html

Source code of emp.html :

<html><body bgcolor=”./mvc”>

</html><html><body bgcolor="cyan"><form action="./mvc"><center>EMPLOYEE NUMBER<input type="text" name="eno"><br><br>

Page 123: Adv Java

<input type=SUBMIT value="SNDEMPNO"></center></body></html>

Source code of Employee.java :

package beanpack;import java.sql.*;public class Employee implements java.io.Serializable{Connection con;private int empno;private String name;private float salary;public Employee(){try{Class.forName("oracle.jdbc.driver.OracleDriver");con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","scott","tiger");}catch(Exception e){}public void setEmpno(int empno){this.empno=empno;results();}public int getEmpno(){return this.empno;}public void setName(String name){this.name=name;}public String getName()

Page 124: Adv Java

{return this.name();}public void setSalary(float salary){this.salary=salary;}public float getSalary(){return this.salary;}public void results(){try{Statement s=con.createStatement();ResultSet rs=s.executeQuery("select * from employee where

empno="+empno);rs.next();name=rs.getString("name");salary=rs.getFloat("salary");}catch(Exception e){}}}//class

Source code of ControllerServlet.java :

package nit.servlet;import javax.servlet.*;import javax.servlet.*;import beanpack.Employee;import java.io.*;public class ControllerServlet extends HttpServlet{public void doGet(HttpServletRequest request, HttpServletResponse

Page 125: Adv Java

response) throws ServletException,IOException{int empno=Integer.parseInt(request.getParameter("eno");Employee ebean=new Employee();ebean.setEmpno(empno);getServletContext().setAttribute("ebean",ebean);getServletContext().getRequestDisapatcher("/view.jsp").forward(request,respo

nse);}}

Source code of View.jsp :

<html><body>EMPLOYEE DETAILS<br><br><%@ page import="beanpack.Employee" %><jsp:useBean id="ebean" class="beanpack.Employee" scope="application" />EMPNO : <jsp:getProperty name="ebean" property="empno" /><br>NAME : <jsp:getProperty name="ebean" property="name" /><br>SALARY : <jsp:getProperty name="ebean" property="salary" /><br></body></html>

Source code of web.xml :

<web-app><servlet><servlet-name>controller</servlet-name><servlet-class>nit.servlets.ControllerServlet</servlet-class></servlet><servlet-mapping><servlet-name>controller</servlet-name><url-pattern>/mvc</url-pattern></servlet-mapping></web-app>

Page 126: Adv Java

Web Application development and deployment steps :

Create the Root directory “MVCApp”Compile the Employee class >javac –d . EmployeeCopy the beanpack in the classes directoryBefore compiling the servlet class set the classpathSet classpath=D:\WorkingDir;%classpath%Compile the Servlet class D:\WorkingDir>javac –d . ControllerServlet.javaCopy the nit package into the classes directoryCopy the emp.html and view.jsp in the MVCAppCopy the MVCApp into the webapps directory of Tomcat installtion directory http://localhost:8080/MVCApp/emp.html

Page 127: Adv Java

Include mechanism in jsp

In industry strength Web Application pages are not created in monolithic manner. A page may include other page context. This mechanism is known as include mechanism.

Code duplication is avoided and web page development becomes faster with include mechanism.

Include mechanism in a jsp is implemented in 2 ways:

1) By using include directive 2) By using include standard action

<%@ include file=”target.jsp” %><jsp:include page=”target.jsp” />

1) include directive: when we use directive the source code of the included file (target) is copied into current jsp at translation time.

2) include standard action: the response of the target jsp is included in the current jsp’s response at request processing time.

Page 128: Adv Java

Q) What are the differences between include directive and include standard action?

A) S.No Criteria Directive Standard Action

1 syntax <%@ include file =”target.jsp” %>

<jsp:include page=”target.jsp”%>

2 What is included Source code of target file

Output of target page

3 When is it included Translation time Runtime4 How many servlets

created1 2

5 Does source jsp file size increase

Yes No

6 Can handle changes to target file(jsp)

No Yes

7 Comparative performance

More Less

Web Application on the implementation of include directiveIncludedirApp

Source.jspHeader.jspFooter.htmlWEB-INF

web.xmlClasses

http://localhost:8080/includedirApp/source.jsp

Source code of Header.jsp

<html><body><marquee><font color=”green” size=8> WELCOME TO OUR SITE</font></marquee>

Page 129: Adv Java

</body></html>

Source code of footer.html

<html><body><br><br><br><br><br><br><br><br>@copy Naresh Information Technologies</body></html>

Source code of source.jsp

<html><body bgcolor=cyan><%@ include file=”header.jsp” %><h1>HERE GOES THE BODY OF THE JSP</h1><@ include file=”footer.html” %></body></html>

web.xml

<web-app></web-app>

Web Application on include standard action

IncludeactionAppSource.jspTarget.jspWEB-INF

Web.xmlClasses

http://localhost:8080/includeactionApp/source.jsp

Page 130: Adv Java

Source code of source.jsp

<html><body bgcolor=”wheat”><h1>INCLUDE ACTION USAGE</h1><jsp:include page=”target.jsp”><jsp:param name=”user” value=”[email protected]” /></jsp:include>

</body></html>

Source code of target.jsp

<html><body bgcolor=wheat><h1><% out.println(“request.getParameter(“user”)); %></h1></html>

Session tracking

Protocols are of two types:Stateless protocolStateful protocol

A protocol is said to be Stateless if it has no memory of prior connections in the server side and server cannot distinguish one client request from that of the other.

When http client makes a request to the http server, it gives response to the client. Once request-response cycle is over, client is disconnected form the server. This nature poses some challenges to the Web Application developers.

Client interaction with the Web Application must be Stateful. Then only, across series of requests a client is uniquely recognized and previous data can be associated with the current request.

Page 131: Adv Java

Session tracking is the ability of the Container to recognize the Client and its associated data across multiple series of interactions.

To make Client interactions Stateful with the Web Applications, SERVLET API provides support for the following techniques:

CookiesHttpsessionurl rewriting

cookies mechanism

a cookie is a name value pair of textual information created bythe server and exchanged between client and server with every interaction

SERVLET API provides the following to implement cookies mechanism

Javax.servlet.http.CookieJavax.servlet.http.HttpServletRequest interfaceJavax.servlet.http.HttpServletResponse interface

We have 2 kinds of cookies Persistent cookiesSession cookies(browsing)

A cookie is said to be persistent if it is stored in the file system of the client machine.

Session cookies is a cookie which will die as soon as browsing session is over.

Steps to implement cookies mechanism

Step 1: instantiating the Cookie class.Cookie c=new Cookie(“bgcolor”, “red”);

Step 2: Setting the life span of the Cookie(if required)c.setmaxAge(365*24*3600);

Page 132: Adv Java

Step 3: Sending the cookie to the client

Response.addCookie(c);

Step 4: Whenever required, retrieval of Cookie(s)Cookies c[]=request.getCookies();

Q) Web Application on the implementation of cookie mechanism?

CookieAppCookieExample.htmlWelcome.htmlWeb-INF

Web.xmlClasses

CreateCookie.classCheckCookie.class

http://localhost:8080/CookieApp/CookieExample.html

Source code of CookieExample.html

<html><body bgcolor=cyan><center><h2>WELCOME TO SHOPPING MALL</h2><form action=”./create” method=”post”><b>User Name</b><input type=text name=”user” > <br> <br><input type=submit value=”welcome” > <br> <br></center></body></html>

Source code of Welcome.html

<html>

Page 133: Adv Java

<body><marquee><font color=green size=6>WELCOME TO SHOPPING MALL</marquee></body></html>

Source code of CreateCookie.java

Import java.io.*;Import javax.servlet.*;Import javax.servlet.http.*;Public class CreateCookie extends HttpServlet{Public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException,IOException{String name=req.getParameter(“user”);Res.setContentType(“text/html”);PrintWriter pw=res.getWriter();Cookie c=new Cookie(“user”,name);Res.addCookie(c);Pw.println(“<html>”);Pw.println(“<body bgcolor=wheat><center>”);Req.getRequestDispatcher(“welcome.html”).include(req,res);Pw.println(“<h2><a href=”./check”>SHOPPING GOES HERE</a></h2>”);Pw.println(“</center></body></html>”);Pw.close();}}

Source code of CheckCookie.java

Import java.io.*;Import javax.servlet.*;Import javax.servlet.http.*;Public class CreateCookie extends HttpServlet{

Page 134: Adv Java

Public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,IOException{Res.setContentType(“text/html”);PrintWriter pw=res.getWriter();Cookie c[]=req.getCookies();Pw.println(“<html>”);Pw.println(“<body bgcolor=wheat><h2>”);For(int i=0;i<length;i++){Cookie c1=c[i];If(c1.getName().equals(“user”)){Pw.println(“Hai”+c1.getValue() + ! Hope enjoying shopping here </h2>”)Break;}}

Pw.println(“</body></html>”);Pw.close();}}

Web.xml

<web-app><servlet><servlet-name>create</servlet-name><servlet-class>CreateCookie</servlet-class></servlet><servlet><servlet-name>check</servlet-name><servlet-class>CheckCookie</servlet-class></servlet><servlet-mapping><servlet-name>create</servlet-name><url-pattern>/create</url-pattern></servlet-mapping><servlet-mapping><servlet-name>check</servlet-name>

Page 135: Adv Java

<url-pattern>/check</url-pattern></servlet-mapping></web-app>

Q) what are the uses of Cookies in Web Application development?A)

Remembering the user preferences To promote targeted Online advertisementsUniquely identifying a client

Note: Browser is intelligent enough to send cookies to the server from where they are generatedA browser can store a maximum of 300 cookiesFrom each server a maximum of 50 cookies are allowedLimitation of cookies is it cannot hold more than 4 kb of information

Q) How to destroy a cookie in a servlet?

A) c.setMaxAge(0);

Cookie Example in jsp:

CookieAppUserdetails.htmlReaddetails.jspGetcookies.jsp

userdetails.html

<html><body bgcolor=wheat><form action=”./readdetails.jsp”>Email ID: <input type=text name=”mail”><br>Phone: <input type=text name=”phone”><br><br><input type=submit value=”submit details”></form></body></html>

Page 136: Adv Java

Source code of readdetails.jsp

<%String emailid=request.getParameter(“mail”);String phone=request.getParameter(“phone”);Cookie c1=new Cookie(“mail”,emailed);Cookie c2=new Cookie(“phone”,phone);Response.addCookie(c1);Response.addCookie(c2);Out.println(“<a href=”./getcookies.jsp”>CLICK HERE TO GET YOUR DETAILS</a>””);%>

Source code of getcookies.jsp

<%Cookie c[]=request.getCookies();Out.println(“EMAIL ID:” +c[0].getValue());Out.println(“PHONE NUMBER:+”c[1].getValue());%>

Session tracking using HttpSession

Session tracking is the ability of the container to associate series of requests with a particular client uniquely. In this process 2 things are to be taken care of

1) Recognizing the client2) Associating client data with the client request

HttpSession is an interface. Its object is created by the Container. This session object represents the association between client and its request.

Steps to implement Session Tracking using HttpSession object.

Step 1: Create the HttpSession object and get its reference.

Page 137: Adv Java

HttpSession session=request.getSession ();

Step 2: Retrieve the client data in the current request and add it to the session object.session.setAttribute (String name, Object value);

Step 3: Whenever we want to retrieve client data after a series of client interactions, we saysession.getAttribute ()Orsession.getAttributeNames ()

Step 4: When the end user explicitly wants to logout, destroy the session object.

Q) How does session tracking working behind the scenes?

A) When getSession () method is called on the request object, it does lot of work in the background.1. It checks the incoming http request headers for session id. Case 1: if session id is encountered, container does not create the new session object. It gives the reference to the existing session object.Case 2: If session id is not encountered, this method creates one new session object, its associated id. This key value pair is internally maintained in a table kind of form.

For each client, a separate session object is created.

When the response is given to the client, container sends the associated session id through response header. For sending session id, cookie mechanism is internally used.

Page 138: Adv Java

Q) What is seesion time-out in Session tracking?A) For each client one session object is dedicated. It will consume few

server resources. Between the last client request and current system time, if a specified amount of time is lapsed which is known as max inactive interval, container destroys the session object associated with that client. This is known as session time-out. When the session object is destroyed, session id as well as client state gets discarded.By default tomcat gives 30 minutes for session time-out. Wecan also configure session time in two ways:

DeclarativelyProgramatically

In the web.xml, we make the following entry:

<session-config><session-timeout>45</session-timeout></session-config>

In a servlet we can say as follows:Session.setMaxInactiveInterval(2700);

Q) Explain overloaded methods of HttpServletRequest to get the HttpSession reference?

A) To get the HttpSession reference of a session object, we make use of the overloaded versions of req.getSession() method. There is no difference between the zero argument method and parameterized method if the argument is true.If the argument is false, getSession() method behaves differently from that of zero argument one. It works as follows:Container looks for the session id in the incoming request header. If it is found the reference to the existing session object is returned. If it is not found, session object is not created. Instead, it returns null.

Q) If we use HttpSession mechanism for session tracking, will it work fine all the times?A) No. if cookies are disabled in the browser, session tracking fails.Remedy for this is url-rewriting.

Page 139: Adv Java

Web Application on URL Rewriting

rewritingAppWEB-INF

Web.xmlClasses

SessionDetailsServlet.class

web.xml

<web-app><servlet><servlet-name>details</servlet-name><servlet-class>SessionDetailsServlet</servlet-class></servlet><servlet-mapping><servlet-name>details</servlet-name><url-pattern>/details</url-pattern></servlet-mapping></web-app>

Source code of SessionDetailsServlet.java

import javax.servlet.*;import javax.servlet.http.*;import java.io.*;import java.util.*;

public class SessionDeatilsServlet extends HttpServlet{public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException{response.setContentType("text/html");PrintWriter pw=response.getWriter();HttpSession session=request.getSession();Integer count=(Integer) session.getAttribute("requestcount");if(count==null)count=new Integer(1);

Page 140: Adv Java

elsecount=new Integer(count.intValue()+1);session.setAttribute("requestcount",count);pw.println("<html><body bgcolor=cyan>");pw.println("<h3>Number of times this page visited:" +count + "</h3>");pw.println("<h2>Your session details </h2>");pw.println("<h2>session id: +session.getId() +"</h2>");if(session.isNew())pw.println("<h2> It is a New Session</h2>");elsepw.println("<h2> It is an existing session </h2>");pw.println("<h2>Created Time: ");pw.println(new Date(session.getCreationTime())+"</h2>");pw.println("<h2>Last accessed Time: ");pw.println("new Date(session.getLastAccessedTime())+"</h2>");pw.println("<h2>Time out in seconds:"+session.getMaxInactiveInterval()+"</h2>");pw.println("<h3>Is session ID coming from cookie: "+request.isRequestedSessionIdFromCookie()+"</h3>");pw.println("<h3>Is session ID coming from URL: "+request.isRequestedSessionIdFromURL()+"</h3>");pw.println("<a href=\""+response.encodeURL(request.getRequestURI())+"\">RELOAD THIS PAGE</a>");//url rewritingpw.println("</body></html>");}}

Page 141: Adv Java

URL rewriting: It is the mechanism of appending session id to the URL to which the request is going to be submitted. To implement this mechanism we call encodeURL method on the response object as follows:

Response.encodeURL (String URL);

This method does not do anything if cookie mechanism is working. If cookies are disabled, this method appends session id to the URL so that client can be uniquely identified.

Custom Action

An action is a functionality provided by the container whenever its associated tag is encountered.

In jsp we have 2 kinds of actions (tags):

1) Standard actions2) Custom actions

1) Standard actions

Standard actions are runtime instructions given by the jsp author to the jsp whose meaning is already known to the container. The advantage of these actions is that by using xml kind of syntax tags, we can get the functionality. There is no need of writing java code directly in the jsp. This makes jsp development easier, flexible, and maintainable.

2) Custom actions

Our own defined actions are known as custom actions.

Syntax and working of custom actions is similar to that of standard actions.

Standard actions are excellent in their functionality but they ate confined to few areas. In practical industry strength Web Applications, this limited functionality is not sufficient.

Page 142: Adv Java

Complex functionality has to be provided. Hence the need of our own defined actions.

Q) What are the differences between standard action and custom actions?

Standard actions Custom actionsTheir meaning is already known to the container

We need to explain

Tags and associated java code is shipped along with the container

We should develop tags plus java code

Functionality is limited Can be used for any complex functionality

Common for every jsp in every web application

Specific to certain Web Application

We need not import any library in order to use them

We have to

Custom Tag Development

While dealing with custom tags, we encounter the following terminology.

1) Tag

It is an instruction given by the jsp author to the container

Tag has 2 parts

I. Prefix II. Action name

For example,

<jsp: forward>

Here jsp is the prefix and forward is the tag name<own: printhello>

2) Tag Handler

Page 143: Adv Java

It is a java class that provides the action (functionality) for the tag.3) Tag library Descriptor

It is an xml file with any name but with .tld extension.

In this file tags and their properties are described. Mapping between tags and corresponding tag handlers specified. Tag library information is specified.

4) Tag library

Combination of tags, tag handler and tld.

Steps to develop Custom Tag:

There are 5 steps to develop and use a Custom tag

Step 1: Define the Tag handlerStep 2: Write the Tag Library DescriptorStep 3: Deploy the Tag Library

Copy the class file of the Tag handler in the classes directory Copy th etld file under WEB-INF

Step 4: Register the Tag Library with the Web Application by making an entry in the web.xmlStep 5: Using a Custom Tag in a jsp.

In order to use the Custom tag, e have to import the tag library into th ejsp by using taglib directive.Developing a tag Handler for a Custom Tag

A Tag Handler is any java class that implements javax.Servlet.jsp.target.tag interface directly or indirectly.

TagSupport class implements Tag interface and thereby provides default functionality to our own Tag handler classes. Therefore, our own Tag Handler classes extend javax.Servlet.jsp.tagext.TagSupport class.Tag interface provides the following life cycle methods.Void setpageContext(PageContext)Int doStartTag()

Page 144: Adv Java

Int doEndTag()Void release()

Page 145: Adv Java

Flow chart for Tag interface

Q) Web Application to implement a Custom Tag and use it in a jsp

A) Refer to the hand-out

Step 1: Develop tag HandlerPublic class HelloHandler extends TagSupport{………..}Step 2: Writing the Tag Library Descriptor(.tld)<taglib>…………</taglib>

SetPageContext(PC)

SetAttributes()………………

After the Custom Tag, further contents of jsp to be evaluated

Return from the current jsp without evaluating

Container evaluates the body of the tag

DoStartTag()

DoEndTag()

Tag.EVAL_BODY_INCLUDE

Tag.EVAL_PAGE Tag.SKIP_PAGE

Page 146: Adv Java

These files has 2 sectionsDescription about the libraryTags definiton and mapping to Tag HandlerStep 3: Deploying the Tag LibraryStep 4: Registering the Tag Library with the Web ApplicationIn the web.xml, we make use of <taglib> element for Tag Library registrationStep 5: Using the Custom Tag we have to import the Tag Library<%@ taglib prefix=”nit” uri=”mapping name to tld file” %>

customtagappWEB-INF

Web.xmlTld Ourtaglib.tldClasses Hellopack

HelloHandler.class

http://localhost:8080/customtagapp/hello.jsp

source code of hello.jsp

<html><body bgcolor=wheat><%@ taglib prefix="nit" uri="http://www.nit.com/customtags" %><h3><nit:hello />WELCOME TO CUSTOM TAGS</h3></body></html>

source code of web.xml

<web-app><taglib><taglib-uri>http://www.nit.com/customtags</taglib-uri><taglib-location>/WEB-INF/tld/ourtaglib.tld</taglib-location></taglib></web-app>

source code of ourtaglib.tld

<taglib>

Page 147: Adv Java

<tlib-version>1.0</tlib-version><jsp-version>2.0</jsp-version><short-name>nit</short-name><tag><name>hello</name><tag-class>hellopack.Hellohandler</tag-class><body-content>empty</body-content></tag></taglib>

source code of HelloHandler.java

package hellopack;import jaax.servlet.jsp.*;import jaax.servlet.jsp.tagext.*;import java.io.*;public class HelloHandler extends TagSupport{public int doStartTag() throws JspException{try{JspWriter out=pageContext.getOut();out.println("hello");}catch(IOException e){System.out.println(e);}return SKIP_BODY;}}

Q) How does a Custom Tag works?A) Whenever Custom tag is encountered in jsp, the Container performs the following things:Picks up the prefix of the Custom Tag and looks fro the match in the taglib directiveOnce match is found it picks up the uri value of the taglib directiveWith that uri value it looks in the web.xml for the uri matchOnce the match is found, it picks up the location of the tld file from the web.xmlContainer looks in the tld file for the encountered custom tag( in the jsp)

Page 148: Adv Java

Once the tag is found, it looks for the corresponding tag handler.Tag Handler is loaded into memory instantiated and initializedOur application looks written in the Life Cycle method gets executed. This is how a particular Custom gets the functionality.

Q) What is the Life Cycle of the Custom Tag?A) Container loads the java class (tag handler) and instantiates it.Container calls the setPageContext() on the Tag Handler instance. Through this method, Container provides the entire jsp environment to the Tag Handler via PageContext object tag Handlers responsibility is to hold this object our own Tag Handler extends AgSuport class and that class provides some default functionality is, holding (saving globally within the class) the PageContext object.PageContext object provides getXXX() methods to retrieve all the implicit objects.Once setPageContext() method is completely executed, Tag Handler is initialized.As the start Tag is encountered Tag is encountered by the Container, it callsteh doStartTag() on the Tag Handler instance.In this method, we write our required logic. This logic is the background functionality for the Custom Tag.This method returns any one of the 2 integer constants of the tag interface.Tag.EVAL_BODY_INCLUDETag.SKIP_BODY

These constants are indicators totheContainer what to do nextWhen jsp engine encounters the end Tag in the jsp, it calls the doEndTag() method on the Tag Handler instance.

This method returns any of the 2 consants.Tag.EVAL_PAGE(default)Tag.SKIP_PAGE

Q) Web Application on Custom Tag without body but with attributes?

A) Refer to hand-out. Whenever attributes are there for a tag, we have to do two things in the Tag Handler.

Declare those many private variables as there are attributes.For each variable, one setter method.

Step 2: In the tld file we have to make entries regarding the attributes<tag>

</tag>

ClassicTagWithAttributesGreet.jspWEB-INF

Web.xmlTld

Page 149: Adv Java

Ourtaglib.tldClasses Greetpack

GreetingHandler.class

source code of greet.jsp

<html><body bgcolor=wheat><%@ taglib prefix="nit" uri="htp://www.nit.com/customtags" %><h2><nit:greet name="Adil" Age="23" /></h2></body></html>

source code of web.xml

<web-app><taglib><taglib-uri>http://www.nit.com/customtags</taglib-uri><taglib-location>/WEB-INF/tld/ourtaglib.tld</taglib-location></taglib></web-app>

source code of ourtaglib.tld

<taglib><tlib-version>1.0</tlib-version><jsp-version>2.0</jsp-version><short-name>nit</short-name><tag><name>greet</name><tag-class>greetpack.GreetingHandler</tag-class><body-content>empty</body-content><attribute><name>name</name><required>true</required><rtexprvalue>true</rtexprvalue></attribute><attribute><name>age</name><required>true</required>

Page 150: Adv Java

<rtexprvalue>true</rtexprvalue></attribute></tag></taglib>

Source code of GreetingHandler.java

package greetpack;import java.io.*;import javax.servlet.jsp.*;import javax.servlet.jsp.tagext.*;public class GreetingHandler extends TagSupport{private String name;private int age;public void setName(String name){this.name=name;}public void setAge(int age){this.age=age;}public int doStartTag() throws JspException{try{JspWriter out=pageContext.getOut();out.println("Hello "+name+" your are "+age+" yearsold");}catch(IOException e){System.out.println(e);}return SKIP_BODY;}}

Page 151: Adv Java

<attribute> element has 3 child elements:

1) <name>: This is an Optional Element. Its value is by default false. If we specify it as true, it means that for the custom tag this attribute and corresponding is mandatory.

2) <required>: This is an optional element. Its values are by default false. If we specify it as true, it means that for the custom tag this attribute and corresponding is mandatory.

3) <rtexprvalue>: It is also an optional element. Its value is by default false. If we specify it as true, it means that the attribute value can be supplied at request time processing only.

Q) Web Application on custom tag implementation. Its Tag Handler performs database access. It receives html form data also?

A) Refer to the hand-out.

DatabaseappResults.htmlResults.jspWEB-INF

Web.xmlMytaglib.tldClasses

StudentsResultshandler.class

http://localhost:8080/databaseapp/results.html

Source code of results.html :<html><body bgcolor=cyan><h2>ENTRANCE EXAM RESULTS</h2><form action=”./results.jsp”>HallTicketNO<input type=text name=”htNp”><br><input type=”submit” value=”get results here”></form></body>

Page 152: Adv Java

</html>

Source code of results.jsp :

<html><body bgcolor=cyan><%@ taglib uri=”customtags” prefix=”nit” %><h2>ENTRANCE SCORE CARD</h2><h3><nit:results /></h3></body></html>

Source code of web.xml :

<web-app><taglib><taglib-uri>customtags</taglib-uri><taglib-location>/WEB-INF/mytaglib.tld</taglib-location></taglib></web-app>

Source code of mytaglib.tld :

<taglib><tlib-version>1.0</tlib-version><jsp-version>1.2</jsp-version><short-name>nit</short-name><tag><name>results</name><tag-class>students.ResultsHandler</tag-class><body-content>empty</body-content></tag></taglib>

Source code of ResultsHandler.java :

Package students;Import javax.servelt.jsp.*;

Page 153: Adv Java

Import javax.servlet.jsp.tagext.*;Import java.sql.*;Public class ResultsHandler extends TagSupport{Connection connection;Public ResultsHandler(){Try{Class.forName(“oracle.jdbc.driver.OracleDriver”);Connection=DriverManager.getConnection(“jdbc:oracle:thin:@localhost:1521:orcl”,”scott”,”tiger”);}Catch(Exception e){}Public int doStarttag() throws JspoException{Try{JspWriter out=pageContext.getOut();String htNo=pageContext.getRequest().getparameter(“htNo”);Statement st=connection.createStatement();ResultSet rs=st.executeQuery(“select * from entrance where htNo=”+htNo);Rs.next();Out.println(“HAL:L TICKET NUMBER :” +htNo);Out.println(“CANDIDATE NAME:”+rs.getString(2));Out.println(“MARKS:”+rs.getString(3));Rs.close();St.close();}Catch(Exception e){}Return SKIP_BODY;}//doStartTag()Public void release(){Try{

Page 154: Adv Java

If(connection!=null)Connection.close();}Catch(Exception e){}}//release}

Page 155: Adv Java

Life Cycle and Flow Chart of Iteration Tag:

Javax.servlet.jsp.tagext.IteartionTag interface is a child of Tag interface. TagSupport class implements this interface also.

IterationTag has one constant and one Life Cycle method.1. IterationTag.EVAL_BODY_AGAIN2. public int doAfterBody()

Tag

IterationTag TagSupport

Extends

Implements

Interface

Interface

Page 156: Adv Java

setPageContext(PC)

setAttributes()………………

Evaluate the rest of the jsp Return from the current jsp without evaluating

doStartTag()

doEndTag()

EVAL_BODY_INCLUDE

EVAL_PAGE SKIP_PAGE

Container evaluates the body of the tag

doAfterBody()

SKIP_BODY

EVAL_BODY_AGAIN

Page 157: Adv Java

Q) Web Application on IterationTagA) Refer to the hand-out.

IterationappLoop.jspWEB-INF

Web.xmlTld Mytaglib.tldClasses Iterationpack

IterationTagHandler.class

http://localhost:8080/iterationapp/loop.jsp

Source code of loop.jsp :

<html><body bgcolor=pink><%@ taglib prefix=”nit” uri=”customtags” %><nit:iterate count=”5” > THIS IS EVALUATED REPETITIVELY</nit:iterate></body></html>

Source code of web.xml

<web-app><taglib><taglib-uri>customtags</taglib-uri><taglib-location>/WEB-INF/tld/mytaglib.tld</taglib-location></taglib></web-app>

Page 158: Adv Java

Source code of mytaglib.tld

<taglib><tlib-version>1.0</tlib-version><jsp-version>2.0</jsp-version><short-name>nit</short-name><Tag><name>iterate</name><tag-class>iterationpack.IterationTagHandler</tag-class><body-content>JSP</body-content><attribute><name>count</name><required>true</required></attribute></Tag></taglib>

Source code of IterationTagHandler.java

Package iterationpack;Import javax.servlet.jsp.*;Import javax.servlet.jsp.tagext.*;Public class IterationTagHandler extends TagSupport{Private int count;Public void setCount(int count){This.count=count;}Public int doStartTag() throws JSpException{If(count>0)Return EVAL_BODY_INCLUDE;ElseReturn SKIP_BODY;}Public int doAfterBody() throws JSpException{If(--count>0)Return EVAL_BODY_AGAIN;

Page 159: Adv Java

ElseReturn SKIP_BODY;}}

TYPES OF RESULTSET

We have the following kinds of ResultSet:

1) Non Scrollable Non Updatable2) Non Scrollable Updatable3) Scrollable Non Updatable4) Scrollable and Updatable

A ResultSet is Scrollable if the cursor can be moved in the ResultSet in forward and between directions. We can also move the cursor to any row in ResultSet object.

A ResultSet is said to be Updatable if we can modify the rows programmatically without the need of SQL Statements directly.

Q) How to create Non Scrollable and Non Updatable ResultSet?

A) Normal way of creating the ResultSet object is Non Scrollable and Non Updatable ResultSet.

Q) How to create the Scrollable and (Non) Updatable ResultSet object?

A) At the time of ResultSet object creation, we don’t do anything special.

ResultSet rs= st.executeQuery (“Select …….”);

Page 160: Adv Java

However we need to create the Statement objects in a special manner so that they can produce Scrollable and Updatable ResultSets. We make use of overloaded versions of Connection interface to create the Statement objects.

Statement st=con.createStatement (ResultSet.SCROLLABILITYCONSTANT, ResultSet.UPDATABILITYCONSTANT);

PreparedStatement ps=con.prepareStatement (String selectStatement, scrollabilityconst, updatabilityconst);

Note:

Once we create the Statement objects in such a specialized manner, they can produce scrollable or updatable ResultSet objects.

Q) Create the java.sql.Statement object that can produce Scrollable and Non Updatable ResultSet

A) Statement st=con.createStatement (ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);OrStatement st=con.createStatement (ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);

Q) Create the Statement object that can produce Non-Scrollable but Updatable ResultSet?

A) Statement st=con.createSatement (ResultSet.TYPE_SCROLL_FORWARDONLY, ResultSet.CONCUR_UPDATABLE);

Q) What are the benefits of Scrollable ResultSet object?

A) There are few benefits if we can move the cursor in both the directions. If we can move the cursor to the required row.

Page 161: Adv Java

We can create a GUI tool using which we can browse through the records of the ResultSet object.Even after reading the row of the ResultSet object, we can read the data again.We can move to a particular row in order to update it.

Q) How many kinds of methods we have in ResultSet interface?

A) Cursor Movement methods Data accessing methods Metadata accessing methods.

Cursor Movement methods:

Next()Previous()Relative(-/+ number)Absolute(-/+ number)First()Last()beforeFirst()afterLast()

To find out the cursor position

Int getRow()Booloean isLast()Boolean isFirst()Boolean isBeforeFirst()Boolean isAfterlast()

Q) Write some piece of code to know the number of records in a tbale progarmatically

Class.forName();Connection con=DM.getConnection();Statement st=con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);ResultSet rs=st.executeQuery(“select * from employee”);

Page 162: Adv Java

Rs.last();Int noofrows=rs.getRow();

Q) Piece of code to print the records of the ResultSet in the reverse order.

ResultSet rs=st.executeQuery(“Select * from employee”);Rs.afterLast();While(rs.previous()){//Data Accessing Code}Q) What is the difference between TYPE_SCROLL_SENSITIVE and TYPE_SCROLL_INSENSITIVE?

A) The ResultSet object which contain a set of records is open to all the applications. If the modifications made to the ResultSet are also available to the external program then we say that the ResultSet is sensitive or else insensitive.

Updating records of the ResultSet programmatically :

Normally ResultSet is read only. We cannot make modifications to the records of the ResultSet. But, if we can produce a ResultSet object that is updatable we can make modifications to the records of not only the ResultSet but also of the table. To make tese modifications we need not use insert, delete or update Statements. In an object oriented way programmatically we can make modifications.

Inserting a row programmatically

Every ResultSet object is associated with a special row known as insert row. It is considered as a special buffer into which we can compose column values of a record.

Step 1: Move the cursor to the buffer row( insert row) to compose the column values.Rs.moveToInsertRow();

Page 163: Adv Java

Step 2: Compose the new row with column values. We call updateXXX() methods to do this job.

Step 3: Call the following method.Rs.insertRow(); This method call does two things : Inserting the record into the ResultSet.Inserting the record into the table.

Deleting a record programmatically

Step 1: move the cursor to the record that we want to delete Step 2: rs.deleteRow();

Record will be deleted both from the REsultSet and database (table) . The above all things are not all used in real time projects, but will be useful in GUI tools.

Batch Updates

Batch Update is a facility offered by the JDBC. By using this facility we can submit SQL Statements as a batch to the database server to perform update operations.OLTP(Online Transaction Processing)Batch Processing- Number of trips to the server can be reduced.

This is the advantage of Batch ProcessingTo implement Batch Update concepts we have 2 methods.1. addBatch(String DMLStmt)2. int[] executeBatch()

Statement object is associated with a list (some internal data structure). This list is initially empty. We can add any number of SQL Statements to the list.

St.addBatch(“insert……..”);St.addBatch(“update……”);St.addBatch(“delete…….”);

Once the bacth is formed, to submit the batch we say

Page 164: Adv Java

Int rows[]=st.executeBatch();

Q) Can we add a Select Statement to a Bacth?A) Yes, we can add even a Select Statement to a Batch without any problem it will not give any compile time error. But as a result of the execution of Select Statemnet, the set of records given that are given cannot be holded in the array compartment, so it will raise SQLException.Int[] excuteBatch()

This array would contain various compartments, each compartment for each Statement. Each compartment would contain a number that would indicate the number of rows that are effected by each of the Batch Statement.

OLTP- When the user expects the response to be given immediately after he/ she gives request.Ex: ATM

Batch update operation implementation code snippet

Statement st=con.createStatement();St.addBatch(“insert into Student values(1, ‘Adil’);St.addBatch(“delete from Student where sno=1”);St.addBatch(“Update student set sname= ‘adil’ where sno=2”);Int affectedRows[] =st.executeBatch();Int rows=0;For(int i=0;i<affectedRows.length;i++)Rows+=affectedRows[i];System.out.println(“Number of rows affected : “ +rows);

executeBatch() method throws 2 kinds of exceptions:

1. SQLException2. BatchUpdateException

For some reasons if any of the SQL Statement is unable to be excuted, the method throws BatchUpdateException

In the batch is any SQL Statement returns other than integer, i.e., DDL or DRL Statement, this method throws SQLException

Page 165: Adv Java

Simple Transaction Management

Transaction: A unit of interaction between the Client Application and the database server in which a group of SQL Statements are submitted whose effected changes are either all are made permanent or none of them are made permanent.

Or

Either all or none is a Transaction

Try{Statement st =con.createStatement();St.executeUpdate(“Update cur_acct set bal=bal-40000 where acct_no=501”);St.executeUpdate(“update sav_acct set bal=bal+40000 where acct_no=956”);}Catch(Exception e){System.out.println(e);}Note: When SQL Statements are submitted through java i.e., JDBCand once the result is given then changes are made permanent to the database. This is the advantage of submitting SQL Statements through java.In SQL, i.e., at the SQL prompt whatever changes are made to the database they aree not permanent, if we want to make the changes permanent we need to use commit.In case of transaction failure changes are rolled back.Every transaction has 2 boundaries. Controlling these boundaries is known as transaction demarcation or transaction management.The 2 boundaries of the transaction are:

1. Beginning of the Transaction2. End of the Transaction

In java when the Connection is established with the database the Connection object is opened with auto commit mode enabled. As a result each SQL

Page 166: Adv Java

Statement submitted to the database behaves as an individual transaction. Therefore, we cannot logically group SQL Statements into one unit of interaction.

In order to group a set of SQL Statements into one unit we have to disable the commit mode of the Connection object.

Con.setAutoCommit(false);

Try{Statement st=con.createStatement();Connection con=DM.getConnection();Con.setAutoCommit(false); //making the changes permanent is stoppedSt.executeUpdate(“update cur_acct set bal=bal-40000 where acct_no=501”);St.executeUpdate(“update sav_acct set bal=bal+40000 where acct_no=956”);Con.commit();//ending the transaction}Catch(Exception e){Con.rollBack();}

Once the above method call is made our unit of interaction ( transaction) starts. In order to end a transaction we have to call eitherCon.commit() – successful endingor con.rollback() – unsuccessful ending

Piece of JDBC code

try{Connection con=DM.getConnection();Statement st=con.createStatement();con.setAutoCommit(false);st.excuteUpdate("update cur set bal=bal-40000 where acct_no=501");st.excuteUpdate("update sav set bal=bal+40000 where acct_no=956");con.commit();

Page 167: Adv Java

}catch(Exception e){try{con.rollback();//this will again raise exception}catch(Exception e){System.out.println(e);}}

Whenever a Transaction is started, it should be ended whether that ending may be successful or unsuccessful ending in order to release the locks.

Q) What is type 2 Driver? Give example.

A) It is known as Native API partly java Driver.This driver eliminates ODBC layer altogether and therefore it offers better performance over Type 1 driver.

Database Server

Type 2 Drivers

Native Library

Client Server

Page 168: Adv Java

This driver converts JDBC method calls of the Client Application (JDBC program) into database server vendor dependent library calls

Disadvantages:

In every Client machine we should have DBServer library. Therefore it cannot be used in Internet applications.

OCI- Oracle Callable interface

Example:

For Oracle, type 2 driver is oracle.jdbc.driver.OracleDriver

Connection URL:

Jdbc:oracle:oci8: @localhost: 1521:orcl

Type 3:

Used in Application Server Environment.

Page 169: Adv Java

Java Server pages Standard Library (JSTL)

JSTL is a group of 4 standard tag libraries.

Core libraryDatabase accessing libraryXml data processing libraryI18n and formatting library

Core library provides tags to perform the following actions in a JSP

Accessing data from memoryTaking decisionsLooping over dataRedirecting control to other pages etc.

Steps to make use of JSTL Tags

Step 1: Copy 2 jar files into the lib directory of our Web application root directory.

Standard.jarJstl.jar

Step 2: Import the JSTL library into the jsp

<%@ taglib uri=http://java.sun.com/jstl/core prefix=”c” %>

Step 3: Make use of Expression language whenever necessary while using the tags of the library.

Expression language: It is a separate language used in the jsps along with JSTL Tags to make accessing with JSTL tags to make accessing data from memory very easier. EL totally eliminates the need of java code in the jsp.EL expression start with “{$” and ends with “}”

Example Web Applications to use JSTL Tags:

Refer to Hand out.

Page 170: Adv Java

Sending Batch Updates

The batch update facility provided by the JDBC 2.0 core API allows a Statement object to submit multiple update commands together as a single unit, or batch, to the underlying DBMS. This ability to submit multiple updates as a batch rather than having to send each update individually can improve performance greatly in some situations.

The following code fragment demonstrates how to send a batch update to a database. In this example, a new row is inserted into three different tables in order to add a new employee to a company database. The code fragment starts by turning off the Connection object con's auto-commit mode in order to allow multiple statements to be sent together as a transaction. After creating the Statement object stmt, it adds three SQL INSERT INTO commands to the batch with the method addBatch and then sends the batch to the database with the method executeBatch. The code looks like this:

Statement stmt = con.createStatement();con.setAutoCommit(false);

stmt.addBatch("INSERT INTO employees VALUES (1000, 'Joe Jones')");stmt.addBatch("INSERT INTO departments VALUES (260, 'Shoe')");stmt.addBatch("INSERT INTO emp_dept VALUES (1000, '260')");

int [] updateCounts = stmt.executeBatch();

Because the connection's auto-commit mode is disabled, the application is free to decide whether or not to commit the transaction if an error occurs or if some of the commands in the batch fail to execute. For example, the application may not commit the changes if any of the insertions fail, thereby avoiding the situation where employee information exists in some tables but not in others.

In the JDBC 2.0 core API, a Statement object is created with an associated list of commands. This list is empty to begin with; commands are added to the list with the Statement method addBatch. The commands added to the list must all return only a simple update count. If, for example, one of the commands is a query (a SELECT statement), which will return a

Page 171: Adv Java

result set, the method executeBatch will throw a BatchUpdateException. A Statement object's list of commands can be emptied by calling the method clearBatch on it.

In the preceding example, the method executeBatch submits stmt's list of commands to the underlying DBMS for execution. The DBMS executes each command in the order in which it was added to the batch and returns an update count for each command in the batch, also in order. If one of the commands does not return an update count, its return value cannot be added to the array of update counts that the method executeBatch returns. In this case, the method executeBatch will throw a BatchUpdateException. This exception keeps track of the update counts for the commands that executed successfully before the error occurred, and the order of these update counts likewise follows the order of the commands in the batch.

In the following code fragment, an application uses a try/catch block, and if a BatchUpdateException is thrown, it retrieves the exception's array of update counts to discover which commands in a batch update executed successfully before the BatchUpdateException object was thrown.

try { stmt.addBatch("INSERT INTO employees VALUES (" +

"1000, 'Joe Jones')");stmt.addBatch("INSERT INTO departments VALUES (260,

'Shoe')");stmt.addBatch("INSERT INTO emp_dept VALUES (1000, '260')");

int [] updateCounts = stmt.executeBatch();

} catch(BatchUpdateException b) {System.err.println("Update counts of successful commands: ");int [] updateCounts = b.getUpdateCounts();for (int i = 0; i < updateCounts.length; i ++) {

System.err.print(updateCounts[i] + " ");}System.err.println("");

}

Page 172: Adv Java

If a printout was generated and looked similar to the following, the first two commands succeeded and the third one failed.

Update counts of successful commands:1 1

JDBC drivers are not required to support batch updates, so a particular driver might not implement the methods addBatch, clearBatch, and executeBatch. Normally a programmer knows whether a driver that he/she is working with supports batch updates, but if an application wants to check, it can call the DatabaseMetaData method supportsBatchUpdates to find out. In the following code fragment, a batch update is used only if the driver supports batch updates; otherwise, each update is sent as a separate statement. The connection's auto-commit mode is disabled so that in either case, all the updates are included in one transaction.

con.setAutoCommit(false); if(dbmd.supportsBatchUpdates) {

stmt.addBatch("INSERT INTO . . .");stmt.addBatch("DELETE . . .");stmt.addBatch("INSERT INTO . . .");. . .stmt.executeBatch();

} else {System.err.print("Driver does not support batch updates; ");System.err.println("sending updates in separate statements.");stmt.executeUpdate("INSERT INTO . . .");stmt.executeUpdate("DELETE . . .");stmt.executeUpdate("INSERT INTO . . .");. . .

con.commit();


Recommended