1 INDEX Sl.No Experiment Page No 1. Introduction To Html 4 2. Write A Html Program For Feedback Form Of An Website 8 3. Introduction To Ordered , Unordered , Definition Lists 11 4. Write A Html Program To Explain About Ordered Lists And Unordered Lists 13 5. Introduction To Cascading Style Sheets 15 6. Write A Html Program To Explian About Different Stylesheets In Html 16 7. Introduction To Frames 20 8. Write A Html Program To Explian About Frames In Html? 22 9. Develop static pages (using Only HTML) of an online Book store.The pages should resemble:www.amazon.com.The website should consists the following pages. Home page Registration User Login Books catalog 26 10. Introduction To Java Script 32 11. Write A Javascript Program Performing Differnt Mathematical Operations 33 12. Write A Javascript Program To Check Whether A Chechbox Is Checked Or Not And Displaying Text In The Text Field Entered 35 13. Write A Javascript Program To Create Documents On The Fly 37 14. Validate the Registration, user login, user profile and payment by credit card pages using JavaScript. 39 15. Introduction To Xml , Dtd 50 16. Develop A DTD And A Xml Document For Employees In An Organisation And Check Whether The Document Is Valid Or Not ? 55 17. Create and save anXML document at the server,which contains 10users 57
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
1
INDEX
Sl.No Experiment Page No1. Introduction To Html 42. Write A Html Program For Feedback Form Of An Website 83. Introduction To Ordered , Unordered , Definition Lists 114. Write A Html Program To Explain About Ordered Lists And
Unordered Lists13
5. Introduction To Cascading Style Sheets 156. Write A Html Program To Explian About Different Stylesheets In
Html16
7. Introduction To Frames 208. Write A Html Program To Explian About Frames In Html? 229. Develop static pages (using Only HTML) of an online Book
store.The pages should resemble:www.amazon.com.The website should consists the following pages.Home pageRegistrationUser LoginBooks catalog
26
10. Introduction To Java Script 3211. Write A Javascript Program Performing Differnt Mathematical
Operations33
12. Write A Javascript Program To Check Whether A Chechbox Is Checked Or Not And Displaying Text In The Text Field Entered
35
13. Write A Javascript Program To Create Documents On The Fly 3714. Validate the Registration, user login, user profile and payment
by credit card pages using JavaScript.39
15. Introduction To Xml , Dtd 5016. Develop A DTD And A Xml Document For Employees In An
Organisation And Check Whether The Document Is Valid Or Not ?
55
17. Create and save anXML document at the server,which contains 10users Information.write a Program,which takes user Id as an input and returns th User details by taking the user information from the XML document.
57
18. Write A Program To Display Information From An Xml Document
59
19. Install TOMCAT web server. Convert the static webpages of assignments 2 into dynamic webpages using servlets and cookies. Hint: Users information (user id, password, credit card number) would be stored in web.xml. Each user should have a separate Shopping Cart.
61
20. Introduction To Servlets 75
2
21. Program To Explain LifeCycle Of Servlet 7622. Program To Get Request Data From The Client 7923. Program To Explain Cookies Concept In Servlets 8224. Introduction To Session Managament 8925. Program To Explain Session Tracking In Servlets 9126. Introduction To Java Server Pages 9627. Program To Explain Accessing Java Beans From Java Server P
ages103
28. Redo the previous task using JSP by converting the static web pages of assignments 2 into dynamic web pages. Create a database with user information and books information and books information. The books catalogue should be dynamically loaded from the database. Follow the MVC architecture while doing the website.
107
29. Implement the "Hello World!" program using JSP Struts Framework
121
30. Program to show how to use Resultset to get data From database table
124
31. Program to show how to use PreparedStatement to insert data into database table
125
32. Program to explain ResultSetMetaData 126
3
INTRODUCTION TO HTML :
What is HTML?
HTML is a language for describing web pages.
HTML stands for Hyper Text Markup Language HTML is not a programming language, it is a markup language A markup language is a set of markup tags HTML uses markup tags to describe web pages
HTML Tags :
HTML markup tags are usually called HTML tags
HTML tags are keywords surrounded by angle brackets like <html> HTML tags normally come in pairs like <b> and </b> The first tag in a pair is the start tag, the second tag is the end tag Start and end tags are also called opening tags and closing tags
HTML Documents = Web Pages
HTML documents describe web pages HTML documents contain HTML tags and plain text HTML documents are also called web pages
The purpose of a web browser (like Internet Explorer or Firefox) is to read HTML documents and display them as web pages. The browser does not display the HTML tags, but uses the tags to interpret the content of the page.
Tag Description
<html> Defines an HTML document
<body> Defines the document's body
<h1> to <h6> Defines header 1 to header 6
<hr /> Defines a horizontal rule
<!--> Defines a comment
4
HTML Paragraphs
Paragraphs are defined with the <p> tag.
HTML Line Breaks
Use the <br /> tag if you want a line break (a new line) without starting a new paragraph
Forms
A form is an area that can contain form elements.
Form elements are elements that allow the user to enter information (like text fields, textarea fields, drop-down menus, radio buttons, checkboxes, etc.) in a form.
A form is defined with the <form> tag.
<form>input elements</form>
InputThe most used form tag is the <input> tag. The type of input is specified with the type attribute. The most commonly used input types are explained below.
Text Fields
Text fields are used when you want the user to type letters, numbers, etc. in a form.<form>First name:<input type="text" name="firstname" /><br />Last name:<input type="text" name="lastname" /></form>
5
How it looks in a browser:
First name: Last name:
Note that the form itself is not visible. Also note that in most browsers, the width of the text field is 20 characters by default.
Radio Buttons
Radio Buttons are used when you want the user to select one of a limited number of choices.
Checkboxes are used when you want the user to select one or more options of a limited number of choices.
<form>I have a bike:<input type="checkbox" name="vehicle" value="Bike" /><br />I have a car:<input type="checkbox" name="vehicle" value="Car" /><br />I have an airplane:<input type="checkbox" name="vehicle" value="Airplane" /></form>
6
How it looks in a browser:
I have a bike: I have a car: I have an airplane:
The Form's Action Attribute and the Submit Button
When the user clicks on the "Submit" button, the content of the form is sent to the server. The form's action attribute defines the name of the file to send the content to. The file defined in the action attribute usually does something with the received input.
Form TagsTag Description<form> Defines a form for user input<input> Defines an input field<textarea> Defines a text-area (a multi-line text input control)<label> Defines a label to a control<fieldset> Defines a fieldset<legend> Defines a caption for a fieldset<select> Defines a selectable list (a drop-down box)<optgroup> Defines an option group<option> Defines an option in the drop-down box<button> Defines a push button<isindex> Deprecated. Use <input> instead
Submit
7
Program 1:
write a html program for feedback form of an website
Code:
<html><head>
<title>example for forms</title></head><body>
<h1>Feedback Form</h1><p>please fill out this form to help us improve our
<input type="submit" value="submit your entries"/>
9
<input type="reset" value="clear your entries"/>
</p></form>
</body></html>
output:
10
INTRODUCTION TO ORDERED , UNORDERED , DEFINITION LISTS:
HTML supports ordered, unordered and definition lists.
Unordered Lists
An unordered list is a list of items. The list items are marked with bullets (typically small black circles).
An unordered list starts with the <ul> tag. Each list item starts with the <li> tag.
<ul><li>Coffee</li><li>Milk</li></ul>
Here is how it looks in a browser:
Coffee Milk
Inside a list item you can put paragraphs, line breaks, images, links, other lists, etc.
Ordered Lists
An ordered list is also a list of items. The list items are marked with numbers.An ordered list starts with the <ol> tag. Each list item starts with the <li> tag.
<ol><li>Coffee</li><li>Milk</li></ol>
Here is how it looks in a browser:
1. Coffee2. Milk
Inside a list item you can put paragraphs, line breaks, images, links, other lists, etc.
11
Definition Lists
A definition list is not a list of single items. It is a list of items (terms), with a description of each item (term).
A definition list starts with a <dl> tag (definition list).
Each term starts with a <dt> tag (definition term).
Each description starts with a <dd> tag (definition description).
<dl><dt>Coffee</dt><dd>Black hot drink</dd><dt>Milk</dt><dd>White cold drink</dd></dl>
Here is how it looks in a browser:
CoffeeBlack hot drink
MilkWhite cold drink
Inside the <dd> tag you can put paragraphs, line breaks, images, links, other lists, etc
List TagsTag Description<ol> Defines an ordered list<ul> Defines an unordered list<li> Defines a list item<dl> Defines a definition list<dt> Defines a term (an item) in a definition list<dd> Defines a description of a term in a definition list<dir> Deprecated. Use <ul> instead<menu> Deprecated. Use <ul> instead
Program 2:
12
write a html program to explain about ordered lists and unordered lists
Code:
<html> <head><title> Example to explain lists </title></head><body> <h1>Best features of internet </h1> <ul type=A> <li> You can meet people across world </li><li> Can access to new media like <ul> <li>Games </li> <li>new applications <ol>
<li> XML </li> <li> JAVA </li> <li> HTML </li> <li> XHTML </li> <li> New languages </li>
</ol> </li>
</ul> </li> <li> LInks </li> <li> keeping in touch with old firends </li> <li> it is a technology of future </li></ul> </body></html>
Output:
13
INTRODUCTION TO CASCADING STYLE SHEETS :
14
The HTML Style Attribute
The purpose of the style attribute is:
To provide a common way to style all HTML elements.
Styles was introduced with HTML 4, as the new and preferred way to style HTML elements. With HTML styles, styles can be added to HTML elements directly by using the style attribute, or indirectly by in separate style sheets (CSS files).
What is CSS?
CSS stands for Cascading Style Sheets Styles define how to display HTML elements Styles were added to HTML 4.0 to solve a problem External Style Sheets can save a lot of work External Style Sheets are stored in CSS files
Styles Solved a Big Problem
HTML was never intended to contain tags for formatting a document.
HTML was intended to define the content of a document, like:
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
When tags like <font>, and color attributes were added to the HTML 3.2 specification, it started a nightmare for web developers. Development of large web sites, where fonts and color information were added to every single page, became a long and expensive process.
To solve this problem, the World Wide Web Consortium (W3C) created CSS.
In HTML 4.0, all formatting could be removed from the HTML document, and stored in a separate CSS file.All browsers support CSS today.CSS Saves a Lot of Work!CSS defines HOW HTML elements are to be displayed.Styles are normally saved in external .css files. External style sheets enable you to change the appearance and layout of all the pages in a Web site, just by editing one single file!
Program 3:
15
write a html program to explian about different stylesheets in html
code:
Inline stylesheet:
<html><head ><title> Example for inline styles </title><body><p> This text does not have any style applied to it. </p> <p style= "font-size:20pt"> This text has <em> font-size 20 pt applied to it </em> </p> <p style="font-size:20pt; color:0000FF"> This text is in BLUE color with font size 2o pt </p></body></html> Output:
Embedded stylesheet:
<html><head >
16
<title> Example for embeded style sheets </title><style type="text/css"> em { background-color:#0000ff; }h1 { font-family:arial,sans-serif }p { font-size:15pt}.special{color:red}</style></head><body><p> This line text had font size 15pt which was effected using embeeded style sheet for p tag </p> <em> This line of text is effected by embedded style sheet with backgournd color blue </em> <h1> Heading with arial font instead of times new roman by using embedded style for h1 tag </h1> <p class="special"> This text is effected with red color by using embeeded style class </p></body></html>Output:
External stylesheet:
Styles.css:-
17
em { background-color:#0000ff; }
h1 { font-family:arial,sans-serif }
p { font-size:15pt}
.special{color:red}
External.html:-
<html> <head><title> Demonstration on external style sheet linking </title><link rel="stylesheet" type="text/css" href="styles.css"/> </head> <body> <p> This line text had font size 15pt which was effected using embeeded style sheet for p tag </p> <em> This line of text is effected by embedded style sheet with backgournd color blue </em> <h1> Heading with arial font instead of times new roman by using embedded style for h1 tag </h1> <p class="special"> This text is effected with red color by using embeeded style class </p> </body></html>
Output:
18
INTRODUCTION TO FRAMES:
19
With frames, you can display more than one HTML document in the same browser window. Each HTML document is called a frame, and each frame is independent of the others.
The disadvantages of using frames are:
The web developer must keep track of more HTML documents It is difficult to print the entire page
The Frameset Tag
The <frameset> tag defines how to divide the window into frames Each frameset defines a set of rows or columns The values of the rows/columns indicate the amount of screen area
each row/column will occupy
The Frame Tag
The <frame> tag defines what HTML document to put into each frame
In the example below we have a frameset with two columns. The first column is set to 25% of the width of the browser window. The second column is set to 75% of the width of the browser window. The HTML document "frame_a.htm" is put into the first column, and the HTML document "frame_b.htm" is put into the second column:
Note: The frameset column size value can also be set in pixels (cols="200,500"), and one of the columns can be set to use the remaining space (cols="25%,*").
Basic Notes - Useful Tips
20
If a frame has visible borders, the user can resize it by dragging the border. To prevent a user from doing this, you can add noresize="noresize" to the <frame> tag.
Add the <noframes> tag for browsers that do not support frames.
Important: You cannot use the <body></body> tags together with the <frameset></frameset> tags! However, if you add a <noframes> tag containing some text for browsers that do not support frames, you will have to enclose the text in <body></body> tags! See how it is done in the first example below.
Frame TagsTag Description<frameset> Defines a set of frames<frame> Defines a sub window (a frame)<noframes> Defines a noframe section for browsers that do not handle frames<iframe> Defines an inline sub window (frame)
21
Program 4:
write a html program to explian about frames in html?
Code:
Welcome.html:-
<html><body>
<h1><center>welcome to our site</center></h1></body></html
<html><body><h3><center>This is the main page</center></h3><br/><h3><center><u>our site provides the following facilities</u></h3><ul> <li> You can meet people across world </li><li> Can access to new media like Games,business,new softwares.</li> <li> keeping in touch with old firends </li> <li> it is a technology of future </li></ul></body></html>
Develop static pages (using Only HTML) of an online Book store.The pages should resemble:www.amazon.com.The website should consists the following pages.
Home page Registration User Login Books catalog
Code:
Main page:
<html>
<head>
<title>home page</title>
</head>
<body>
<center><b><h1>welcome to amazon.com</h1></b><br><br>
<form method="post"action="login.html">
<input type="submit"value="click">registration user login hear
JavaScript was designed to add interactivity to HTML pages JavaScript is a scripting language A scripting language is a lightweight programming language JavaScript is usually embedded directly into HTML pages JavaScript is an interpreted language (means that scripts execute
without preliminary compilation) Everyone can use JavaScript without purchasing a license
What can a JavaScript do? JavaScript gives HTML designers a programming tool - HTML
authors are normally not programmers, but JavaScript is a scripting language with a very simple syntax! Almost anyone can put small "snippets" of code into their HTML pages
JavaScript can put dynamic text into an HTML page - A JavaScript statement like this: document.write("<h1>" + name + "</h1>") can write a variable text into an HTML page
JavaScript can react to events - A JavaScript can be set to execute when something happens, like when a page has finished loading or when a user clicks on an HTML element
JavaScript can read and write HTML elements - A JavaScript can read and change the content of an HTML element
JavaScript can be used to validate data - A JavaScript can be used to validate form data before it is submitted to a server. This saves the server from extra processing
JavaScript can be used to detect the visitor's browser - A JavaScript can be used to detect the visitor's browser, and - depending on the browser - load another page specifically designed for that browser
JavaScript can be used to create cookies - A JavaScript can be used to store and retrieve information on the visitor's computerTo insert a JavaScript into an HTML page, we use the <script> tag. Inside the <script> tag we use the type attribute to define the scripting language.So, the <script type="text/javascript"> and </script> tells where the JavaScript starts and endsBy entering the document.write command between the <script> and </script> tags, the browser will recognize it as a JavaScript command and execute the code line
Program 6:
32
write a javascript program performing differnt mathematical operations
write a javascript program to check whether a chechbox is checked or not and displaying text in the text field entered
Code:
<html><head><title>Objects</title><script language="JavaScript"> <!-- hidefunction first() {// creates a popup window with the// text which was entered into the text elementalert("The value of the textelement is: " +document.myForm.myText.value);}function second() {// this function checks the state of the checkboxvar myString= "The checkbox is ";// is checkbox checked or not?if (document.myForm.myCheckbox.checked) myString+= "checked"else myString+= "not checked";// output stringalert(myString);}// --></script></head><body bgcolor=lightblue><form name="myForm"><input type="text" name="myText" value="hai how r u"><input type="button" name="button1" value="Button 1"onClick="first()"><br><input type="checkbox" name="myCheckbox" CHECKED><input type="button" name="button2" value="Button 2"onClick="second()"></form><p><br><br><script language="JavaScript"> <!-- hidedocument.write("The background color is: ");document.write(document.bgColor + "<br>");document.write("The text on the second button is: ");document.write(document.myForm.button2.value);// -->
35
</script></body></html>
Output:
Program 8:
write a javascript program to create documents on the fly
36
Code:
<html><head><script language="JavaScript"> <!-- hidefunction openWin3() {myWin= open("", "displayWindow","width=500,height=400,status=yes,toolbar=yes,menubar=yes");// open document for further outputmyWin.document.open();// create documentmyWin.document.write("<html><head><title>On-the-fly");myWin.document.write("</title></head><body>");myWin.document.write("<center><font size=+3>");myWin.document.write("This HTML-document has been created ");myWin.document.write("with the help of JavaScript!");myWin.document.write("</font></center>");myWin.document.write("</body></html>");// close the document - (not the window!)myWin.document.close();}// --></script></head><body><form><input type=button value="On-the-fly" onClick="openWin3()"></form></body></html>
Output:
37
38
Program 9:
Develop static pages (using only HTML) of an online Book store. The pages should resemble :www.amazon.com. The website should consist the following pages.
Home page Registration and user Login User profile page Books catalog Shopping cart Payment by credit cardtt Order Conformation
Validate the Registration, user login, user profile and payment by credit card pages using JavaScript.
Code:
Main.html:
<frameset rows=”25%, 75 %”> <frame src=”top.html” name=”top”> <frameset cols=”25%,75%”> <frame src=”left.html” name=”left”> <frame src=”right.html” name=”right”> </frameset> </frameset>Top.html: <html> <body bgcolor=”pink”> <br><br> <marquee><h1 align=”center”><b><u>ONLINE BOOK STORAGE</u></b></h1></marquee> </body> </html>Right.html: <html> <body bgcolor=”pink”> <br><br><br><br><br> <h2 align=”center”> <b><p> welcome to online book storage. Press login if you are having id otherwise press registration. </p></b></h2></body></html>Left.html: <html> <body bgcolor=”pink”> <h3> <ul>
function validate(){var flag=1;if(document.myform.id.value==""||document.myform.pwd.value==""){flag=0;}if(flag==1){alert("VALID INPUT");}else{alert("INVALID INPUT");document.myform.focus();}}</script><form name="myform"><div align="center"><pre>LOGIN ID :<input type="text" name="id"><br>PASSWORD:<input type="password" name="pwd"></pre><br><br></div><br><br><div align="center"><input type="submit" value="ok" onClick="validate()"> <input type="reset" value="clear" ></form></body></html>
45
46
47
48
49
INTRODUCTION TO XML,DTD :
XML:XML was designed to transport and store data.
HTML was designed to display data.
What is XML?
XML stands for EXtensible Markup Language XML is a markup language much like HTML XML was designed to carry data, not to display data XML tags are not predefined. You must define your own tags XML is designed to be self-descriptive XML is a W3C Recommendation
The Difference Between XML and HTML
XML is not a replacement for HTML.
XML and HTML were designed with different goals:
XML was designed to transport and store data, with focus on what data is.
HTML was designed to display data, with focus on how data looks.
HTML is about displaying information, while XML is about carrying information.
XML Does not DO Anything
Maybe it is a little hard to understand, but XML does not DO anything. XML was created to structure, store, and transport information.
The following example is a note to Tove from Jani, stored as XML:
<note><to>Tove</to><from>Jani</from><heading>Reminder</heading><body>Don't forget me this weekend!</body></note>
50
The note above is quite self descriptive. It has sender and receiver information, it also has a heading and a message body.
But still, this XML document does not DO anything. It is just pure information wrapped in tags. Someone must write a piece of software to send, receive or display it.
XML is Just Plain Text
XML is nothing special. It is just plain text. Software that can handle plain text can also handle XML.
However, XML-aware applications can handle the XML tags specially. The functional meaning of the tags depends on the nature of the application.
With XML You Invent Your Own Tags
The tags in the example above (like <to> and <from>) are not defined in any XML standard. These tags are "invented" by the author of the XML document.
That is because the XML language has no predefined tags.
The tags used in HTML (and the structure of HTML) are predefined. HTML documents can only use tags defined in the HTML standard (like <p>, <h1>, etc.).
XML allows the author to define his own tags and his own document structure.
XML is Not a Replacement for HTML
XML is a complement to HTML.
It is important to understand that XML is not a replacement for HTML. In most web applications, XML is used to transport data, while HTML is used to format and display the data.
51
XML is a software- and hardware-independent tool for carrying information.
XML is Everywhere
We have been participating in XML development since its creation. It has been amazing to see how quickly the XML standard has developed, and how quickly a large number of software vendors has adopted the standard.
XML is now as important for the Web as HTML was to the foundation of the Web.
XML is everywhere. It is the most common tool for data transmissions between all sorts of applications, and is becoming more and more popular in the area of storing and describing information.
XML Separates Data from HTML
If you need to display dynamic data in your HTML document, it will take a lot of work to edit the HTML each time the data changes.
With XML, data can be stored in separate XML files. This way you can concentrate on using HTML for layout and display, and be sure that changes in the underlying data will not require any changes to the HTML
XML Simplifies Data Sharing
In the real world, computer systems and databases contain data in incompatible formats.
XML data is stored in plain text format. This provides a software- and hardware-independent way of storing data.
This makes it much easier to create data that different applications can share.
XML Simplifies Data Transport
With XML, data can easily be exchanged between incompatible systems.
One of the most time-consuming challenges for developers is to exchange data between incompatible systems over the Internet.
Exchanging data as XML greatly reduces this complexity, since the data can be read by different incompatible applications.
52
XML Simplifies Platform Changes
Upgrading to new systems (hardware or software platforms), is always very time consuming. Large amounts of data must be converted and incompatible data is often lost.
XML data is stored in text format. This makes it easier to expand or upgrade to new operating systems, new applications, or new browsers, without losing data.
XML Makes Your Data More Available
Since XML is independent of hardware, software and application, XML can make your data more available and useful.
Different applications can access your data, not only in HTML pages, but also from XML data sources.
With XML, your data can be available to all kinds of "reading machines" (Handheld computers, voice machines, news feeds, etc), and make it more available for blind people, or people with other disabilities.
XML is Used to Create New Internet Languages
A lot of new Internet languages are created with XML.
Here are some examples:
XHTML the latest version of HTML WSDL for describing available web services WAP and WML as markup languages for handheld devices RSS languages for news feeds RDF and OWL for describing resources and ontology SMIL for describing multimedia for the web
DTD :
53
A Document Type Definition (DTD) defines the legal building blocks of an XML document. It defines the document structure with a list of legal elements and attributes.
A DTD can be declared inline inside an XML document, or as an external reference.
Internal DTD Declaration
If the DTD is declared inside the XML file, it should be wrapped in a DOCTYPE definition with the following syntax:
<!DOCTYPE root-element [element-declarations]>
External DTD Declaration
If the DTD is declared in an external file, it should be wrapped in a DOCTYPE definition with the following syntax:
<!DOCTYPE root-element SYSTEM "filename">
Why Use a 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.
Program 10:
54
Develop a DTD and a xml document for employees in an organisation and check whether the document is valid or not ?
Code:
Emps.dtd:-
<!ENTITY % text "#PCDATA"><!ELEMENT emps (emp+,dept)><!ELEMENT emp (name,sal,desig)><!ELEMENT name (first-name,last-name)><!ELEMENT first-name (%text;)><!ELEMENT last-name (%text;)><!ELEMENT sal (%text;)><!ELEMENT desig (%text;)><!ELEMENT dept (dept-name,desc)><!ELEMENT dept-name (%text;)><!ELEMENT desc (%text;)><!ATTLIST emp empno ID #REQUIRED><!ATTLIST emp managerid IDREF #IMPLIED><!ATTLIST emp working (yes | no) 'yes'><!ATTLIST dept deptno ID #REQUIRED>
If there are no errors in xml document the you will get“ document validated “ messageOtherwise you will get the errors in your xml document
Program 11:
56
Create and save anXML document at the server,which contains 10 users Information.write a
Program,which takes user Id as an input and returns the User details by taking the user
information from the XML document.
PROCEDURE:
Step 1:
Copy xmlbeans – current-src.zip to a directory(E:\tr)
Then extract the content of above jar file using the following command
E:\tr> jar XVF Xmlbeans-current-src.zip
Step 2:
Search for the ant tool for complining all the extracted java files and set that to path
Set Path=C:\j2sdkee1.4\bin;%Path%;
Step 3:
Move to the directory Xmlbeans-1.0.3 make sure that there is no folder with the name
build.
Then give the command
E:\tr\Xmlbeans-1.0.3>ant
As part of the Xmlbeans-1.0.3/bin we get the tool called scomp(schema compiler)
Step 4:
Create the Xml directory in E:\
Then given the command
E:\Xmlb>set path=E:\tr\Xmlbeans-1.0.3\bin;%path%
E:\Xmlb>scomp
No error means Xmlbeans is loaded correctly.
Create src,cls directories under Xmlb.
Step 5:
57
Open the Xmlspy>file>new>xsdfile>ok
Schema design > schema setting>
Select notarget namespace
Give the root element name as user then right click and select add child/sequence then right click select add child/element and give the name as user id repeat this,and add the elements as
Userid User— name
Address --------- city
State
Save this as user.xsd in E:\xmlb directory
E:\xmlb>scomp--- srg –d cls user.xsd
Output:
1 XYZ
III I.T Rajahmundry
A.P
58
Program 12:
write a program to display information from an xml document
Code:
import org.w3c.dom.*;import com.ibm.xml.parser.*;import java.io.*;public class GetEmpDetails{
public static void main(String s[])throws Exception{
Install TOMCAT web server. Convert the static webpages of assignments 2 into dynamic webpages using servlets and cookies. Hint: Users information (user id, password, credit card number) would be stored in web.xml. Each user should have a separate Shopping Cart.
PROCEDURE:
First install the tomcat into the system.Then make a subdirectly(eg., tr) in the \tomcat\webapps.Under tr create WEB-INF directory and also place the html files in this tr directory only.Next under WEB-INF create two subclasses lib,classes and web.xmlNext place all the class files under the classes and jar files(servlet-api.jar,classes12.jar etc…) under lib subdirectories.After this start tomcat by giving the following command at the instll_dir>tomcat>binCatalina.bat runAt the I.E(web browser) give the url as http;//localhost:8080//tr/htmlfile or servlet url patternPortno 8080 is assigned for the tomcat.
Web.xml
<?xml version="1.0" encoding="iso-8859-1"?><!DOCTYPE web-appPUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN""http://java.sun.com/dtd/web-app_2_3.dtd"><web-app>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><body bgcolor="pink"><br /><br /><br /><br /><br /><h1 align="center"><U>ONLINE BOOK STORAGE</U></h1><br /><br /><br /><h2 align="center"><pre><b>Welcome to online book storage.Press LOGIN if you are having idotherwise press REGISTRATION</b></pre></h2><br /><br /><pre><div align="center"><a href="/tr/login.html">LOGIN</a> <a href="/tr/reg.html">REGISTRATION</a></div></pre></body></html>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml">
}if(flag==1){pw.println("SORRY INVALID ID ALREADY EXITS TRY AGAIN WITH NEW ID<br><br>");
pw.println("<a href=\"/tr/reg.html\">press REGISTER to RETRY</a>");}else{
67
Statement stmt1=con.createStatement();stmt1.executeUpdate("insertintologin values("+names","+addr+","+no+","+id+","+pwd+")");pw.println("YOUR DETAILS ARE ENTERED<br><br>");pw.println("<a href=\"/tr/login.html\">press LOGIN to login</a>");
}pw.println("</body></html>");
}catch(Exception e){
resp.sendError(500,e.toString());}
}}
Catlog.java
import java.sql.*;import java.io.*;import java.util.*;import javax.servlet.*;import javax.servlet.http.*;public class login extends HttpServlet{
public void service(HttpServletRequest req,HttpServletResponse resp)throws ServletException,IOException{
pw.println("SORRY INVALID ID TRY AGAIN ID<br><br>");pw.println("<a href=\\"/tr/order.html\\">press HERE to RETRY</a>");
}else{
Statement stmt2=con.createStatement();String s="select cost from book where title="+title+"";ResultSet rs1=stmt2.executeQuery(s);int flag1=0;while(rs1.next()){
flag1=1;x=Integer.parseInt(rs1.getString(1));amount=count*x;pw.println("AMOUNT :"+amount+"<br><br><br><br>");Statement stmt1=con.createStatement();stmt1.executeUpdate("insertintodetails values('"+id+",'"+title+"'+amount+'","'+cno+'")"');pw.println("YOUR ORDER has taken<br>");
71
}if(flag1==0){
pw.println("SORRY INVALID ID TRY AGAIN ID<br><br>");pw.println("<a href=\\"/tr/order.html\\">press HERE to RETRY</a>");
}}pw.println("</body></html>");con.close();
}catch(Exception e){
resp.sendError(500,e.toString());}
}
Output:
72
73
74
INTRODUCTION TO SERVLETS:
What Is a Servlet?
A servlet is a Java programming language class that is used to extend the capabilities of servers that host applications access via a request-response programming model. Although servlets can respond to any type of request, they are commonly used to extend the applications hosted by web servers. For such applications, Java Servlet technology defines HTTP-specific servlet classes.
The javax.servlet and javax.servlet.http packages provide interfaces and classes for writing servlets. All servlets must implement the Servlet interface, which defines life-cycle methods. When implementing a generic service, you can use or extend the GenericServlet class provided with the Java Servle API. The HttpServlet class provides methods, such as doGet and doPost, for handling HTTP-specific services.
Servlet Life Cycle
The life cycle of a servlet is controlled by the container in which the servlet has been deployed. When a request is mapped to a servlet, the container performs the following steps.
1. If an instance of the servlet does not exist, the web containera. Loads the servlet class.b. Creates an instance of the servlet class.c. Initializes the servlet instance by calling the init method. Initialization is
covered in Initializing a Servlet.2. Invokes the service method, passing request and response objects..
If the container needs to remove the servlet, it finalizes the servlet by calling the servlet's destroy method.
75
Program 14:
Program To Explain LifeCycle Of Servlet
Code:
hello.html:-
<html><body>
<center><u><h3>Program to demonstrate lifecycle of servlet</h3></u></center>
<?xml version="1.0" encoding="ISO-8859-1"?><!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"><web-app> <!-- Define servlets that are included in the example application --> <servlet> <servlet-name>HS</servlet-name> <servlet-class>com.nit.hello.HelloServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>HS</servlet-name> <url-pattern>/sayhello</url-pattern> </servlet-mapping> </web-app>
/WEB-INF/classes/HelloServlet.java:-
76
package com.nit.hello;import javax.servlet.*;import java.io.*;public class HelloServlet implements Servlet{
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"><web-app> <!-- Define servlets that are included in the example application --> <servlet> <servlet-name>HS</servlet-name> <servlet-class>com.nit.reqdata.RequestData</servlet-class> </servlet> <servlet-mapping> <servlet-name>HS</servlet-name> <url-pattern>/s1</url-pattern> </servlet-mapping> </web-app>
/WEB-INF/classes/RequestData.java:-package com.nit.reqdata;import java.io.*;import javax.servlet.*;public class RequestData extends GenericServlet{ public void service(ServletRequest req,ServletResponse res)throws ServletException,IOException
{ String fn=req.getParameter("firstname");String ln=req.getParameter("lastname");String fathername=req.getParameter("fathername");res.setContentType("text/html");PrintWriter pw=res.getWriter();pw.println("<html><body>");pw.println("<center><u><h3>Program to get the request data from the
client</h3></u></center>");pw.println("<center><u><h3>The Given Information are</h3></u></center>");pw.println("FirstName: "+fn+"<br/>");pw.println("LastName: "+ln+"<br/>");pw.println("FatherName: "+fathername+"<br/>");pw.println("</html></body>");
}}Output:
80
Cookies:-
81
Cookie is a small data unit which can be saved into client machine .cookies are supported by HTTP protocol i.e., the client side http adapter can take the instructions from the server(in the response message) and save the data given by the server.
Each and every cookie consist of following information:-
name of the cookie
value of the cookie
maximum age(or time) a cookie can be alive on client machine
path
domain name
To present this cookie information to the servlet , servlet container uses javax.servlet.http.Cookie abstract class
In HttpServletRequest class the following method is used to get the cookies associated with current request :-
Cookie[] getCookies()
In HttpServletResponse class the following method is used to add a cookie to the response:-
addCookie(cookie)
some of the methods Cookie class are :-
String getName() - returns the name of the cookie
String getValue() - returns the value of the cookie
setMaxage(int) - sets the maximum time for which the cookie is alive on the client
int getMaxage() – gets maxium age of a cookie
Program 16:
82
Program to explain cookies concept in servlets
Code:
Firstform.html:-
<html><body>
<center><u><h3>Program to demonstrate use of Cookies</h3></u></center>
<form method="get" action="ser1"><center><h3> <u>Enter cookie name and values
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"><web-app> <!-- Define servlets that are included in the example application --> <servlet> <servlet-name>servlet1</servlet-name> <servlet-class>FirstServlet</servlet-class> </servlet> <servlet> <servlet-name>servlet2</servlet-name> <servlet-class>SecondServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>servlet1</servlet-name> <url-pattern>/ser1</url-pattern> </servlet-mapping>
pw.println("<center><h3> <u><a href=\"./FirstForm.html\">Click here to add more cookies</a> </u></h3></center>");
pw.println("</html></body>");}
}
Output:
85
86
87
88
INTRODUCTION TO SESSION MANAGAMENT :Maintaining Client State
Many applications require that a series of requests from a client be associated with one another. Web-based applications are responsible for maintaining such state, called a session, because HTTP is stateless. To support applications that need to maintain state, Java servlet technology provides an API for managing sessions and allows several mechanisms for implementing sessions.
Accessing a Session
Sessions are represented by an HttpSession object. You access a session by calling the getSession method of a request object. This method returns the current session associated with this request, or, if the request does not have a session, it creates one.
Associating Objects with a Session
You can associate object-valued attributes with a session by name. Such attributes are accessible by any web component that belongs to the same web context and is handling a request that is part of the same session.
Notifying Objects That Are Associated with a Session
Recall that your application can notify web context and session listener objects of servlet life-cycle events (Handling Servlet Life-Cycle Events). You can also notify objects of certain events related to their association with a session such as the following:
When the object is added to or removed from a session. To receive this notification, your object must implement the javax.servlet.http.HttpSessionBindingListener interface.
When the session to which the object is attached will be passivated or activated. A session will be passivated or activated when it is moved between virtual machines or saved to and restored from persistent storage. To receive this notification, your object must implement the javax.servlet.http.HttpSessionActivationListener interface.
Session Management
Because there is no way for an HTTP client to signal that it no longer needs a session, each session has an associated timeout so that its resources can be reclaimed. The timeout period can be accessed by using a session's [get|set]MaxInactiveInterval methods.
89
To ensure that an active session is not timed out, you should periodically access the session via service methods because this resets the session's time-to-live counter.
When a particular client interaction is finished, you use the session's invalidate method to invalidate a session on the server side and remove any session data.
Session Tracking
A web container can use several methods to associate a session with a user, all of which involve passing an identifier between the client and the server. The identifier can be maintained on the client as a cookie, or the web component can include the identifier in every URL that is returned to the client.
If your application uses session objects, you must ensure that session tracking is enabled by having the application rewrite URLs whenever the client turns off cookies. You do this by calling the response's encodeURL(URL) method on all URLs returned by a servlet. This method includes the session ID in the URL only if cookies are disabled; otherwise, it returns the URL unchanged.
90
Program 17:
Program to explain session tracking in servlets
Code :
Firstform.html:-
<html><body>
<center><u><h3>Program to demonstrate Session Tracking</h3></u></center>
<?xml version="1.0" encoding="ISO-8859-1"?><!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"><web-app> <!-- Define servlets that are included in the example application --> <servlet> <servlet-name>servlet1</servlet-name> <servlet-class>FirstServlet</servlet-class> </servlet> <servlet> <servlet-name>servlet2</servlet-name> <servlet-class>SecondServlet</servlet-class> </servlet>
fathername=(String)hs.getAttribute("fathername");pw.println("<html><body>");pw.println("<center><u><h3>Program to demonstrate
Session Tracking</h3></u></center>");pw.println("<center><h3>The Details Given by you
are</h3></center>");pw.println("First Name
is:<h3>"+firstname+"</h3><br/>");pw.println("Last Name is:<h3>"+lastname+"</h3><br/>");pw.println("Father name
is:<h3>"+fathername+"</h3><br/>");pw.println("Date of Birth:<h3>"+dob+"</h3><br/>");pw.println("address is:<h3>"+address+"</h3><br/>");
}}
93
Output :
94
95
INTRODUCTION TO JAVA SERVER PAGES :
What Is a JSP Page?
A JSP page is a text document that contains two types of text: static data, which can be expressed in any text-based format (such as HTML, SVG, WML, and XML, and JSP elements, which construct dynamic content.
The recommended file extension for the source file of a JSP page is .jsp. The page can be composed of a top file that includes other files that contain either a complete JSP page or a fragment of a JSP page. The recommended extension for the source file of a fragment of a JSP page is .jspf.
The JSP elements in a JSP page can be expressed in two syntaxes--standard and XML--though any given file can use only one syntax. A JSP page in XML syntax is an XML document and can be manipulated by tools and APIs for XML documents.
The Life Cycle of a JSP Page
A JSP page services requests as a servlet. Thus, the life cycle and many of the capabilities of JSP pages (in particular the dynamic aspects) are determined by Java Servlet technology.
When a request is mapped to a JSP page, the web container first checks whether the JSP page's servlet is older than the JSP page. If the servlet is older, the web container translates the JSP page into a servlet class and compiles the class. During development, one of the advantages of JSP pages over servlets is that the build process is performed automatically.
Translation and Compilation
During the translation phase each type of data in a JSP page is treated differently. Static data is transformed into code that will emit the data into the response stream. JSP elements are treated as follows:
Directives are used to control how the web container translates and executes the JSP page.
Scripting elements are inserted into the JSP page's servlet class. See Chapter 16 for details.
Expression language expressions are passed as parameters to calls to the JSP expression evaluator.
jsp:[set|get]Property elements are converted into method calls to JavaBeans components.
jsp:[include|forward] elements are converted into invocations of the Java Servlet API.
The jsp:plugin element is converted into browser-specific markup for activating an applet.
Both the translation and the compilation phases can yield errors that are observed only when the page is requested for the first time. If an error is encountered during either phase, the server will return JasperException and a message that includes the name of the JSP page and the line where the error occurred.
After the page has been translated and compiled, the JSP page's servlet (for the most part) follows the servlet life cycle described in Servlet Life Cycle:
1. If an instance of the JSP page's servlet does not exist, the containera. Loads the JSP page's servlet classb. Instantiates an instance of the servlet classc. Initializes the servlet instance by calling the jspInit method
2. The container invokes the _jspService method, passing request and response objects.
If the container needs to remove the JSP page's servlet, it calls the jspDestroy method.
Execution
You can control various JSP page execution parameters by using page directives. The directives that pertain to buffering output and handling errors are discussed here. Other directives are covered in the context of specific page-authoring tasks throughout the chapter.
Buffering
When a JSP page is executed, output written to the response object is automatically buffered. You can set the size of the buffer using the following page directive:
<%@ page buffer="none|xxxkb" %>
A larger buffer allows more content to be written before anything is actually sent back to the client, thus providing the JSP page with more time to set appropriate status codes and headers or to forward to another web resource. A smaller buffer decreases server memory load and allows the client to start receiving data more quickly.
97
Handling Errors Any number of exceptions can arise when a JSP page is executed. To specify that the web container should forward control to an error page if an exception occurs, include the following page directive at the beginning of your JSP page:
<%@ page errorPage="file_name" %>
The following page directive at the beginning of JSP page indicates that it is serving as an error page
<%@ page isErrorPage="true" %>
JavaBeans Components
JavaBeans components are Java classes that can be easily reused and composed together into applications. Any Java class that follows certain design conventions is a JavaBeans component.
JavaServer Pages technology directly supports using JavaBeans components with standard JSP language elements. You can easily create and initialize beans and get and set the values of their properties.
JavaBeans Component Design Conventions JavaBeans component design conventions govern the properties of the class and govern the public methods that give access to the properties. A JavaBeans component property can be
Read/write, read-only, or write-only Simple, which means it contains a single value, or indexed, which means it
represents an array of values
A property does not have to be implemented by an instance variable. It must simply be accessible using public methods that conform to the following conventions:
For each readable property, the bean must have a method of the form PropertyClass getProperty() { ... }
For each writable property, the bean must have a method of the form setProperty(PropertyClass pc) { ... }
In addition to the property methods, a JavaBeans component must define a constructor that takes no parameters.
98
Creating and Using a JavaBeans Component
To declare that your JSP page will use a JavaBeans component, you use a jsp:useBean element. There are two forms:
The second form is used when you want to include jsp:setProperty statements, described in the next section, for initializing bean properties.
The jsp:useBean element declares that the page will use a bean that is stored within and is accessible from the specified scope, which can be application, session, request, or page. If no such bean exists, the statement creates the bean and stores it as an attribute of the scope object .The value of the id attribute determines the name of the bean in the scope and the identifier used to reference the bean in EL expressions, other JSP elements, and scripting expressions.). The value supplied for the class attribute must be a fully qualified class name. Note that beans cannot be in the unnamed package. Thus the format of the value must be package_name.class_name.
The following element creates an instance of mypkg.myLocales if none exists, stores it as an attribute of the application scope, and makes the bean available throughout the application by the identifier locales:
The standard way to set JavaBeans component properties in a JSP page is by using the jsp:setProperty element. The syntax of the jsp:setProperty element depends on the source of the property value. Table 12-3 summarizes the various ways to set a property of a JavaBeans component using the jsp:setProperty element.
Table 12-3 Valid Bean Property Assignments from String Values
1. beanName must be the same as that specified for the id attribute in a useBean element.
2. There must be a setPropName method in the JavaBeans component.
3. paramName must be a request parameter name.
A property set from a constant string or request parameter must have one of the types listed in Table 12-4. Because constants and request parameters are strings, the web
100
container automatically converts the value to the property's type; the conversion applied is shown in the table.
String values can be used to assign values to a property that has a PropertyEditor class. When that is the case, the setAsText(String) method is used. A conversion failure arises if the method throws an IllegalArgumentException.
The value assigned to an indexed property must be an array, and the rules just described apply to the elements.
Table 12-4 Valid Property Value Assignments from String Values
Property Type Conversion on String Value
Bean Property Uses setAsText(string-literal)
boolean or Boolean As indicated in java.lang.Boolean.valueOf(String)
byte or Byte As indicated in java.lang.Byte.valueOf(String)
char or Character As indicated in java.lang.String.charAt(0)
double or Double As indicated in java.lang.Double.valueOf(String)
int or Integer As indicated in java.lang.Integer.valueOf(String)
float or Float As indicated in java.lang.Float.valueOf(String)
long or Long As indicated in java.lang.Long.valueOf(String)
short or Short As indicated in java.lang.Short.valueOf(String)
Object new String(string-literal)
You use an expression to set the value of a property whose type is a compound Java programming language type. The type returned from an expression must match or be castable to the type of the property.
101
Retrieving JavaBeans Component Properties
The main way to retrieve JavaBeans component properties is by using the JSP EL expressions. Thus, to retrieve a book title, the Duke's Bookstore application uses the following expression:
${bookDB.bookDetails.title}
Another way to retrieve component properties is to use the jsp:getProperty element. This element converts the value of the property into a String and inserts the value into the response stream:
Note that beanName must be the same as that specified for the id attribute in a useBean element, and there must be a getPropName method in the JavaBeans component. Although the preferred approach to getting properties is to use an EL expression, the getProperty element is available if you need to disable expression evaluation.
102
Program 18:
Program to explain accessing java beans from java server pages
Code:
Firstpage.html:-
<html><body>
<center><u><h3>Program to demonstrate accessing javabeans from jsp</h3></u></center>
Redo the previous task using JSP by converting the static web pages of assignments 2 into dynamic web pages. Create a database with user information and books information and books information. The books catalogue should be dynamically loaded from the database. Follow the MVC architecture while doing the website.
PROCEDURE:
1) Create your own directory under tomcat/webapps (e.g. tr1)
2) Copy the html files in tr1
3) Copy the jsp files also into tr1
4) Start tomcat give the following command
Catalina.bat run
At install-dir/bin
5) at I.E give url as http://localhost:8081/tr1/main.html
Main.html:
<html>
<body bgcolor=”pink”>
<br><br><br><br><br><br>
<h1 align=”center”>>U>ONLINE BOOK STORAGE</u></h1><br><br><br>
out.println(“SORRY INVALID BOOK TRY AGAIN <br><br>”);
out.println(“<a href=\”/tr1/order.html\”>press HERE to RETRY </a>”);
}
} out.println (“</body></html>”);%>
117
118
119
120
Program 20:
Implement the "Hello World!" program using JSP Struts Framework
PROCEDURE:
Step 1:in tomcat install directoryOpen tomcat/webapps Create a subdirectory(ts)Copy the struts-blank.war fileAt that directory path in cmd give the command asJar xvf struts-blank.warStep 2:
create a directory (work in e:\) and copy struts.jar,servelet-appi.jar into work d directory.Then set the classpath asset classpath=struts.jar;servlet-api.jar;then copy the ActionOne.class file to webapps/ts/WEB-INF/classes
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:nit","scott","tiger");Statement st=con.createStatement();ResultSet rs=st.executeQuery("select * from bank");while(rs.next()){ int accno=rs.getInt(1);
String name=rs.getString(2);double bal=rs.getDouble("bal");System.out.println(accno + "\t" + name + "\t" + bal + "\n");
}con.close();
}}Output:Before executing this program create a database table bank as follows :Create table bank(accno number,name varchar2(50),bal number)And insert some data into that table as follows :Insert into bank values(101,satish,16000)Insert into bank values(102,Prasad,20000)Javac ResultSetEx.javaJava ResultSetEx101 satish 16000102 prasad 20000
124
Program 22:Program to show how to use PreparedStatement to insert data into database table
Code :
import java.sql.*;public class InsertEx{
public static void main(String args[]) throws Exception{
Output:Before executing this program create a database table myemp as follows :Create table myemp(empno number,empname varchar2(50))Javac InsertExJava InsertEx
125
Program 23:
Program to explain ResultSetMetaData
Code:
import java.sql.*;import java.util.*;public class RSMDEX{
public static void main(String s[])throws Exception{
Before executing this program create a database table bank as follows :Create table bank(accno number,name varchar2(50),bal number)And insert some data into that table as follows :Insert into bank values(101,satish,16000)Insert into bank values(102,Prasad,20000)Insert into bank values(103,babu,30000)Javac RSMDEX.javaJava RSMDEX--------------------------------------------Accno name bal---------------------------------------101 satish 16000102 prasad 20000103 BABU 30000