Unit 5
Unit 5
AJAX
AJAX is an acronym for Asynchronous JavaScript and XML. AJAX is a new technique for
creating better, faster and interactive web applications with the help of JavaScript, DOM, XML,
HTML, CSS etc. AJAX allows you to send and receive data asynchronously without reloading the
entire web page. So it is fast.
AJAX allows you to send only important information to the server not the entire page. So
only valuable data from the client side is routed to the server side. It makes your application
interactive and faster.
Ajax is the most viable Rich Internet Application(RIA) technique so far.
Where it is used?
There are too many web applications running on the web that are using AJAX Technology.
Some
are
: 1. Gmail
2. Face book
3. Twitter
4. Google maps
5. YouTube etc.,
Synchronous Vs. Asynchronous Application
Before understanding AJAX, let’s understand classic web application model and AJAX Web
application model.
Synchronous (Classic Web-Application Model)
A synchronous request blocks the client until operation completes i.e. browser is not
unresponsive. In such case, JavaScript Engine of the browser is blocked.
As you can see in the above image, full page is refreshed at request time and user is
blocked until request completes.
AJAX Components
AJAX is not a technology but group of inter-related technologies. AJAX Technologies
includes:
HTML/XHTML and CSS
DOM
XML or JSON(JavaScript Object Notation)
XMLHttpRequest Object
JavaScript
DOM
It is used for dynamic display and interaction with data.
XMLHttpRequest Object
For asynchronous communication between client and server.
JavaScript
It is used to bring above technologies together. Independently, it is used mainly for client-
side validation.
Understanding XMLHttpRequest
It is the heart of AJAX technique. An object of XMLHttpRequest is used for asynchronous
communication between client and server.it provides a set of useful methods and properties that are
used to send HTTP Request to and retrieve data from the web server. It performs following
operations:
1. Sends data from the client in the background
2. Receives the data from the server
3. Updates the webpage without reloading it.
1. User sends a request from the UI and a javascript call goes to XMLHttpRequest object.
2. HTTP Request is sent to the server by XMLHttpRequest object.
3. Server interacts with the database using JSP, PHP, Servlet, ASP.net etc.
4. Data is retrieved.
5. Server sends XML data or JSON data to the XMLHttpRequest callback function.
6. HTML and CSS data is displayed on the browser.
UNIT-III AJAX
Web services receive information from clients as messages, containing instructions about what
client wants, similar to method calls with parameters. These message delivered by web services are
encoded using XML.XML enabled web services are interoperable with other web services.
If we are creating web service that offered latest stock quotes, we need to create WSDL file
on server that describes service. Client obtains copy of this file, understand contract, create SOAP
request based on contract and dispatch request to server using HTTP post. Server validates the
request, if found valid executes request. The result which is latest stock price for requested symbol is
then returned to client as SOAP response.
Typical SOAP message is shown below:
<IVORY:Envelope xmlns:IVORY=”http://schemas.xmlsoap.org/soap/envelope”
IVORY:encodingStyle=”http://schemas.xmlsoap.org/soap/encoding
”>
<IVORY:Body>
<m:GetLastTradePrice xmlns:m=”Some-URI”>
<symbol>DIS</symbol>
</m:GetLastTradePrice>
</IVORY:Body>
</IVORY:Envelope>
The consumer of web service creates SOAP message as above, embeds it in HTTP POST
request and sends it to web service for processing:
<SOAP-ENV:Envelope xmlns:SOAP-
ENV=”http://schemas.xmlsoap.org/soap/envelope” SOAP-ENV:encodingStyle=”
http://schemas.xmlsoap.org/soap/encoding” />
<SOAP-ENV:Body>
<m:GetLastTradePrice xmlns:m=”Some-URI”>
<Price>34.5</Price>
</m:GetLastTradePrice>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
Interoperability:
The major goal in design of SOAP was to allow for easy creation of interoperable distributed
web services. Few details of SOAP specifications are open for interpretation; implementation may
differ across different vendors. SOAP message though it is conformant XML message, may not
strictly follow SOAP specification.
Implementations:
SOAP technology was developed by DevelopMentor, IBM, Lotus, Microsoft etc. More than
50 vendors have currently implemented SOAP. Most popular implementations are by Apache which
is open source java based implementation and by Microsoft in .NET platform. SOAP specification has
UNIT-III AJAX
been submitted to W3C, which is now working on new specifications called XMLP (XML Protocol)
SOAP Messages with Attachments (SwA)
SOAP can send message with an attachment containing of another document or image etc. On
Internet, GIF, JPEG data formats are treated as standards for image transmission. Second iteration of
SOAP specification allowed for attachments to be combined with SOAP message by using multipart
MIME structure. This multi part structure is called as SOAP Message Package. This new
specification was developed by HP and Microsoft. Sample SOAP message attachment is shown here:
MIME-Version: 1.0
Content-Type: Multipart/Related;
boundary=MIME_boundary; type=text/xml;
start=”<[email protected]>” Content-
Description: This is the optional message description.
--MIME_boundary
Content-Type: text/xml;
charset=UTF-8 Content-Transfer-
Encoding: 8bit
Content-ID: <[email protected]>
<?xmll version=‟1.0‟ ?>
<SOAP-ENV: Envelope xmlns:SOAP-ENV=”http://schemas.xmlsoap.org/soap/envelope”
<SOAP-ENV:Body>
…
<theSignedForm href=”cid:[email protected]” />
…
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
--MIME_boundary
Content-Type:
image/tiff
Content-Transfer-Encoding: binary
Content-ID: <[email protected]>
…binary TIFF image…
--MIME_boundary--
WSDL Document:
WSDL document is an XML document that contains of set of definitions. First we declare
name spaces required by schema definition:
<schema xmlns=”http://www.w3.org/2000/10/XMLSchema”
xmlns:wsdl=”http://schemas.xmlsoap.org/wsdl/”
targetNameSpace=http://schemas.xmlsoap.org/wsdl/ elementFormDefault=”qualified”>
The name attribute is optional and can serve as light weight form of documentation. The
nmtoken represents name token that are qualified strings similar to CDATA, but character usage is
limited to letters, digits, underscores, colons, periods and dashes. A targetNamespace may be
specified by providing uri. The import tag may be used to associate namespace with document
locations. Following code segment shows how declared namespace is associated with document
location specified in import statement:
<definitions name=”StockQuote”
targetNameSpace=”http://example.com/stockquote/defiinitio
ns” xmlns:tns=”http://example.com/stockquote/definitions”
xmlns:xsdl=”http://example.com/stockquote/schemas”
xmlns:soap=”http://schemas.xmlsoap.org/wsdl/soap/‟
xmlns=”http://schemas.xmlsoap.org/wsdl/”>
<import namespace=”http://example.com/stockquote/schemas”
Location=”http://example.com/stockquote/stockquote.xsd
”/>
Types Element: it provides definitions for data types used to describe how messages
will exchange data. Syntax for types element is as follows:
<wsdl:types> ?
<wsdl:documentation …/>
<xsd:schema …/>
<-- extensibility element -->
</wsdl:types>
The wsdl:documentation tag is optional as in case of definitions. The xsd type system may be
used to define types in message. WSDL allows type systems to be added via extensibility
element.
Message Element: It represents abstract definition of data begin transmitted. Syntax for
message element:
<wsdl:message name=”nktoken”> *
<wsdl;documentation …/>
<part name=”nmtoken” element=”qname”? type=”qname”? /> *
</wsdl:message>
The message name attribute is used for defining unique name for message with in
document scope. The wsdl:documentation is optional and may be used for declaring
human readable documentation. The message consists of one or more logical parts. The
part describes logical abstract content of message. Each part consists of name and optional
element and type attributes.\
Port Type Element: It defines set of abstract operations. An operation consists of both input
and output messages. The operation tag defines name of operation, input defines input for
operation and output defines output format for result. The fault element is used for describing
contents of SOAP fault details element. It specifies abstract message format for error
UNIT-III AJAX
messages that may be output as result of operation:
<wsdl:portType name=”nmtoken”>*
<wsdl:documentation …./>?
<wsdl:operation name=”nmtoken”>*
<wsdl:documentation …./>?
<wsdl:input name=”nmtoken”? message=”qname”>?
<wsdl:documentation …./>?
</wsdl:input>
<wsdl:output name=”nmtoken”? message=”qname”>?
<wsdl:documentation …./>?
</wsdl:output>
<wsdl:fault name=”nmtoken”? message=”qname”>?
<wsdl:documentation …./>?
</wsdl:fault>
</wsdl:operation>
</wsdl:portType>
Binding Element: It defines protocol to be used and specifies data format for operations and
messages defined by particular portType. The full syntax for binding is given below:
<wsdl:binding name=”nmtoken” type=”qname”> *
<wsdl:documentation …./>?
<--Extensibility element -->*
<wsdl:operation name=”nmtoken”>*
<wsdl:documentation …./>?
<--Extensibility element -->*
<wsdl:input> ?
<wsdl:documentation …./>?
<--Extensibility element -->*
</wsdl:input>
<wsdl:output> ?
<wsdl:documentation …./>?
<--Extensibility element -->*
</wsdl:output>
<wsdl:fault name=”nmtoken”> *
<wsdl:documentation …./>?
<--Extensibility element -->*
</wsdl:fault>
</wsdl:operation>
</wsdl:binding>
The operation in WSDL file can be document oriented or remote procedure call (RPC)
oriented. The style attribute of <soap:binding> element defines type of operation. If operation is
document oriented, input and output messages will consist of XML documents. If operation is
RPC oriented, input message contains operations input parameters and output message contains
result of operation.
Port Element: It defines individual end point by specifying single address for binding:
The name attribute defines unique name for port with current WSDL document. The
binding
attribute refers to binding and extensibility element is used to specify address information for port.
UNIT-III AJAX
Service Element: it aggregates set of related ports. Each port specifies address for binding:
<wsdl:service name=”nmtoken”> *
<wsdl:documentation …./>?
<wsdl:port name=”nktoken” binding=”qname”> *
<wsdl:documentation …/> ?
<--Extensibility element -->
</wsdl:port>
<--Extensibility element -->
</wsdl:service>
A business or a company can register three types of information into a UDDI registry. This
information is contained in three elements of UDDI. These three elements are:
White Pages,
Yellow Pages, and
Green Pages.
White Pages
White pages contain:
Basic information about the company and its business.
Basic contact information including business name, address, contact phone number, etc.
A Unique identifiers for the company tax IDs. This information allows others to discover
your web service based upon your business identification.
Yellow Pages
Yellow pages contain more details about the company. They include descriptions of the
kind of electronic capabilities the company can offer to anyone who wants to do business
with it.
Yellow pages uses commonly accepted industrial categorization schemes, industry codes,
product codes, business identification codes and the like to make it easier for companies to
search through the listings and find exactly what they want.
Green Pages
Green pages contains technical information about a web service. A green page allows someone to
bind to a Web service after it's been found. It includes:
The various interfaces
The URL locations
Discovery information and similar data required to find and run the Web service.
Implementation:
This is global, public registry called UDDI business registry. It is possible for individuals to
set up private UDDI registries. The implementations for creating private registries are available from
IBM, Idoox etc. Microsoft has developed UDDI SDK that allows visual basic programmer to write
program code to interact with UDDI registry. The use of SDK greatly simplifies interaction with
registry and shields programmer from local level details of XML and SOAP.
UNIT-1
Introduction to HTML
1. Create a simple HTML page which demonstrates use of three types
of lists? (Or)Explain the concept of list?
Ans.
Lists: Lists is one of the most effective ways of structuring a website or its contents.HTML
provides three types of lists, they are:
i. Ordered Lists: An ordered list has a number instead of bullet in front of each list item.
Example:
<ol type="1">
<li>Apple</li>
<li>Orange</li>
<li>Grapefruit</li>
</ol>
Example:
1. Apple
2. Orange
3. Grapefruit
ii. Unordered list: The basic unordered list has a bullet in front of each list item.
Example:
<ul type="disk">
<li>Apple</li>
<li>Orange</li>
<li>Grapefruit</li>
</ul>
1
Example:
Apple
Orange
Pear
iii. Definition list: These are different to the previous types in that they do not use list
Example:
<dl>
<dt>HTML</dt>
<dt>CSS</dt>
</dl>
<ol type="1">
<li>Apple</li>
<li>Orange</li>
<li>Grapefruit</li>
</ol>
<ul type="disc">
<li>Apple</li>
<li>Orange</li>
<li>Grapefruit</li>
</ul>
<dl>
<dt>HTML</dt>
</dl>
2
Figure 1. Example for lists
Definition:
• Cascading Style Sheets (CSS) form the presentation layer of the user interface.
– Structure (XHTML)
– Presentation (CSS)
• Tells the browser agent how the element is to be presented to the user.
CSS Syntax:
• A CSS rule has two main parts: a selector, and one or more declarations:
• The property is the style attribute you want to change. Each property has a value.
3
Styling HTML with CSS
• CSS was introduced together with HTML 4, to provide a better way to style HTML
elements.
i. Inline Styles
• An inline style can be used if a unique style is to be applied to one single occurrence
of an element.
Example:
<!DOCTYPE html>
<html>
<body style="background-color:yellow;">
</body>
</html>
Output:
An internal style sheet can be used if one single document has a unique style. Internal
styles are defined in the <head> section of an HTML page, by using the <style> tag, like
this:
Example:
<!DOCTYPE html>
<html> <head>
<style>
body {background-color:yellow;}
h1 {color:red;}
h2 {color:blue;}
4
p {color:green;}
</style></head>
<body>
</body></html>
Output:
An external style sheet is ideal when the style is applied to many pages. With an external
style sheet, you can change the look of an entire Web site by changing one file. Each page
must link to the style sheet using the <link> tag. The <link> tag goes inside the <head>
section:
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
</head>
Tag Description
resource
Advantages of CSS:
• CSS removes the presentation attributes from the structure allowing reusability, ease
of maintainability, and an interchangeable presentation layer.
– <font>
– <b>
– <i>
5
3. Write short notes on HTML hyperlinks? (Or) Discuss the
difference between relative and absolute paths in hyperlinks.
Ans.
A hyperlink (or link) is a word, group of words, or image that you can click on to
jump to another document.
When you move the cursor over a link in a Web page, the arrow will turn into a little
hand.
The most important attribute of the <a> element is the href attribute, which
indicates the link's destination.
The example below will open the linked document in a new browser window or a new
tab:
Example
W3Schools!</a>
Web site</a>
Tip: Bookmarks are not displayed in any special way. They are invisible to the reader.
6
Example
Create a link to the "Useful Tips Section" inside the same document:
Or, create a link to the "Useful Tips Section" from another page:
Example:
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<br />
<br />
</body> </html>
7
Figure 2. Example for Hyperlinks
• An HTML form can contain input elements like text fields, checkboxes, radio-buttons,
submit buttons and more.
• A form can also contain select lists, textarea, fieldset, legend, and label elements.
<form>
…..
input elements
……..
</form>
• Forms are the primary method for gathering data from site visitors
• Example:
...
</form>
Syntax:
<input type="text―
Text Fields
Defines a one-line input field that a user can enter text into:
8
Example:
<form>
First name: <input type="text" name="firstname"><br>
Last name: <input type="text" name="lastname">
</form>
Note: The form itself is not visible. Also note that the default width of a text field is 20
characters.
2. Password Field
Example:
<form>
Password: <input type="password" name="pwd">
</form>
Note: The characters in a password field are masked (shown as asterisks or circles).
3. Radio Buttons
<input type="radio"> defines a radio button. Radio buttons let a user select ONLY ONE
of a limited number of choices:
Example:
<form>
<input type="radio" name=―gender" value="male">Male<br>
<input type="radio" name=―gender" value="female">Female
</form>
4. Checkboxes
Example:
<form>
<input type="checkbox" name="vehicle" value="Bike">I have a bike<br>
<input type="checkbox" name="vehicle" value="Car">I have a car
</form>
9
5. Submit Button
A submit button is used to send form data to a server. The data is sent to the page
specified in the form's action attribute. The file defined in the action attribute usually
does something with the received input:
Example:
</form>
6. Button
Example:
<!DOCTYPE html>
<html>
<body>
<form action="">
</form> </body></html>
8. Image button – acts like submit but image is displayed and click coordinates are sent
Fieldset:
10
<input type="text" id="Name" />
</fieldset>
</form>
• Dropdown menus:
<html>
<body>
<form action="">
<select name="cars">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="fiat">Fiat</option>
<option value="audi">Audi</option>
</select>
</form>
</body>
</html>
Labels:
• Form labels are used to associate an explanatory text to a form field using the field's
ID.
Example: form.html
<fieldset><legend>Academic information</legend>
<label for="degree">Degree</label>
11
<select name="degree" id="degree">
</fieldset>
<fieldset><legend>Personal Details</legend>
Gender:
<label for="gm">Male</label>
<label for="email">Email</label>
</fieldset>
</form>
12
Output:
• Tables should not be used for layout. Use CSS floats and positioning styles
instead.
• Start and end of a table
<table>.. </table>
• Start and end of a row
<tr>...</tr>
• Start and end of a cell in a row
<td>...</td>
Example:
13
<tr><td><img src="zip.gif"></td>
Output:
Note:
14
UNIT -2
JAVA SCRIPT
1. Write a javascript logic for validating email-id of a registration
form.
Ans.
JavaScript is a scripting language. A scripting language is a lightweight programming
language.
In HTML, JavaScripts must be inserted between <script> and </script> tags. The <script>
and </script> tells where the JavaScript starts and ends.
JavaScripts can be put in the <body> and in the <head> section of an HTML page.
The following is the java script code that validates the email id of the registration form:
<html> <head>
<script language="javascript">
function validate()
{ /*E-mail validation*/
var e=f5.t3.value;
var atpos=e.indexOf("@");
var dotpos=e.lastIndexOf(".");
1
else
</script>
</head>
<body bgcolor="pink">
<form name="f5">
<fieldset>
<legend>Registration Details</legend>
<center>
<table> <tr>
</tr>
/* <tr>
</tr>
<tr>
2
<option value=9>9 </option>
<option value=10>10</option>
<option value=11>11</option>
<option value=12>12</option>
<option value=13>13</option>
<option value=14>14</option>
<option value=15>15</option>
<option value=16>16</option>
<option value=17>17</option>
<option value=18>18</option>
<option value=19>19</option>
<option value=20>20</option>
<option value=21>21</option>
<option value=22>22</option>
<option value=23>23</option>
<option value=24>24</option>
<option value=25>25</option>
<option value=26>26</option>
<option value=27>27</option>
<option value=28>28</option>
<option value=29>29</option>
<option value=30>30</option>
<option value=31>31</option>
</select>
<select name=month>
<option value=Jan>Jan</option>
<option value=Feb>Feb</option>
3
<option value=Mar>Mar</option>
<option value=Apr>Apr</option>
<option value=May>May</option>
<option value=Jun>Jun</option>
<option value=Jul>Jul</option>
<option value=Aug>Aug</option>
<option value=Sep>Sep</option>
<option value=Oct>Oct</option>
<option value=Nov>Nov</option>
<option value=Dec>Dec</option>
</select>
<select name=year>
<option value=1995>1995</option>
<option value=1996>1996</option>
<option value=1997>1997</option>
<option value=1998>1998</option>
<option value=1999>1999</option>
<option value=2000>2000</option>
<option value=2001>2001</option>
</select>
</td>
</tr> */
</table>
</center>
</fieldset></form></body></html>
4
2. Write a JavaScript code to validate user id and password input
fields with the following constraints:
Ans.
JavaScript is a scripting language. A scripting language is a lightweight programming
language.
In HTML, JavaScripts must be inserted between <script> and </script> tags. The <script>
and </script> tells where the JavaScript starts and ends.
JavaScripts can be put in the <body> and in the <head> section of an HTML page.
The following is the java script code that validates the user id and passwords of the
registration form:
<html>
<head>
<script language="javascript">
function validate()
var f=f6.t1.value;
var l=f6.t2.value;
var u=f6.t3.value;
5
var p=f6.t4.value;
var re1=/\d|\W|_/i;
var re2=/\d|\w|/;
if(f.length<3)
var x=document.getElementById("first");
else
if(re1.test(f))
var x=document.getElementById("first");
else
if(l.length<3)
var x=document.getElementById("last");
else
if(re1.test(l))
var x=document.getElementById("last");
else
6
if(re2.test(u))
var x=document.getElementById("uid");
else
if(p.length<8)
var x=document.getElementById("pswd");
else
window.alert("successfully registered");
</script>
</head>
<body bgcolor="pink">
<form name="f6">
<fieldset>
<legend>Registration Details</legend>
<center>
<table>
<tr>
</tr>
<tr>
7
<td>LastName:</td><td><input type="text" name=t2><span id="last"
style="color:red"></span></td>
</tr>
<tr>
</tr>
<tr>
</tr>
</table>
</center>
</fieldset>
</form>
</body>
</html>
Ans.
JavaScript Functions
Often, JavaScript code is written to be executed when an event occurs, like when the user
clicks a button.
Invoke a function = call upon a function (ask for the code in the function to be executed).
Function Declarations
function functionName(parameters) {
code to be executed
}
8
Declared functions are not executed immediately. They are "saved for later use", and will be
executed later, when they are invoked (called upon).
Example
function myFunction(a, b) {
return a * b;
}
Function Expressions
Example
Function arguments are the real values passed to (and received by) the function.
The code in a function is not executed when the function is defined. It is executed
when the function is invoked.
function myFunction(a, b) {
return a * b;
}
myFunction(10, 2); // myFunction(10, 2) will return 20
Ans.
JavaScript is a scripting language. A scripting language is a lightweight programming
language.
In HTML, JavaScripts must be inserted between <script> and </script> tags. The <script>
and </script> tells where the JavaScript starts and ends.
JavaScripts can be put in the <body> and in the <head> section of an HTML page.
The following is the Java Script code for matching two password input fields:
<html>
<head>
<script type="text/javascript">
function validation()
{
var c=document.f1.pass.value;
if(c=="")
{
alert("PLease enter your Password");
document.f1.pass.focus();
return false;
}
var d=document.f1.cpass.value;
if(d=="")
{
return false;
}
if(c!=d)
{
alert("Password and confirm Password Mismatched");
return false;
}
}
</script>
</head>
<body>
<form name="f1" method="post" action="">
Password: <input type="password" name="pass" />
Confirm Password: <input type="password" name="cpass" />
<button type="reset" name="reset" >Reset</button>
<buttontype="submit" name="submit" onClick=‖validation()‖>
10
Submit</button>
</form>
</body>
</html>
Ans:
• Client-side technology
• In <head> part
• In <body> part
JavaScript Syntax
Ex:- document.writeln(―hello‖);
• HTML tags can be used within the ― ― to invoke the functionality of the tag
11
• Usage: - window.prompt(―enter x‖,――);
Advantages
Disadvantages
• Security. Because the code executes on the users' computer, in some cases it can
be exploited for malicious purposes. This is one reason some people choose to
disable JavaScript.
• Reliance on End User. JavaScript is sometimes interpreted differently by different
browsers. Whereas server-side scripts will always produce the same output, client-
side scripts can be a little unpredictable.
6. JavaScript Variables
Example on Variables:
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
12
<script>
var length;
length = 6;
document.getElementById("demo").innerHTML = length;
</script>
</body>
</html>
7. String Manipulation
Method Description
charAt() Returns the character at the specified index (position)
concat() Joins two or more strings, and returns a copy of the joined strings
Returns the position of the first found occurrence of a specified value in a
indexOf()
string
lastIndexOf() Returns the position of the last found occurrence of a specified value in a
string
Searches a string for a match against a regular expression, and returns the
match()
matches
Searches a string for a value and returns a new string with the value
replace()
replaced
search() Searches a string for a value and returns the position of the match
slice() Extracts a part of a string and returns a new string
split() Splits a string into an array of substrings
Extracts a part of a string from a start position through a number of
substr()
characters
substring() Extracts a part of a string between two specified positions
toLowerCase() Converts a string to lowercase letters
toString() Returns the value of a String object
toUpperCase() Converts a string to uppercase letters
trim() Removes whitespace from both ends of a string
valueOf() Returns the primitive value of a String object
8. Arrays
Displaying Arrays
<!DOCTYPE html>
<html>
<body>
13
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = cars[0];
</script></body></html>
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
lastIndexOf() Search the array for an element, starting at the end, and returns its position
pop() Removes the last element of an array, and returns that element
push() Adds new elements to the end of an array, and returns the new length
reverse() Reverses the order of the elements in an array
shift() Removes the first element of an array, and returns that element
slice() Selects a part of an array, and returns the new array
sort() Sorts the elements of an array
splice() Adds/Removes elements from an array
toString() Converts an array to a string, and returns the result
Adds new elements to the beginning of an array, and returns the new
unshift()
length
valueOf() Returns the primitive value of an array
9. Introduction to DHTML
• Dynamic HTML (DHTML)
– Makes possible a Web page to react and change in response to the user’s
actions
• DHTML = HTML + CSS + JavaScript
14
DHTML
• HTML defines Web sites content through semantic tags (headings, paragraphs, lists,
…)
• CSS defines 'rules' or 'styles' for presenting every aspect of an HTML document
– Font (family, size, color, weight, etc.)
– Background (color, image, position, repeat)
– Position and layout (of any object on the page)
• JavaScript defines dynamic behavior
– Programming logic for interaction with the user, to handle events, etc.
Note:
Have a glance on the topics:
Objects in Javascript
15
UNIT-3
XML
1. Explain about Document Type Definition and explain about the
elements?
Ans.
1
i. DTD:
Use of DTD:
• With a DTD, each of your XML files can carry a description of its own format.
• With a DTD, independent groups of people can agree to use a standard DTD for
interchanging data.
• Your application can use a standard DTD to verify that the data you receive from
the outside world is valid.
• You can also use a DTD to verify your own data.
The Building Blocks of XML Documents are seen from a DTD point of view. All XML
documents (and HTML documents) are made up by the following building blocks:
• Elements
• Attributes
• Entities
• PCDATA
• CDATA
Elements:
In a DTD, XML elements are declared with an element declaration with the following
syntax: <!ELEMENT element-name category>
Or
<!ELEMENT element-name (element-content)>
In the above syntax, element-name is nothing but the name of the tag used and the
category field may be of among different types specified below:
a. Empty Elements
Empty elements are declared with the category keyword EMPTY
Syntax: <!ELEMENT element-name EMPTY>
b. Elements with Parsed Character Data
Elements with only parsed character data are declared with #PCDATA
inside parentheses:
Syntax: <!ELEMENT element-name (#PCDATA)>
c. Elements with any Contents
Elements declared with the category keyword ANY, can contain any
combination of parsable data
Syntax: <!ELEMENT element-name ANY>
d. Elements with Children (sequences)
Elements with one or more children are declared with the name of the
children elements inside parentheses
2
Syntax: <!ELEMENT element-name (child1)>
or
<!ELEMENT element-name (child1,child2,...)>
e. Declaring either/or Content
Example: !ELEMENT note (to,from,header,(message|body))>
f. Declaring Mixed Content
Example:<!ELEMENT note (#PCDATA|to|from|header|message)*>
Example1
XML Example:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE note SYSTEM "Note.dtd">
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
DTD Example:
<?xml version="1.0" encoding="UTF-8"?>
<!ELEMENT note (to,from,heading,body)>//since for ―note‖ there are
4 children:to, from, heading, body. Hence it is specified like this.
<!ELEMENT to (#PCDATA)>//this if for ―to‖ node and here the
category is of type ―b‖ as given above.
<!ELEMENT from (#PCDATA)>
<!ELEMENT heading (#PCDATA)>
<!ELEMENT body (#PCDATA)>
Based on the occurrence of the Element in XML, the syntax used in the DTD may
change as shown below.
Example2
XML example:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE address SYSTEM "name.dtd">
<address>
<name>
<fname>shaik</fname>
<lname>K K Baseer</lname>
</name>
3
<name>
<fname>shaik</fname>
<lname>K K Baseer-SVEC</lname>
</name>
</address>
DTD Example:
<?xml version="1.0" encoding="UTF-8"?>
<!ELEMENT address (name+)>//Since the element ―name‖ in the
above example are used twice, hence ―name+‖ is used in the category
field.
<!ELEMENT name ( fname, lname ) >//fname and lname are children
to parent element name.
<!ELEMENT fname (#PCDATA)>
<!ELEMENT lname (#PCDATA)>
Introduction to parsers
The word parser comes from compilers
In a compiler, a parser is the module that reads and interprets the programming
language.
In XML, a parser is a software component that sits between the application and
the XML files.
It reads a text-formatted XML file or stream and converts it to a document to be
manipulated by the application.
Types of parsers:
4
Ideal for browsers, editors, XSL processors.
Tree-based parsers deal generally small documents.
Tree-based parsers are generally easier to implement.
DOM is an example of tree based parsers.
DOM:
Properties of DOM:
Programmers can build documents, navigate their structure, and add, modify,
or delete elements and content.
DOM provides a standard programming interface that can be used in a wide
variety of environments and applications.
structural isomorphism.
The Document Object Model is not a binary specification. The Document Object
Model is not a way of persisting objects to XML or HTML. The Document Object Model
does not define "the true inner semantics" of XML or HTML. The Document Object
Model is not a set of data structures, it is an object model that specifies interfaces.
5
Example:
XML:
<?xml version="1.0"?>
<products>
<product>
<name>XML Editor</name>
<price>499.00</price>
</product>
<product>
<name>DTD Editor</name>
<price>199.00</price>
</product>
<product>
<name>XML Book</name>
<price>19.99</price>
</product>
<product>
<name>XML Training</name>
<price>699.00</price>
</product>
</products>
DOM Tree:
Example:
<!DOCTYPE html>
<html>
6
<body>
<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
varpara = document.createElement("p");
var node = document.createTextNode("This is new.");
para.appendChild(node);
var element = document.getElementById("div1");
element.appendChild(para);
</script>
</body>
</html>
Example:
<!DOCTYPE html>
<html>
<body>
<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
var parent = document.getElementById("div1");
var child = document.getElementById("p1");
parent.removeChild(child);
</script>
</body>
</html>
Example:
<!DOCTYPE html>
<html>
<body>
<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
var parent = document.getElementById("div1");
var child = document.getElementById("p1");
varpara = document.createElement("p");
var node = document.createTextNode("This is new.");
para.appendChild(node);
7
parent.replaceChild(para,child);
</script>
</body>
</html>
Limitations:
Introduction to parsers
The word parser comes from compilers
In a compiler, a parser is the module that reads and interprets the
programming language.
In XML, a parser is a software component that sits between the
application and the XML files.
It reads a text-formatted XML file or stream and converts it to a document
to be manipulated by the application.
Types of parsers:
8
Event-based parsers deal generally used for large documents.
Event-based parsers are more complex and give hard time for the
programmer.
SAX is an example of event based parser.
SAX:
SAX (the Simple API for XML) is an event-based parser for xml documents.
The parser tells the application what is in the document by notifying the
application of a stream of parsing events. Application then processes those events to
act on data.
History:
SAX is a common, event-based API for parsing XML documents, developed as a
collaborative project of the members of the XML-DEV discussion under the leadership
of David Megginson.
Versions:
SAX 1 introduced in May 1998,
SAX 2.0 introduced in May 2000.
9
Supported in:
Java
Perl
C++
Python
Components of SAX:
1. Element opening tags
2. Element closing tags
3. Content of elements
4. Entities
5. Parsing errors
Example:
<DocumentElementparam="value">
<FirstElement>¶ Some Text </FirstElement>
<?some_pisome_attr="some_value"?>
<SecondElement param2="something"> Pre-Text
<Inline>Inlined text</Inline> Post-text.
</SecondElement>
</DocumentElement>
SAX Parser:
This XML document, when passed through a SAX parser, will generate a
sequence of events like the following:
• XML Element start, named DocumentElement, with an attribute param equal
to "value"
• XML Element start, named FirstElement
• XML Text node, with data equal to "¶ Some Text"
• XML Element end, named FirstElement
• Processing Instruction event, with the target some_pi and
data some_attr="some_value"
• XML Element start, named SecondElement, with an attribute param2 equal to
"something"
• XML Text node, with data equal to "Pre-Text"
• XML Element start, named Inline
• XML Text node, with data equal to "Inlined text‖
• XML Element end, named Inline
• XML Text node, with data equal to " Post-text‖
• XML Element end, named SecondElement
• Document End.
Limitations of SAX:
With SAX, it is not possible to navigate through the document as you can with
a DOM.
The application must explicitly buffer those events it is interested in.
10
4. XML Schema
• The XML Schema language is also referred to as XML Schema Definition (XSD).
The purpose of an XML Schema is to define the legal building blocks of an XML
document, just like a DTD.
An XML Schema:
The following example is an XML Schema file called "note.xsd" that defines the
elements of the XML document above ("note.xml"):
11
XML Schema example:
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="note">
<xs:complexType>
<xs:sequence>
<xs:element name="to" type="xs:string"/>
<xs:element name="from" type="xs:string"/>
<xs:element name="heading" type="xs:string"/>
<xs:element name="body" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element></xs:schema>
5. Presenting XML
• XSL stands for EXtensible Stylesheet Language, and is a style sheet language
for/presenting XML documents.
• XS stylesheets are not the same as HTML Cascading Stylesheets.
• Create a style for a specific XML element or class of elements, with XSL a
template is created. This template is used to format XML elements which
match a specified pattern.
• The template is a page design or the design of part of a page.
Example: note.xsl
XSL Example
<xsl:template match="/">
12
<html>
<body>
<h2>NOTE</h2>
<table border="1">
<tr bgcolor="#9acd32">
<th>note</th>
</tr>
<tr bgcolor="#9acd44">
<th>from</th>
<th>to</th>
<th>heading</th>
<th>body</th>
</tr>
<xsl:for-each select="note">
<tr>
<td><xsl:value-of select="from"/></td>
<td><xsl:value-of select="to"/></td>
<td><xsl:value-of select="heading"/></td>
<td><xsl:value-of select="body"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
13
UNIT-IV
SERVLET PROGRAMMING
1
iv) The server invokes the service() method of the Servlet. This method is called to
process the HTTP request. You will see that it is possible for the Servlet to read
data that has been provided in the HTTP reuest. It may also formulate an HTTP
response for the client.
The servlet remains in the servers address space and is available to process any
other HTTP requests received from the clients. The service () method is called for
each HTTP request.
v) Finally, the server may decide to unload the Servlet from its memory. The
destroy() method to relinquish any resources such as file handles that are
allocated for the Servlet.
Important data may be saved to a persistent store .The memory allocated for the
Servlet and its objects
can then be garbage collected.
2
• Servlet implementation
– GenericServlet
– HttpServlet
• A Java Servlet is a typical Java class that extends the abstract class HttpServlet.
• The HttpServlet class extends another abstract class called GenericServlet.
• The GenericServlet class implements three interfaces:
javax.servlet.Servlet
javax.servlet.ServletConfig and
java.io.Serializable.
3
Javax.servlet.Servlet interface, the following five methods must be implemented:
Method Description
void init( ServletConfig config )The servlet container calls this method once during a
throws ServletException servlet’s execution cycle to initialize the servlet. The
ServletConfig argument is supplied by the servlet
container that executes the servlet.
ServletConfig getServletConfig() This method returns a reference to an object that
implements interface ServletConfig. This object provides
access to the servlet’s configuration information such as
servlet initialization parameters and the servlet’s
ServletContext, which provides the servlet with access to
its environment (i.e., the servlet container in which the
servlet executes).
String getServletInfo() This method is defined by a servlet programmer to return
a string containing servlet information such as the
servlet’s author and version.
void service( ServletRequest The servlet container calls this method to respond to a
request, ServletResponse client request to the servlet.
response ) throws
ServletException, IOException
void destroy() This ―cleanup‖ method is called when a servlet is
terminated by its servlet container. Resources used by
the servlet, such as an open file or an open database
connection, should be deallocated here.
4
iii) The HttpServlet Class
5
3. Explain about Servlet Configuration and Servlet Exceptions?
Ans.
Servlet Configuration:
In the Java Servlet API, javax.servlet.ServletConfig objects represent the
configuration of a servlet.
The configuration information contains initialization parameters (a set of name/value
pairs), the name of the servlet and a javax.servlet.ServletContext object, which
gives the servlet information about the container.
The initialization parameters and the name of a servlet can be specified in the
deployment descriptor (the web.xml file).
Example:
<web-app>
<servlet>
<servlet-name>Admin</servlet-name>
<servlet-class>com.apress.admin.AdminServlet
</servlet-class>
<init-param>
<param-name>email</param-name>
<param-value>[email protected]</param-value>
</init-param>
<init-param>
<param-name>helpURL</param-name>
<param-value>/admin/help/index.html</param-value>
</init-param>
</servlet>
</web-app>
For Example registers a servlet with name Admin, and specifies two initialization
parameters, email and helpURL.
• The web container reads this information, and makes it available to the
com.apress.admin.AdminServlet via the associated javax.servlet.ServletConfig
object.
• If we want to change these parameters, we can do so without having to recompile
the servlet.
The ServletConfig Interface
public interface ServletConfig
Methods:
• public String getInitParameter(String name)
Ex: [email protected]
6
• public Enumeration getInitParameterNames()
Ex: email and helpURL
• public ServletContex getServletContext()
• public String getServletName()
Servlet Exception
javax.servlet package specifies two exception classes:
• javax.servlet.ServletException
• javax.servlet.UnavailableException
public class ServletException extends java.lang.Exception
This is a generic exception, which can be thrown by the init(), service(), doXXX(), and
destroy() methods. The class provides the following constructions:
• public ServletException()
• public ServletException(String message)
While creating objects of type ServletException, you can embed any application level
exception (called the root-cause).
The containers use the root-cause exception for logging purposes.
For instance, you can embed a java.sql.SQLException in a javax.servlet.ServletException.
There are two additional constructors to support root-cause exceptions:
public ServletException(Throwable cause)
public ServletException(String message, Throwable cause)
The getRootCause() returns the root-cause exception:
public Throwable getRootCause()
public class UnavailableException extends ServletException
The purpose of this is to indicate to the webcontainer that the servlet is either temporarily
or permanently unavailable, then the following constructions:
public UnavailableException(String message)
public UnavailableException(String message, int seconds)
7
4. Explain about cookies and session tracking with an example? (or)
Define Session and Describe with an example how to use the
HttpSession object to find out the creation time and the last-
accessed time for a session using HttpSession interface.
Ans.
Cookies: Cookies are the most commonly used means of tracking client sessions. Cookies
were initially introduced by Netscape, and this technology was later standardized in RFC
2109.
Definition: A Cookie is a small piece of textual information sent by the server to the client,
stored on the client, and return by the client for all requests to the server.
A webserver can assign a unique session ID as a cookie to each web client and for
subsequent requests from the client they can be recognized using the received cookie.
Drawback: This may not be an effective way because many time browsers do not support
a cookie, so I would not recommend using this procedure to maintain the sessions.
Session: Session tracking enables you to track a user's progress over multiple servlets or
HTML pages, which, by nature, are stateless. A session is defined as a series of related
browser requests that come from the same client during a certain time period. Session
tracking ties together a series of browser requests—think of these requests as pages—that
may have some meaning as a whole, such as a shopping cart application.
javax.servlet.HttpSession interface
The HttpSession Object:
Apart from the above mentioned three ways, servlet provides HttpSession Interface
which provides a way to identify a user across more than one page request or visit to a Web
site and to store information about that user.
The servlet container uses this interface to create a session between an HTTP client
and an HTTP server. The session persists for a specified time period, across more than one
connection or page request from the user.
You would get HttpSession object by calling the public method getSession() of
HttpServletRequest, as below:
HttpSession session = request.getSession();
8
You need to call request.getSession() before you send any document content to the
client. Here is a summary of the important methods available through HttpSession object:
9
visitCount = visitCount + 1;
userID = (String)session.getAttribute(userIDKey);
}
session.setAttribute(visitCountKey, visitCount);
// Set response content type
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>\n" + "<head><title>" + title + "</title></head>\n" +
"<body bgcolor=\"#f0f0f0\">\n" + "<h1 align=\"center\">" + title + "</h1>\n" + "<h2
align=\"center\">Session Infomation</h2>\n" +"<table border=\"1\" align=\"center\">\n"
+ "<tr bgcolor=\"#949494\">\n" + " <th>Session info</th><th>value</th></tr>\n" +
"<tr>\n" + " <td>id</td>\n" + " <td>" + session.getId() + "</td></tr>\n" + "<tr>\n" +
" <td>Creation Time</td>\n" + " <td>" + createTime + " </td></tr>\n" +
"<tr>\n" + " <td>Time of Last Access</td>\n" +
" <td>" + lastAccessTime + " </td></tr>\n" + "<tr>\n" +
" <td>User ID</td>\n" + " <td>" + userID + " </td></tr>\n" + "<tr>\n" +
" <td>Number of visits</td>\n" + " <td>" + visitCount + "</td></tr>\n" + "</table>\n"
+ "</body></html>");
}}
Compile above servlet SessionTrack and create appropriate entry in web.xml file. Now
running http://localhost:8080/SessionTrack would display the following result when you
would run for the first time:
Output:
Welcome to my website
Session Information
Session info
Value
Id 0AE3EC93FF44E3C525B435
1B77ABB2D5
Creation Time Tue Jun 08 17:26:40
GMT+04:00 2010
Time of Last Access Tue Jun 08 17:26:40
GMT+04:00 2010
User ID ABCD
Number of visits 0
Now try to run the same servlet for second time, it would display following result.
Output:
Welcome Back to my website
Session Information
info type Value
Id 0AE3EC93FF44E3C525B435
1B77ABB2D5
Creation Time Tue Jun 08 17:26:40
GMT+04:00 2010
Time of Last Access Tue Jun 08 17:26:40
GMT+04:00 2010
User ID ABCD
Number of visits 1
10
UNIT-V
DATABASE PROGRAMMING WITH JDBC
Ans:
The table opposite shows standard mappings between SQL data types and Java primitive
and object types. In practice, many databases provide these standard types plus some
subtly non-standard variants. You might find that on your column you are using the subtly
non-standard variant!
If you are not sure of the type, you can always retrieve getObject() and then find out what
type it is (via getClass()). Luckily, JDBC will generally come to the rescue by converting
between the type returned by the JDBC driver and the type requested.
The ResultSet.getXXX() methods are generally slightly "lenient". If you ask for a different
type to that returned by the JDBC driver (e.g. if you ask for an int when the actual data type
was a short), then JDBC will automatically convert the value to the requested type. This
conversion works:
between all numeric types (though you could lose precision in the conversion);
between most types and String.
1
2. Explain the process of connection management using JDBC.
Ans:
Connection Management:
Connection Management
Class/interface Description
java.sql.DriverManger This class provides the functionality necessary
class for managing one or more database drivers.
Each driver in turn lets you connect to a
specific database
java.sql.Driver interface This is an interface that abstracts the vendor-
specific connection protocol.
java.sql.DriverPropertyInfo Since each database may require a distinct
class set of properties to obtain a connection, you
can use this class to discover the properties
required to obtain the connection.
Java.sql.Connection This interface abstracts most of the
interface interaction with the database. Using a
connection, you can send SQL statements to
the database, and read the results of
execution.
23
The Driver Manager has three variants of a static method getConnection() used to
establish connections.
The driver manager delegates these calls to the connect methods on the java.sql.Driver
interface.
for example: jdbc:odbc:Data where Data is a DSN setup using our ODBC driver
administrator.
Whether we get connection with this method or not is depends on whether the database
accepts connection request without authentication.
This method requires URL and a java.util.Properties object. It contains required parameters
for the specified database. These parameters differs from database to database. Two
common parameters are autocommit=true and create =false.
2
• public static Connection getConnection(String url,String user,String
password) throws SQLException
This method takes user and password as the arguments in addition to the URL.
Ans:
1. Prepare: The statement template is created by the application and sent to the
database management system (DBMS). Certain values are left unspecified,
calledparameters, placeholders or bind variables (labelled "?" below):
INSERT INTO PRODUCT (name, price) VALUES (?, ?)
2. The DBMS parses, compiles, and performs query optimization on the statement
template, and stores the result without executing it.
3. Execute: At a later time, the application supplies (or binds) values for the
parameters, and the DBMS executes the statement (possibly returning a result). The
application may execute the statement as many times as it wants with different
values. In this example, it might supply 'Bread' for the first parameter and '1.00' for
the second parameter.
As compared to executing SQL statements directly, prepared statements offer two main
advantages:[1]
The overhead of compiling and optimizing the statement is incurred only once, although
the statement is executed multiple times. Not all optimization can be performed at the
time the prepared statement is compiled, for two reasons: the best plan may depend on
3
the specific values of the parameters, and the best plan may change as tables and
indexes change over time.[2]
Prepared statements are resilient against SQL injection, because parameter values,
which are transmitted later using a different protocol, need not be correctly escaped. If
the original statement template is not derived from external input, SQL injection cannot
occur.
On the other hand, if a query is executed only once, server-side prepared statements can be
slower because of the additional round-trip to the server.[3] Implementation limitations may
also lead to performance penalties: some versions of MySQL did not cache results of
prepared queries,[4] and some DBMSs such as PostgreSQL do not perform additional query
optimization during execution.[5][6]
A stored procedure, which is also precompiled and stored on the server for later execution,
has similar advantages. Unlike a stored procedure, a prepared statement is not normally
written in a procedural language and cannot use or modify variables or use control flow
structures, relying instead on the declarative database query language. Due to their
simplicity and client-side emulation, prepared statements are more portable across vendors.
Ans:
Database Drivers
• JDBC drivers implement the defined interfaces in the JDBC API for interacting with
your database server.
• For example, using JDBC drivers enable you to open database connections and to
interact with it by sending SQL or database commands then receiving results with
Java.
• The Java.sql package that ships with JDK contains various classes with their
behaviors defined and their actual implementations are done in third-party drivers.
Third party vendors implement the java.sql.Driver interface in their database driver.
4
JDBC Drivers Types:
JDBC driver implementations vary because of the wide variety of operating systems and
hardware platforms in which Java operates. Sun has divided the implementation types into
four categories, Types 1, 2, 3, and 4, which is explained below:
• In a Type 1 driver, a JDBC bridge is used to access ODBC drivers installed on each
client machine. Using ODBC requires configuring on your system a Data Source Name
(DSN) that represents the target database.
• 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.
• The JDBC-ODBC bridge that comes with JDK 1.2 is a good example of this kind of
driver.
Java Data
Application Source
JDBC JDBC
ODBC ODBC ODBC
API API
Bridge Layer
11
• In a Type 2 driver, JDBC API calls are converted into native C/C++ API calls which
are unique to the database. These drivers typically provided by the database vendors
and used in the same manner as the JDBC-ODBC Bridge, the vendor-specific driver
must be installed on each client machine.
5
Java Data
Application Source
JDBC Vendor
JDBC
API Specific
Driver
API
14
• This kind of driver is extremely flexible, since it requires no code installed on the
client and a single driver can actually provide access to multiple databases.
• You can think of the application server as a JDBC "proxy," meaning that it makes
calls for the client application. As a result, you need some knowledge of the
application server's configuration in order to effectively use this driver type.
• Your application server might use a Type 1, 2, or 4 driver to communicate with the
database, understanding the nuances will prove helpful.
Java Data
Application Source
17
6
Type 4: 100% pure Java
• This kind of driver is extremely flexible, you don't need to install special software on
the client or server. Further, these drivers can be downloaded dynamically.
Java Data
Application Source
JDBC JDBC
API Driver
20
• If you are accessing one type of database, such as Oracle, Sybase, or IBM, the
preferred driver type is 4.
• If your Java application is accessing multiple types of databases at the same time,
type 3 is the preferred driver.
• Type 2 drivers are useful in situations where a type 3 or type 4 driver is not available
yet for your database.
• The type 1 driver is not considered a deployment-level driver and is typically used for
development and testing purposes only.
Ans:
SAVEPOINT in JDBC
That may be fine for simple applications, but there are three reasons why you may want to
turn off auto-commit and manage your own transactions:
7
To increase performance
Transactions enable you to control if, and when, changes are applied to the database.
It treats a single SQL statement or a group of SQL statements as one logical unit, and if any
statement fails, the whole transaction fails.
To enable manual- transaction support instead of the auto-commit mode that the
JDBC driver uses by default, use the Connection object's setAutoCommit() method. If you
pass a boolean false to setAutoCommit( ), you turn off auto-commit. You can pass a boolean
true to turn it back on again.
For example, if you have a Connection object named conn, code the following to turn off
auto-commit:
conn.setAutoCommit(false);
Otherwise, to roll back updates to the database made using the Connection named
conn, use the following code:
conn.rollback();
The following example illustrates the use of a commit and rollback object:
try{
//Assume a valid connection object conn
conn.setAutoCommit(false);
Statementstmt=conn.createStatement();
In this case none of the above INSERT statement would success and everything would be
rolled back.
8
Using Savepoints:
The new JDBC 3.0 Savepoint interface gives you additional transactional control. Most
modern DBMS support savepoints within their environments such as Oracle's PL/SQL.
When you set a savepoint you define a logical rollback point within a transaction. If an error
occurs past a savepoint, you can use the rollback method to undo either all the changes or
only the changes made after the savepoint.
The Connection object has two new methods that help you manage savepoints:
try{
//Assume a valid connection object conn
conn.setAutoCommit(false);
Statementstmt=conn.createStatement();
//set a Savepoint
Savepoint savepoint1 =conn.setSavepoint("Savepoint1");
String SQL ="INSERT INTO Employees "+
"VALUES (106, 20, 'Rita', 'Tez')";
stmt.executeUpdate(SQL);
//Submit a malformed SQL statement that breaks
String SQL ="INSERTED IN Employees "+
"VALUES (107, 22, 'Sita', 'Tez')";
stmt.executeUpdate(SQL);
// If there is no error, commit the changes.
conn.commit();
}catch(SQLException se){
// If there is any error.
conn.rollback(savepoint1);
}
In this case none of the above INSERT statement would success and everything would be
rolled back.
6. Write a java program for storing student details like name, roll
number, branch and mobile number into the database using JDBC.
Ans:
9
public class FirstExample
{
public static void main(String[] args)
{
Connection conn = null; //Connection is an interface, create only reference: conn
Statement stmt = null; //Statement is an interface, create only reference: stmt
try{
//STEP 2: Register JDBC driver
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); //Class.forName calls indirectly
DriverManager.registerDriver() and Type-1 driver
String sql1;
sql1="create table emp_data4(empId Number,empName Text, age Number, city Text)";
stmt.executeUpdate(sql1);
System.out.println("table created");
String sql2, sql3;
sql2="insert into emp_data4 values(9,'xyz',29,'delhi')";
stmt.executeUpdate(sql2);
sql3="insert into emp_data4 values(10,'abc',50,'Mumbai')";
stmt.executeUpdate(sql3);
System.out.println("2 rows inserted");
String sql4;
sql4 = "select empId, empName, age,city from emp_data4";
ResultSet rs = stmt.executeQuery(sql4);
10
}
catch(Exception e)
{
//Handle errors for Class.forName
e.printStackTrace();
}
}//end main
}//end FirstExample
Class/interface Description
java.sql.Statement This interface lets you execute SQL statements over the
underlying connection and access the results.
java.sql.Driver PreparedStatement This is a variant of the java.sql.Statement interface
following for parameterized SQL statements include
markers (as ―?‖), which can be replaced with actual
values later on.
8. Datatypes
The java.sql package also provides several java data types that correspond to some of the
SQL types. You can use one of the following types as appropriate depending on what a field
in a result row correspond in a database.
Class/interface Description
java.sql.Blob interface This interface provides a java language abstraction of the SQL type
BLOB.
java.sql.Clob interface This interface provides a java language abstraction of the SQL type
CLOB.
java.sql.Date class This class provides a java language abstraction of the SQL type
DATE.
java.sql.Time class This interface provides a java language abstraction of the SQL type
TIME.
11
Java.sql.Types class This class holds a set of constant integers, each corresponds to a
SQL type.
9. Database Metadata
The JDBC API also includes facilities to obtain metadata about the database,
parameters to statements, and results.
Class/interface Description
Class/interface Description
12
11. Loading a Database Driver and Opening Connections
The java.sql.Connection interface represents a connection with a database. The JDBC API
provides two different approaches for obtaining connections.
The first uses java.sql.DriverManager and is suitable for non-managed applications such as
standalone java database clients.
The second approach is based on the java.sql package that introduces the notation of data
sources and is suitable for access in J2EE applications.
Whether we get connection with this method or not is depends on whether the database
accepts connection request without authentication.
• public static Connection getConnection(String url, java.util.Properties info)
throws SQLException
This method requires URL and a java.util.Properties object. It contains required
parameters for the specified database. These parameters differs from database to
database. Two common parameters are autocommit=true and create =false.
• public static Connection getConnection(String url,String user,String
password) throws SQLException
This method takes user and password as the arguments in addition to the URL.
• public static void setLoginTimeout(int seconds)
This method can be used to set the login timeout.
• public static void getLoginTimeout()
This method can be used to get the login timeout.
13
12. Establishing Connection
To communicate with a database using JDBC, we first establish a connection to the database
using java.sql.Connection interface.
It has the following public methods:
Function Methods
1. What are the limitations of Servlets? Discuss how JSP overcomes these
Problems.
JSP pages easily combine static templates, including HTML or XML fragments,
with code that generates dynamic content.
JSP pages are compiled dynamically into servlets when requested, so page
authors can easily make updates to presentation code. JSP pages can also be
precompiled if desired.
JSP tags for invoking JavaBeans components manage these components
completely, shielding the page author from the complexity of application logic.
Developers can offer customized JSP tag libraries that page authors access using
an XML-like syntax.
Web authors can change and edit the fixed template portions of pages without
affecting the application logic. Similarly, developers can make logic changes at
the component level without editing the individual pages that use the logic.
1
2. What is MVC architecture? Explain with a neat diagram.
Model classes store the data for a page or page section. A single page might use
one or more Model classes, depending on how much of the page data can be shared
by other types of pages. A Model defines how data is accessed and set for a given
page, including any functions necessary for security or data validation and
modification. Models encapsulate calls to the portal server API and also store UI-
specific data. Data that is globally accessed by the UI is available from the
ActivitySpaceobject . All other data should be stored in a Model.
View classes contain HTMLElements and HTMLConstructs that describe how the data
from the Model should be displayed to the user. In the portal UI design,
DisplayPage objects are used to aggregate View objects to encapsulate all the
information needed to render a particular page. Some Views are common
throughout the portal and some are specific to certain pages. For example, the
banner that makes up the majority of the portal is a common View that defines the
color scheme and where the search section will be displayed. In contrast, the View
used to create and modify data within a User Profile is specific to the User Profile
function and is seen only on that page.
Control are actions or sets of actions that are executed when a specific event is
triggered. Multiple Controls can be defined within a page, each with its own
functional specification. For example, one Control might produce a popup window
that allows the user to browse for a specific object and places the selection within
the View, and another could save the new data to the Model.
The diagram below shows a simplified version of how the classes used for the Login page
interact with each other using the Model-View-Control (MVC) pattern.
2
5. The Control either redirects to another page or returns to the same page with new
data since the Model has been updated. In this case, the Control redirects to the
MyPage.
6. The Interpreter gets the HTML for the page requested by the Control from the
appropriate View, in this case the MyPage View.
7. The View returns the HTML for the page.
8. The Interpreter sends the HTML for the page back to the browser.
1. JSPs are converted into servlets by the JSP container. This makes the page load a bit
late ( but only for the first time) from then on it loads the servlet from the cache.
2. Java code in JSP: This actually proves to be a nightmare for HTML programmers as
java code in JSP has got "lousy looping". The main idea of JSP was to clearly separate
the presentation from the business logic or the processing logic. But it doesn’t seem to
operate that way. The temptation to add java code in JSP is always there. Sometimes
the HTML programmers may even "knock off" some java code in the JSP file leading to
"chaos" Solution: We can use the combination of custom TagLibs and Bean Tags to
overcome this problem, but only to a certain extent. Moreover if we have our
architecture right, wherein we use a combination of servlets and JSP we can overcome
the above problem. In this architecture only the "View" is given to the JSP. The
"Controller" will be a servlet that takes care of the processing logic.
3. Using Templates in JSP: Though in its initial stage, by using templates we can
componentize the GUI also. The design pattern says "Anything that changes " should be
encapsulated.
• JSP actions use constructs in XML syntax to control the behavior of the servlet
engine. You can dynamically insert a file, reuse JavaBeans components, forward
the user to another page, or generate HTML for the Java plugin.
There is only one syntax for the Action element, as it conforms to the XML standard:
Action elements are basically predefined functions and there are following JSP actions
available:
3
Syntax Purpose
• JSP Implicit Objects are the Java objects that the JSP Container makes available
to developers in each page and developer can call them directly without being
explicitly declared. JSP Implicit Objects are also called pre-defined variables.
Object Description
Out This is the PrintWriter object used to send output to the client.
4
This is the ServletContext object associated
Application
with application context.
• The availability of a JSP object for use from a particular place of the application is
defined as the scope of that JSP object. Every object created in a JSP page will
have a scope.
• Object scope in JSP is segregated into four parts and they are page, request,
session and application.
Syntax:
5. JSP Directives
Directive Description
<%@ include ... %> Includes a file during the translation phase.
<%@ taglib ... %> Declares a tag library, containing custom actions, used in the page
The page directive is used to provide instructions to the container that pertain to the
current JSP page. You may code page directives anywhere in your JSP page. By
convention, page directives are coded at the top of the JSP page.
5
Following is the basic syntax of page directive:
Attribute Purpose
Specifies a list of packages or classes for use in the JSP as the Java import
Import
statement does for Java classes.
Defines a string that can be accessed with the servlet's getServletInfo()
Info
method.
isThreadSafe Defines the threading model for the generated servlet.
Session Specifies whether or not the JSP page participates in HTTP sessions
isELIgnored Specifies whether or not EL expression within the JSP page will be ignored.
The include directive is used to includes a file during the translation phase. This
directive tells the container to merge the content of other external files with the current
JSP during the translation phase. You may code include directives anywhere in your JSP
page.
The filename in the include directive is actually a relative URL. If you just specify a
filename with no associated path, the JSP compiler assumes that the file is in the same
directory as your JSP.
6
The taglib Directive
• The JavaServer Pages API allows you to define custom JSP tags that look like
HTML or XML tags and a tag library is a set of user-defined tags that implement
custom behavior.
• The taglib directive declares that your JSP page uses a set of custom tags,
identifies the location of the library, and provides a means for identifying the
custom tags in your JSP page.
Examples
6. Scripting Elements
• The Scriptlet
• JSP Declarations
• JSP Expression
• JSP Comments
• A Test of Comments
The Scriptlet
Example
7
if (name == null)
{ %>
<% }
else
{ %>
<% } %>
JSP Declarations
A declaration declares one or more variables or methods that you can use in Java
code later in the JSP file. You must declare the variable or method before you use it in
the JSP file.
Example
%! int i = 0; %>
JSP Expression
8
• Following is the simple example for JSP Expression:
<html>
<head>
<body>
</p>
</body>
</html>
JSP Comments
• JSP comment marks text or statements that the JSP container should ignore. A
JSP comment is useful when you want to hide or "comment out" part of your JSP
page.
Example
<html>
<body>
<%-- This comment will not be visible in the page source --%>
</body>
</html>
Syntax Purpose
<%-- comment --%> A JSP comment. Ignored by the JSP engine.
<!-- comment --> An HTML comment. Ignored by the browser.
<\% Represents static <% literal.
9
%\> Represents static %> literal.
\' A single quote in an attribute that uses single quotes.
\" A double quote in an attribute that uses double quotes.
When you send XML data via HTTP, it makes sense to use JSP to handle incoming and
outgoing XML documents for example RSS documents. As an XML document is merely a
bunch of text, creating one through a JSP is no more difficult than creating an HTML
document.
You can send XML content using JSPs the same way you send HTML. The only difference
is that you must set the content type of your page to text/xml. To set the content type,
use the
<books>
<book>
<name>Padam History</name>
<author>ZARA</author>
<price>100</price>
</book>
</books>
Ans. hello.jsp
<html>
<head>
<title>Sample page</title></head>
10
<body>
</body>
</html>
The hello.jsp page is a static HTML page embedded with a JSP command. A JSP
command is an XML-like snippet that encapsulates logic that dynamically generates
content within the static HTML. JSP commands can include directives, declarations,
expressions, actions, and blocks of Java code, all enclosed within angle-brackets, like
XML elements.
At compile-time, the JSP is converted into a servlet, which is what tc Runtime instance
actually executes at runtime.
This JSP directive simply prints out a message to the client (browser): Hello!
NOTE:
11
UNIT -7
A. JavaBean is a specially constructed Java class written in the Java and coded
according to the JavaBeans API specifications.
Following are the unique characteristics that distinguish a JavaBean from other Java
classes:
• It may have a number of "getter" and "setter" methods for the properties.
JavaBeans Properties
• A JavaBean property is a named attribute that can be accessed by the user of the
object. The attribute can be of any Java data type, including classes that you
define.
• A JavaBean property may be read, write, read only, or write only. JavaBean
properties are accessed through two methods in the JavaBean's implementation
class:
Method Description
getPropertyName() For example, if property name is firstName,
your method name would be getFirstName()
to read that property. This method is called
accessor.
setPropertyName() For example, if property name is firstName,
your method name would be setFirstName()
to write that property. This method is called
mutator.
2. Accessing JavaBeans
• The useBean action declares a JavaBean for use in a JSP. Once declared, the
bean becomes a scripting variable that can be accessed by both scripting
elements and other custom tags used in the JSP.
1
<jsp:useBean id="bean's name" scope="bean's scope" typeSpec/>
Here values for the scope attribute could be page, request, session or application
based on your requirement. The value of the id attribute may be any value as a
long as it is a unique name among other useBean declarations in the same JSP.
<html>
<head>
<title>useBean Example</title>
</head>
<body>
</body>
</html>
value="value"/>
...........
</jsp:useBean>
2
JavaBeans Example
public StudentsBean() {}
return firstName;
return lastName;
return age;
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
3
}
<html>
<head>
</head>
<body>
</jsp:useBean>
</p>
</p>
<p>Student Age:
</p>
</body>
</html>
• JSP 1.1 specification was support for Tag Extensions (custom tags).
• JSP 1.2 Specification, confirming tag extensions as one of the important features
of JSP.
• The extension look a lot like standard HTML or XML tags embedded in a JSP page,
but they have a special
4
• Meaning to the JSP engine at translation time, and allow custom functionality to
be invoked without having to write Java code within scriptlets.
Attribute Description
Uri Specifies the relative or absolute uri of the tag
library descriptor
tagPrefix Specifies the required prefix that distinguishes
custom tags from built-in tags. The prefix names
jsp, jspx, java, javax, servelt, sun and sunw
are reserved.
Tag Library
e.g. META-INF/taglib.tld
Syntax
Tags are made available within a JSP page via the taglib directive:
• Directive’s uri attribute references the TLD (established via WAR file’s web.xml)
• Directive’s prefix attribute provides a local namespace for the TLD’s tags
5
Figure 1. Structure of the war file
A war file is a jar file with special directories and a file named web.xml in the WEB-INF
directory
A Simple Tag
Hello.jsp
<html>
</head>
<body>
<ex:Hello>
//</ex:Hello>
</body>
</html>
6
HelloTag.java
import javax.servlet.jsp.tagext.*;
java.io.*;
}}
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>2.0</jsp-version>
<short-name>ex</short-name>
<tag>
<name>Hello</name>
<tag-class>HelloTag</tag-class>
<body-content>empty</body-content></tag> </taglib>
web.xml
<web-app>
<taglib>
<taglib-uri>/hello</taglib-uri>
<taglib-location>/WEB-INF/tlds/hello.tld</taglib-location>
</taglib>
</web-app>
7
4. Anatomy of tag Extensions
Note:
Like the standard actions, custom tags follow XML syntax conventions:
</prefix:name>
Tag handlers
– javax.servlet.jsp.tagext.Tag
– javax.servlet.jsp.tagext.IterationTag
– javax.servlet.jsp.tagext.BodyTag
– javax.servlet.jsp.tagext.TagSupport or
– javax.servlet.jsp.tagext.BodyTagSupport class
– /WEB-INF/classes/<package-directory-structure>
• Tag attributes are managed as JavaBeans properties (i.e., via getters and setters)
8
Figure 2. Javax.servlet.jsp.tagext.Tag interface
9
Figure 4. Class Diagram
10
5. Writing Tag Extensions
11
Figure 6. WelcomeTag-Handler custom tag handler.
12
Figure 7. Custom tag library descriptor files example-taglib.tld
NOTE:
13
UNIT -8
<jsp:useBean>
<jsp:setProperty>
<jsp:getProperty>
1
Figure 1 shows how custom tags fit into the Web application architecture.
Typically HTTP requests coming from the client are handled by the centralized
controller, which in turn forwards them to JSP pages. The JSP pages then call
server side objects for business logic processing. These server side objects
can be either in the form of Java Beans or custom tags.
Property Purpose
2
Following is the example to specify properties related to an attribute:
.....
<attribute>
<name>attribute_name</name>
<required>false</required>
<type>java.util.Date</type>
<fragment>false</fragment>
</attribute>
.....
If you are using two attributes then you can modify your TLD as
follows:
.....
<attribute>
<name>attribute_name1</name>
<required>false</required>
<type>java.util.Boolean</type>
<fragment>false</fragment>
</attribute>
<attribute>
<name>attribute_name2</name>
<required>true</required>
<type>java.util.Date</type>
</attribute>
.....
3
2. Introducing the JSP Standard Tag Library (JSPTL)
Sample Example1:
Example 2
<html>
<head>
</head>
<body bgcolor=―#FFFFFF‖>
<tr>
<td
width=―67%‖><b><i>Name</i></b></td><td><b><i>RGB
Value</i></b></td>
</tr>
<td><jx:expr value=―$color.name‖/></td>
<td><jx:expr value=―$color.RGBValue‖/></td>
</tr>
4
</jx:forEach>
</body>
</html>
Example:
<jx:expr id="postcode"
type="java.lang.String" />
5
Table 2 Iteration tags
<TD><jx:expr value="$color.name"/></TD>
</jx:forEach>
</jx:forEach>
6
var The name to assign the scoped attribute that
represents the current Item of the collection being
iterated over. In the case where the Iteration object
is a Java.util.Map, the current item exposed, will be
a java.util.Map.Entry object.In the case where the
Iteration object is a java.sql.ResultSet the current
item exposed will be the java.sql.ResultSet itself,
positioned at the next row.
7
begin Same behavior as the begin attribute of the
forEachTag.
8
Table 4 Iteration Tag Extesibility
Tag Description
interfaceIteratorTag The JSPTL iteration tags provide the status of the iteration
Status cycle within the scope of the tag. Custom iteration tags that
confirm to the IteratorTag interface must also provide this
information through the IteratorTagStatus object.
abstractclass Abstract base class for building custom iteration tags. Custom
IteratorTagSupport iteration tags just implement the hasNext() and next()
methods, providing the stop mechanism of the iteration cycle
and the iterated over in sequence.
Example:
</jx:if>
<jx:ifvar="isMale"test=―$employee.sex
== „M‟‖/>
9
test An expression-language expression, if
used with the jx tag library or a request-
time expression, if used with the jr tag
library. The expression must evaluate to
a boolean primitive or primitive wrapper
Boolean object.
< j x : choose>
</jx:when>
<jx:when
test="$employee.age >= 40">
</jx:when>
<jx:otherwise>
</jx:othewise>
</jx:choose>
10