Introduction To Javascript: Unit-2 Syllabus
Introduction To Javascript: Unit-2 Syllabus
Unit-2 syllabus
• PART-1
• Java Script: An introduction to JavaScript–JavaScript
• DOM Model-Date and Objects,- Regular Expressions- Exception
Handling-Validation-Built-in objects-Event Handling- DHTML with
JavaScript.
• Servlets: Java Servlet Architecture- Servlet Life Cycle- Form GET and
POST actions- Session Handling- Understanding Cookies.
• PART-2
• Installing and Configuring Apache Tomcat Web Server;- DATABASE
CONNECTIVITY: JDBC perspectives, JDBC program example
• JSP: Understanding Java Server Pages-JSP Standard Tag Library(JSTL)-
Creating HTML forms by embedding JSP code.
JAVA SCRIPT
Introduction
<html>
<body>
<script type="text/javascript">
document.write("Hello World!")
</script>
</body>
</html>
• Inline JavaScript
• When java script was written within the html
element using attributes related to events of
the element then it is called as inline java
script.
• Example of Inline JavaScript
• Example How to use JavaScript
• <html> <form> <input type="button"
value="Click" onclick="alert('Button
Clicked')"/> </form> </html>
• Output:
Click
Internal JavaScript
• When java script was written within the section using element then it is
called as internal java script.
• Example of Internal JavaScript
• <html>
• <head>
• <script>
• function msg()
• { alert("Welcome in JavaScript"); }
• </script>
• </head>
• <form>
• <input type="button" value="Click" onclick="msg()"/>
• </form>
• </html>
• Output: click
External JavaScript
<script type="text/javascript">
<!–
document.writeln("Hello, WWW");
// -->
</script>
<noscript>
Your browser does not support JavaScript.
</noscript>
alert(), confirm(), and prompt()
<script type="text/javascript">
alert("This is an Alert method");
confirm("Are you OK?");
prompt("What is your name?");
prompt("How old are you?","20");
</script>
alert() and confirm()
alert("Text to be displayed");
• Display a message in a dialog box.
• The dialog box will block the browser.
• Contains only 'A' – 'Z', 'a' – 'z', '0' – '9', '_', '$'
• First character cannot be a digit
• Case-sensitive
• Cannot be reserved words or keywords
Variable and Variable Declaration
<head><script type="text/javascript">
// We are in the default scope – the "window" object.
x = 3; // same as "window.x = 3"
var y = 4; // same as "y = 4" or "window.y = 4"
</script></head>
• Post/pre increment/decrement
– ++, --
• Comparison operators
– ==, !=, >, >=, <, <=
– ===, !== (Strictly equals and strictly not equals)
• i.e., Type and value of operand must match / must not
match
== vs ===
// Type conversion is performed before comparison
var v1 = ("5" == 5); // true
• || – Logical OR
– OP1 || OP2
– If OP1 is true, expression evaluates to the value of OP1.
Otherwise the expression evaluates to the value of OP2.
var tmp1 = null && 1000; // tmp1 is null
• Assignment operators
– =, +=, -=, *=, /=, %=
• Bitwise operators
– &, |, ^, >>, <<, >>>
Conditional Statements
• “if” statement
• “if … else” statement
• "? :" ternary conditional statement
• “switch” statement
if (condition)
{
code to be executed if condition is true
}
else
{
code to be executed if condition is not true
}
Conditional Statements Examples
<script>
x=3
if(x<0)
{
alert (“negatif”)
}
else
{
alert (“pozitif”)
}
</script>
Conditional Statements Examples - 2
<script>
c=confirm(“Kitap Okuyor musunuz?”)
if(c)
{
alert (“tebrikler walla”)
}
else
{
alert (“ayıp ettiniz ama”)
}
</script>
Conditional Statements Examples - 3
<script>
p=prompt("Ankara'nın plaka numarası nedir?", " ")
if(p=="06")
{
alert("Doğru")
}
else
{
alert("Yanlış")
}
</script>
Built-In Functions
• eval(expr)
– evaluates an expression or statement
• eval("3 + 4"); // Returns 7 (Number)
• eval("alert('Hello')"); // Calls the function alert('Hello')
• isFinite(x)
– Determines if a number is finite
• isNaN(x)
– Determines whether a value is “Not a Number”
Built-In Functions
• parseInt(s)
• parseInt(s, radix)
– Converts string literals to integers
– Parses up to any character that is not part of a valid integer
• parseInt("3 chances") // returns 3
• parseInt(" 5 alive") // returns 5
• parseInt("How are you") // returns NaN
• parseInt("17", 8) // returns 15
• parseFloat(s)
– Finds a floating-point value at the beginning of a string.
• parseFloat("3e-1 xyz") // returns 0.3
• parseFloat("13.5 abc") // returns 13.5
Events
• An event occurs as a result of some activity
– e.g.:
• A user clicks on a link in a page
• Page finished loaded
• Mouse cursor enter an area
• A preset amount of time elapses
• A form is being submitted
Event Handlers
• Event Handler – a segment of codes (usually a
function) to be executed when an event occurs
• When the mouse cursor is over the link, the browser displays the text "CUHK
Home" instead of the URL.
• The "return true;" of onMouseOver forces browser not to display the URL.
• window.status and window.defaultStatus are disabled in Firefox.
onSubmit Event Handler Example
<html><head>
<title>onSubmit Event Handler Example</title>
<script type="text/javascript">
function validate() {
// If everything is ok, return true
// Otherwise return false
}
</script>
</head>
<body>
<form action="MessageBoard" method="POST"
onSubmit="return validate();"
>
…
</form></body></html>
• See online references for complete list of available methods in these objects:
http://javascript-reference.info/
String Object (Some useful methods)
• length
–A string property that tells the number of character in the string
• charAt(idx)
–Returns the character at location "idx"
• toUpperCase(), toLowerCase()
–Returns the same string with all uppercase/lowercase letters
• substring(beginIdx)
–Returns a substring started at location "beginIdx"
• substring(beginIdx, endIdx)
–Returns a substring started at "beginIdx" until "endIdx" (but
not including "endIdx"
• indexOf(str)
–Returns the position where "str" first occurs in the string
Error and Exception Handling in JavaScript
• Javascript makes no distinction between Error
and Exception (Unlike Java)
• Handling Exceptions
– The onError event handler
• A method associated with the window object.
• It is called whenever an exception occurs
– The try … catch … finally block
• Similar to Java try … catch … finally block
• For handling exceptions in a code segment
– Use throw statement to throw an exception
• You can throw value of any type
– The Error object
• Default object for representing an exception
• Each Error object has a name and message properties
How to use “onError” event handler?
<html>
<head>
<title>onerror event handler example</title>
<script type="text/javascript">
function errorHandler(){
alert("Error Ourred!");
}
// JavaScript is casesensitive
// Don't write onerror!
window.onError = errorHandler;
</script>
</head>
<body>
<script type="text/javascript">
document.write("Hello there;
</script>
</body>
</html>
try … catch … finally
try {
// Contains normal codes that might throw an exception.
} catch ( errorVariable ) {
// Codes here get executed if an exception is thrown
// in the try block.
} finally {
// Executed after the catch or try block finish
} catch( errVar ) {
document.write("Exception caught<br>");
// errVar is an Error object
// All Error objects have a name and message properties
document.write("Error name: " + errVar.name + "<br>");
document.write("Error message: " + errVar.message +
"<br>");
} finally {
document.write("Finally block reached!");
}
</script>
Throwing Exception
<script type="text/javascript">
try{
var num = prompt("Enter a number (1-2):", "1");
// You can throw exception of any type
if (num == "1")
throw "Some Error Message";
else
if (num == "2")
throw 123;
else
throw new Error ("Invalid input");
} catch( err ) {
alert(typeof(errMsg) + "\n" + err);
// instanceof operator checks if err is an Error object
if (err instanceof Error)
alert("Error Message: " + err.message);
}
</script>
Document Object Model (DOM)
• When a web page is loaded, the browser
creates a Document Object Model of the page.
• Representation of the current web page as a
tree of Javascript objects
• allows you to view/modify page elements in
script code after page has loaded
• client side = highly responsive interactions
• browser-independent
• allows progressive enhancement.
• With the object model, JavaScript gets all the power it
needs to create dynamic HTML:
• JavaScript can change all the HTML elements in the page
• JavaScript can change all the HTML attributes in the
page
• JavaScript can change all the CSS styles in the page
• JavaScript can remove existing HTML elements and
attributes
• JavaScript can add new HTML elements and attributes
• JavaScript can react to all existing HTML events in the
page
• JavaScript can create new HTML events in the page
What is the DOM?
• ObjectProperties
1.car.name = Fiat 2.car.model = 500
3.car.weight = 850kg 4.car.color = white
• Methods
1.car.start() 2.car.drive() 3.car.brake() 4.car.stop()
• All cars have the same properties, but the
property values differ from car to car.
• All cars have the same methods, but the
methods are performed at different times.
• JavaScript Objects
• You have already learned that JavaScript
variables are containers for data values.
• This code assigns a simple value (Fiat) to
a variable named car:
• <!DOCTYPE html>
• <html>
• <body>
• <p>Creating a JavaScript Variable.</p>
• <p id="demo"></p>
• <script>
• var car = "Fiat";
• document.getElementById("demo").innerHTML =
car;
• </script>
• </body>
• </html>
• Objects are variables too. But objects can contain many values.
• This code assigns many values (Fiat, 500, white) to a variable named car:
• <!DOCTYPE html>
• <html>
• <body>
• <p>Creating a JavaScript Object.</p>
• <p id="demo"></p>
• <script>
• var car = {type:"Fiat", model:"500", color:"white"};
• document.getElementById("demo").innerHTML = car.type;
• </script>
• </body>
• </html>
• <p id="demo"></p>
• <script>
• var person = {
• firstName: "John",
• lastName : "Doe",
• id : 5566
• };
• document.getElementById("demo").innerHTML =
• person.firstName + " " + person.lastName;
• </script>
• </body>
• </html>
• <!DOCTYPE html>
• <html>
• <body>
• <p>
• There are two different ways to access an object property:
• </p>
• <p>You can use person.property or person["property"].</p>
• <p id="demo"></p>
• <script>
• var person = {
• firstName: "John",
• lastName : "Doe",
• id : 5566
• };
• document.getElementById("demo").innerHTML =
• person["firstName"] + " " + person["lastName"];
• </script>
• </body>
• </html>
Accessing Object Methods
• <p id="demo"></p>
• <script>
• var person = {
• firstName: "John",
• lastName : "Doe",
• id : 5566,
• fullName : function() {
• return this.firstName + " " + this.lastName;
• }
• };
• document.getElementById("demo").innerHTML = person.fullName();
• </script>
• </body>
• </html>
The Document Object
• document.anchors[n-1];
• Links
Another array holding all links in the order in which they were appeared on
the Webpage
• Forms
Another array, this one contains all of the HTML forms. By combining this
array with the individual form objects each form item can be accessed.
The Window Object
• Properties:
• toolbar = [1|0] location= [1|0] menubar = [1|0] scrollbars = [1|0]
status = [1|0] resizable = [1|0]
• where as 1 means on and 0 means off
• height=pixels, width=pixels : These properties can be used to set
the window size.
• The following code shows how to open a new window
• newWin =
open(“first.html”,”newWin”,”status=0,toolbar=0,width=100,height=
100”);
• Window object supports three types of message
boxes.
• Alert box Confirm box Prompt box
• Alert box is used to display warning/error
messages to user. It displays a text string with OK
button.
• Syntax: window. Alert (“Message”);
• Confirm Box is useful when submitting form
data. This displays a window containing
message with two buttons: OK and Cancel.
Selecting Cancel will abort the any pending
action, while OK will let the action proceed.
• Syntax
• window.confirm(“String”);
• Prompt box used for accepting data from user
through keyboard. This displays simple window that
contains a prompt and a text field in which user can
enter data. This method has two parameters: a
text string to be used as a prompt and a string to
use as the default value. If you don‟t want to
display a default then simply use an empty string.
Syntax
• Variable=window.prompt(“string”,”default value”);
The Form Object
• This object is used for obtaining the date and time. In JavaScript,
dates and times represent in milliseconds since 1st January 1970
UTC. JavaScript supports two time zones: UTC and local. UTC is
Universal Time, also known as Greenwich Mean Time(GMT),
which is standard time throughout the world. Local time is the
time on your System. A JavaScript Date represents date from
-1,000,000,000 to -1,000,000,000 days relative to 01/01/1970.
• Date Object Constructors:
• new Date(); Constructs an empty date object.
• new Date(“String”); Creates a Date object based upon the
contents of a text string.
• new Date(year, month, day[,hour, minute, second] ); Creates a
Date object based upon the numerical values for the year, month
and day.
Displaying Arrays
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars[0];
</script>
</body>
</html> 85
Creating an Array Cont..
Using an array literal is the easiest way to create a JavaScript Array.
Syntax:
var array-name = [item1, item2, ...];
Using the JavaScript Keyword new
The following example also creates an Array, and assigns values to it:
var cars = new Array("Saab", "Volvo", "BMW");
Access the Elements of an Array
You refer to an array element by referring to the index number.
var name = cars[0];
This statement modifies the first element in cars:
cars[0] = "Opel";
Can Have Different Objects in One Array
• JavaScript variables can be objects. Arrays are special kinds
of objects.
• Because of this, you can have variables of different types in
the same Array.
Example:
myArray[0] = Date.now;
myArray[1] = myFunction;
myArray[2] = myCars; 86
Cont..
Arrays are Objects
• Arrays are a special type of objects. The typeof operator in
JavaScript returns "object" for arrays.
• But, JavaScript arrays are best described as arrays.
Arrays use numbers to access its "elements". In this example,
person[0] returns John:
Array: var person = ["John", "Doe", 46];
Objects use names to access its "members". In this example,
person.firstName returns John:
Object: var person = {firstName:"John", lastName:"Doe“,
age:46};
Array Properties and Methods
The real strength of JavaScript arrays are the built-in array
properties and methods:
Examples
var x = cars.length; // The length property returns the number
of elements in cars
var y = cars.sort(); // The sort() method sort cars in
alphabetical order
87
Cont..
Note:
var points = new Array(); // Bad
var points = []; // Good
88
Array Object Methods Cont..
Method Description
concat() Joins two or more arrays, and returns a copy of the joined arrays
indexOf() Search the array for an element and returns its position
join() Joins all elements of an array into a string
Search the array for an element, starting at the end, and returns
lastIndexOf()
its position
pop() Removes the last element of an array, and returns that element
Adds new elements to the end of an array, and returns the new
push()
length
reverse() Reverses the order of the elements in an array
shift() Removes the first element of an array, and returns that element
arr.length;
• Finding element's index in the array:
arr.indexOf(1);
92
JavaScript Regular Expressions
• A regular expression is a sequence of characters that forms
a search pattern.
• The search pattern can be used for text search and text
replace operations.
Syntax
/pattern/modifiers;
Example:
var patt = /w3schools/I
93
Cont..
Using String Methods
In JavaScript, regular expressions are often used with the
two string methods: search() and replace().
Quantifiers define quantities:
Quantifier Description
n+ Matches any string that contains at least one n
n* Matches any string that contains zero or more
occurrences of n
n? Matches any string that contains zero or one Cont..
occurrences of n 97
Cont..
Using the RegExp Object
• In JavaScript, the RegExp object is a regular expression object
with predefined properties and methods.
Example
var patt = /e/;
patt.test("The best things in life are free!");
(or)
/e/.test("The best things in life are free!")
Since there is an "e" in the string, the output of the code above will
be: true
98
constructor
try……..
Example: try
{
statement one
statement two
statement three
}
catch
Example:
catch exception
{
handle the exception }
115
The concept of try…catch statement
<html>
<head>
<script type="text/javascript">
try
{
document.write(junkVariable)
}
catch(err)
{
document.write(err.message + "<br/>")
}
</script>
</head>
<body>
</body>
</html>
• The output of the above program is
‘junkVariable’ is undefined
• In the above program, the variable
junkVariableis undefined and the usage of this
in try block gives an error. The control is
transferred to the catch block with this error
and this error message is printed in the catch
block.
throw in JavaScript:
var x=f1.t1.value;
var y=f1.t2.value;
var re=/\d|\W|_/g;
if(x==''||y=='')
window.alert("Enter both user id and password");
else if(x.length<6||y.length<6)
window.alert("both user id and password should greater than or equal to 6");
else if((re.test(x)))
window.alert("user name show3uld be alphabets");
else
window.alert("welcome"+" Mr."+x);
}
</script>
</head>
<body bgcolor="green">
<form name="f1">
<center>
User Name<input type="text" name="t1"><br><br>
Password <input type="password" name="t2"><br><br>
<input type="submit" value="submit" onClick=validate()>
<input type="reset" value="reset">
</center>
</form>
</body>
</html>
DYNAMIC HTML
• DHTML is combination of HTML, CSS and
JavaScript. It gives pleasant appearance to web
page.
• Difference between HTML and DHTML
HTML DHTML
HTML is used to create static web pages. DHTML is used to create dynamic web pages.
Creation of html web pages is simplest but less Creation of DHTML is complex but more
interactive. interactive.
Dynamic HTML, or DHTML, is for a collection of
technologies used together to create
interactive and animated by using a combination of a
static markup language (such as HTML), a client-
side scripting language (such as JavaScript), a
presentation definition language (such as CSS),
and the Document Object Model.
• Uses
• DHTML allows authors to add effects to their
pages that are otherwise difficult to achieve.
• For example, DHTML allows the page author to:
• Animate text and images in their document,
independently moving each element from any
starting point to any ending point, following a
predetermined path or one chosen by the user.
• · Embed a ticker that automatically refreshes its
content with the latest news, stock quotes, or
other data.
• · Use a form to capture user input, and then
process and respond to that data without having
to send data back to the server.
• · Include rollover buttons or drop-down menus.
• DHTML FORMS
• Forms are key components of all Web-based
applications. But important as they are, Web
developers often present users with forms that are
difficult to use.
• There are three common problems:
• Forms can be too long. A seemingly endless list of
questions is to make sure the user click the back
button or jump to another site.
• In many situations a specific user will need to fill out
only some of the form elements. If you present
needless questions to a user, you’ll add clutter to your
page and encourage the user to go elsewhere.
• Form entries often need to conform to certain formats
and instructions. Adding this information to a Web
page can make for a cluttered and unappealing screen.
Summary of the unit:
1.DOM
2.Ojects in java script
3.Arrays concept
4.RegEx
5.Exception Handling-try,catch and throw
6.DHTML-HTML+CSS+JAVASCRIPT
Servlet
Servlet technology is used to create web
application (resides at server side and
generates dynamic web page).
• Servlet is a java based server side web technology
allows us to develop dynamic web component having
ability to develop dynamic web pages.
• Servlet is a JEE module based technology executes at
server side having capabilty to extend functionality to
web server,application server.
• Servlet is a JEE module web technology(server side)
that allows to develop single instance multiple thread
based server based technology web component.
• Servlet is JEE module web technology given set of
rules and guidelines for vendor companies to develop
servlet container & given application for programmers
to develop server side web components.
• Servlet technology is robust and scalable
because of java language. Before Servlet, CGI
(Common Gateway Interface) scripting language
was popular as a server-side programming
language. But there was many disadvantages of
this technology. We have discussed these
disadvantages below.
• There are many interfaces and classes in the
servlet API such as Servlet, GenericServlet,
HttpServlet, ServletRequest, ServletResponse
etc.
What is a Servlet?
public void init(ServletConfig initializes the servlet. It is the life cycle method of servlet
config) and invoked by the web container only once.
public void destroy() It is invoked only once and indicates that servlet is being
destroyed.
• HTTP is a stateless protocol.
• In other words, the current request does not know what
has been done in the previous requests.
• This creates a problem for applications that runs over
many requests, such as online shopping (or shopping cart).
You need to maintain a so-called session to pass data
among the multiple requests.
• You can maintain a session via one of these three
approaches:
• Cookie: A cookie is a small text file that is stored in the
client's machine, which will be send to the server on each
request. You can put your session data inside the cookie.
The biggest problem in using cookie is clients may disable
the cookie.
• URL Rewriting: Passes data by appending a
short text string at the end of every URL,
e.g., http://host/path/file.html;jsessionid=123
456. You need to rewrite all the URLs (e.g., the
"action" attribute of <form>) to include the
session data.
• Hidden field in an HTML form: pass data by
using hidden field tag (<input type="hidden"
name="session" value="...." />). Again, you
need to include the hidden field in all the
pages.
Session Tracking in Servlets
Method Description
<form action="servlet1">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
3)URL Rewriting
• Java JDBC is a java API to connect and execute query with the
database. JDBC API uses jdbc drivers to connect with the
database.
• Why use JDBC?
• What is API ?
• API (Application programming interface) is a document that
contains description of all the features of a product or software.
It represents classes and interfaces that software programs can
follow to communicate with each other. An API can be created
for applications, libraries, operating systems, etc
Introduction
JDBC stands for Java Database Connectivity, which is a standard
Java API for database-independent connectivity between the Java
programming language and a wide range of databases.
The JDBC library includes APIs for each of the tasks commonly
associated with database usage:
• Making a connection to a database
• Creating SQL or MySQL statements
• Executing that SQL or MySQL queries in the database
• Viewing & Modifying the resulting records
Fundamentally, JDBC is a specification that provides a complete
set of interfaces that allows for portable access to an underlying
database. Java can be used to write different types of
executables, such as: Java Applications
Java Applets
Java Servlets
Java Server Pages (JSPs)
Enterprise JavaBeans (EJBs) 207
• All of these different executables are able to use a JDBC driver
to access a database and take advantage of the stored data.
JDBC Architecture
208
Cont..
Following is the architectural diagram, which shows the location
of the driver manager with respect to the JDBC drivers and the
Java application:
209
Cont..
211
5 Steps to connect to the database in java
223
Cont..
JDBC Drivers Types
• When Java first came out, this was a useful driver because
most databases only supported ODBC access but now this type
of driver is recommended only for experimental use or when no
other alternative is available.
JDBC JDBC
ODBC ODBC ODBC
API API
Bridge Layer
226
Cont..
Type 2: JDBC-Native API
227
Cont..
228
Java Data
Application Source
JDBC Vendor
JDBC
API Specific
Driver
API
229
Cont..
Type 3: JDBC-Part Java
• In a Type 3 driver, a three-tier approach is used to accessing
databases. The JDBC clients use standard network sockets to
communicate with a middleware application server. The socket
information is then translated by the middleware application
server into the call format required by the DBMS, and
forwarded to the database server.
231
Java Data
Application Source
232
• What does IDS Server do?
• IDS Server is an internet database access server (or
middleware) that allows you to create Web applications that
can interact with your backend DBMS. IDS Server offers two
ways of doing this:
(b) IDS Server includes IDS JDBC Driver, a Type-3 JDBC driver
that will enable you to write and deploy Java applets and
programs using the JDBC API to perform database operations.
Cont..
Type 4: 100% pure Java
234
Cont..
235
Java Data
Application Source
JDBC JDBC
API Driver
236
Cont..
Which Driver should be used?
• If you are accessing one type of database, such as Oracle,
Sybase, or IBM, the preferred driver type is 4.
237
Connection:
• The connection to the database is established by using one of three
getConnection()methods of the DriverManager object. The getConnection()
method requests access to the database from the DBMS. It is up to the DBMS
to grant or reject access. Aconnection object is returned by the getConnection()
method if access is granted, otherwise the getConnection() method throws an
SQLException.
• Sometimes the DBMS grants access to a database to anyone. In this case, the
J2ME application uses the getConnection(String url) method. One parameter is
passed to the method because the DBMS only needs the database identified.
This is shown in Listing 10-5.
• String url = "jdbc:odbc:CustomerInformation";
• Statement DataRequest;
• Connection Db;
• try {
• Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver");
• Db = DriverManager.getConnection(url);
• }
• catch (ClassNotFoundException error) {
• System.err.println("Unable to load the JDBC/ODBC
bridge." +
• error);
• System.exit(1);
• }
• catch (SQLException error) {
• System.err.println("Cannot connect to the database." +
error);
• System.exit(2);
• }
• Sometimes the DBMS grants access to a database to anyone. In this case, the
J2ME application uses the getConnection(String url) method. One parameter is
passed to the method because the DBMS only needs the database identified. This
is shown in Listing 10-5.
• String url = "jdbc:odbc:CustomerInformation";
• Statement DataRequest;
• Connection Db;
• try {
• Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver");
• Db = DriverManager.getConnection(url);
• }
• catch (ClassNotFoundException error) {
• System.err.println("Unable to load the JDBC/ODBC bridge." +
• error);
• System.exit(1);
• }
• catch (SQLException error) {
• System.err.println("Cannot connect to the database." + error);
• System.exit(2);
• }
• TIME OUT
• multiple applications might attempt to access a database simultaneously. The
DBMS may not respond quickly for a number of reasons, one of which might
be that database connections are not available. Rather than wait for a delayed
response from the DBMS, the J2ME application can set a timeout period after
which the Driver Manager will cease trying to connect to the database.
• The public static void DriverManager.setLoginTimeout(int seconds) method
can be used by the J2ME application to establish the maximum time the
DriverManager waits for a response from a DBMS before timing out. Likewise,
the public static int DriverManager.getLoginTimeout() method is used to
retrieve from the DriverManager the maximum time the DriverManager is set
to wait until it times out. The DriverManager.getLoginTimeout() returns an int
that represents seconds.
Connection Pool
• A connection pool is a collection of database connections that are
opened once and loaded into memory so these connections can be
reused without having to reconnect to the DBMS.
• Clients use the Data Source interface to interact with the
• connection pool.
• The connection pool itself is implemented by the application server
and other J2EE-specific technologies, which hide details on how the
connection pool
• . There are two types of connections made to the database. The first
is the physical connection, which is made by the application server
using Pooled Connection objects.
• Pooled Connection objects are cached and reused. The other type of
connection is the logical connection.
• Context ctext = new InitialContext();
• DataSource pool = (DataSource)
ctext.lookup("java:comp/env/jdbc/pool");
• Connection db = pool.getConnection();
• // Place code to interact with the database
here
• db.close();
• Statement Objects
• Once a connection to the database is opened, the J2ME
application creates and sends a
• query to access data contained in the database. The
query is written using SQL.
• One of three types of Statement objects is used to
execute the query.
• These objects are Statement, which executes a query
immediately;
• Prepared Statement, which is used to execute a
compiled query; and Callable Statement, which is used
to execute store procedures.
The Statement Object
• An SQL query must be compiled before the DBMS processes the query.
Compiling occurs after one of the Statement object’s execution methods is
called. Compiling a query is an overhead that is acceptable if the query is called
once. However, the compiling process can become an expensive overhead if the
query is executed several times by the same instance of the J2ME application
during the same session.
• An SQL query can be precompiled and executed by using the
PreparedStatement object. The preparedStatement() method of the Connection
object is called to return the PreparedStatement object. The
preparedStatement() method is passed the query that is then precompiled. The
setXXX() method of the PreparedStatement object is used to replace the
question mark with the value passed to the setXXX() method. There are a
• number of setXXX() methods available in the PreparedStatement object, each
of which specifies the data type of the value that is being passed to the setXXX()
method
• String url = "jdbc:odbc:CustomerInformation";
• String userID = "jim";
• String password = "keogh";
• ResultSet Results;
• Connection Db;
• try {
• Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver");
• Db = DriverManager.getConnection(url,userID,password);
• }
• catch (ClassNotFoundException error) {
• System.err.println(
• "Unable to load the JDBC/ODBC bridge." + error);
• System.exit(1);
• }
catch (SQLException error) {
System.err.println("Cannot connect to the
database." + error);
System.exit(2);
}
try {
String query = "SELECT * FROM Customers WHERE
CustNumber = ?";
PreparedStatement pstatement =
Db.preparedStatement(query);
pstatement.setString(1, "123");
Results = pstatement.executeQuery ();
//Place code here to interact with the ResultSet
• pstatement.close();
• }
• catch ( SQLException error ){
• System.err.println("SQL error." + error);
• System.exit(3);
• }
• Db.close();
Callable Statement
• The Callable Statement is used to call a stored
procedure from within a J2ME object. A
• stored procedure is a block of code and is
identified by a unique name.
• The Callable Statement object uses three
types of parameters when calling a stored
procedure.
• These parameters are IN, OUT, and INOUT.
• The IN parameter contains any data that needs to be
passed to the stored procedure and whose value is
assigned using the setXXX() method.
• The OUT parameter contains the value returned by
the stored procedures, if any. The OUT parameter
must be registered using the registerOutParameter()
method .
• J2ME application using the getXXX() method. The
INOUT parameter is a single parameter used for
both passing information to the stored procedure
and retrieving information from a stored procedure
using the techniques described in the previous two
paragraphs.
ResultSet
• A query is used to update,delete, and retrieve information stored in
a database.
• The executeQuery() method is used to send the query to the DBMS
for processing and returns a ResultSet object that
• contains data requested by the query.
• The ResultSet object contains methods that are used to copy data
from the ResultSet into a Java collection of objects or variable(s) for
further processing.
• Data in a ResultSet object is logically organized into a virtual table
consisting of rows and columns.
• In addition to data, the ResultSet object also contains metadata,
such as column names, column size, and column data type.
The ResultSet uses a virtual cursor to point to a row of the virtual table.
A J2ME application must move the virtual cursor to each row, then use other methods of the
ResultSet object to interact with the data stored in columns of that row.
The virtual cursor is positioned above the first row of data when the ResultSet is returned by
the executeQuery() method.
This means that the virtual cursor must be moved to the first row using the next() method.
The next() method returns a boolean true if the row contains data, otherwise a boolean false
is returned, indicating that no more rows exist in the ResultSet.
Columns appear in the ResultSet in the order in which column names appeared in
the SELECT statement in the query.
Six methods of the ResultSet object are used to position the virtual cursor, in addition to the
next() method discussed in the previous section.
The first() method moves the virtual cursor to the first row in the ResultSet. Likewise, the last()
method positions the virtual cursor at the last row in the ResultSet.
The previous() method moves the virtual cursor to the previous row.
The absolute() method positions the virtual cursor at the row number specified by the integer
passed as a parameter to the absolute() method.
The relative() method moves the virtual cursor the specified number of rows
contained in the parameter.
For example, a –4 moves the virtual cursor back four rows from the current row.
Likewise, a 5 moves the virtual cursor forward five rows from the current row.
And the getRow() method returns an integer that represents the number of the
current row in the ResultSet.
The Statement object that is created using the createStatement() of the Connection
object must be set up to handle a scrollable ResultSet by passing the
createStatement() method one of three constants.
File: index.html
<html>
<body>
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
</body>
</html>
File: welcome.jsp
<html>
<body>
<%
String name=request.getParameter("uname");
out.print("welcome "+name);
%>
</form>
</body>
</html>
JSP expression tag
The jsp scriptlet tag can only The jsp declaration tag can declare
declare variables not methods. variables as well as methods.
JSP Servlet No
• In translation phase JSP Current?
Parse JSP
Yes
page is compiled into a JSP Servlet Generate JSP
Loaded?
servlet Yes No
Servlet Source
processed
Send
Response
Scripting Elements
Types
<%@
page language=“java”
buffer=“10kb”
autoflush=“true”
errorPage=“/error.jsp”
import=“java.util.*, javax.sql.RowSet”
%>
Include Directive
Basics
• Syntax:
<jsp:useBean id=“name”
scope=“page | request | session | application”
class=“className” type=“typeName” |
bean=“beanName” type=“typeName” |
type=“typeName” />
– At least one of the type and class attributes must be present
– We can’t specify values for bith the class and bean name.
• Example
<jsp:useBean id=“myName” scope=“request” class=“java.lang.String”>
<% firstName=“Sanjay”; %>
</jsp:useBean>
JSP Actions
get/setProperty
• getProperty is used in conjunction with useBean to get property values
of the bean defined by the useBean action
• Example (getProperty)
– <jsp:getProperty name=“myBean” property=“firstName” />
– Name corresponds to the id value in the useBean
– Property refers to the name of the bean property
Header.jsp
Gets input to compute loan from user index.jsp Footer.jsp