You are on page 1of 70

MOHAMED SATHAK A.

J COLLEGE OF ENGINEERING
(Approved by AICTE, New Delhi and Affiliated to Anna University)
34, Old Mahabalipuram Road, Egattur, Chennai – 603 103.
ISO 9001: 2008 Certified Institution

(ACADEMIC YEAR: 2022- 2023)

CS8661-INTERNET PROGRAMMING LABORATORY

Name :

Register Number :

Department : COMPUTER SCIENCE AND ENGINEERING

Year/Semester : III /VI

(ANNA UNIVERSITY: CHENNAI - 600 025)

1
MOHAMED SATHAK A.J COLLEGE
OFENGINEERING
(Approved by AICTE, New Delhi and Affiliated to Anna University) 34, Old
Mahabalipuram Road, Egattur, Chennai – 603 103.

Sponsored By: MOHAMED SATHAK TRUST, Chennai – 600 034.

BONAFIDE CERTIFICATE

This is to certify that this is the Bonafide Record of work done by


Mr. /Ms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Register Number .................................................................................... of

III YEAR / VI Semester –COMPUTER SCIENCE AND ENGINEERING


in the CS8661-INTERNET PROGRAMMING LABORATORY during the
academic year 2022-2023.

Staff In-Charge Head of the Department

Submitted for the Anna University B.E Practical Examination held on.
...............................

Internal Examiner External Examiner

2
MARKS PAGE SIGNA
S.NO DATE TITLE
(25) NO. TURE
Create a web page with the following using HTML
1 a. To embed a map in a webpage
b. To fix the hot spots in that map
c. Show all the related information when the hot spots are clicked
Create a web page with the following.
2 a. Cascading stylesheets.
b. Embedded stylesheets.
Use our college information for the web pages.
3 Validate the Registration, user login, user profile and payment by
credit card pages using JavaScript
Write programs in Java using Servlets:
4 i. To invoke servlets from HTML forms
ii. To invoke servlets from Applets
Write programs in Java to create three-tier applications using servlets
5 for conducting on-line examination for displaying student mark list.
Assume that student information is available in a database which has
been stored in a database server.
Install TOMCAT web server. Convert the static webpages of
programs 1&2 into dynamic web pages using servlets (or JSP) and
6 cookies. Hint: Users information (user id, password, credit card
number) would be stored in web.xml. Each user should have a
separate Shopping Cart.
7 Redo the previous task using JSP by converting the static web pages
into dynamic web pages. Create a database with user information and
books information. The books catalogue should be dynamically
loaded from the database

8 Create and save an XML 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
9 Validate the form using PHP regular expression.

10 Write a web services for finding what people think by asking 500
people’s opinion for any consumer product

CONTENT BEYOND THE SYLLABUS

1. Develop an applet that receives an integer in one text field, and


computes its factorial Value and returns it in another text field,
when the button named
“Compute” is clicked.
2. Write an HTML page including any required java script that
breaks a number from one text field in a range of 0 to 999 and
shows it in another text field in words. If the number is out of
range it should show “out of range” and if it is not a number it
should show “not a number”,
in the result box.

3
CONTENT BEYOND THE SYLLABUS

S.N DATE TITLE MARKS(25) PAGE NO. SIGNATURE


O
1. Develop an applet that receives
an integer in one text field, and
computes its factorial Value and
returns it in another text field,
when the button named
“Compute” is clicked.
2. Write an HTML page including
any required java script that
breaks a number from one text
field in a range of 0 to 999 and
shows it in another text field in
words. If the number is out of
range it should show “out of
range” and if it is not a number
it should show “not a number”,
in the result box.

4
EX NO:1 WEB PAGE INCLUDING MAP AND FIXING HOTSPOT
DATE:

AIM:
• To create a webpage with the following using HTML
• To embed an image in webpage
• To fix the hotspots.
• Show all the related information when a hot spot is
clicked in the map

ALGORITHM:
Step 1: Create an html file with map tag.
Step 2: Set the source attribute of the img tag to the location of the image and also set the use map
attribute.
Step 3: Specify an area with name, shape and href set of the appropriate value.
Step 4: Repeat step3 as many hot spots you want to put in the map.
Step 5: Create html file for each and every hot spots the user will select the particular
location it shows information about it.

PROGRAM:
Indiamap.html
<HTML>
<HEAD>
<TITLE>Image Map</TITLE> </HEAD>
<BODY>
<img src="https://img.favpng.com/25/16/25/states-and-territories-of-india-mapa-polityczna-png-favpng-
reY2xBHFVM85h8QsCmvR3AfMu_t.jpg" width=600 usemap="#metroid" ismap="ismap" > <map
name="metroid" id="metroid">
<area href="TamilNadu.html" shape="circle" coords="208,606,20" title="TamilNadu"/>
<area href="Kerala.html" shape="rect" coords = "154,606,166,621" title ="Kerala" /> </map>
</BODY>
</HTML>

TamilNadu.html
<HTML><HEAD>
<TITLE>About Tamil Nadu</TITLE>
</HEAD>
<BODY>
<CENTER><H1>Tamil Nadu</H1></CENTER> <HR>
<UL>
<LI>Area : 1,30,058 Sq. Kms.</LI>
<LI>Capital : Chennai</LI>
<LI>Language : Tamil</LI>
<LI>Population : 6,21,10,839</LI> </UL><hr>
<a href='ImageMap.html'>India Map</a>
</BODY>
</HTML>

Kerala.html
<HTML>
<HEAD>
<TITLE>About Kerala</TITLE>
</HEAD>
<BODY>
<CENTER>
<H1>Kerala</H1></CENTER>
<HR>
<UL>
<LI>Area : 38,863 Sq. Kms.</LI>
<LI>Capital : Thiruvananthapuram</LI>
<LI>Language : Malayalam</LI>
<LI>Population : 3,18,38,619</LI>
</UL>
<hr>
<a href='ImageMap.html'>India Map</a>
</BODY></HTML>
5
OUTPUT:

RESULT:
Thus the program on creation of web pages using HTML is compiled and executed successfully.

6
Ex. No: 2 WEB PAGE CREATION USING STYLESHEETS
Date :

AIM:
To create a webpage with the following using html to embedded the style sheet

ALGORITHM:
INTERNAL
Step1: Create html file with the style tag, inside head tag.
Step2: Set the style such as font-family, font-size, color, left etc, for the heading h1,h2,…h6 and
respectively.
Step3: Close the head tag.
Step4: Specify the heading and information required inside the body tag.
Step5: Close the opened tag.
INLINE
Step1: Use the style attribute within the element tags
Step2: Set style such as font-family, font-size, color, left etc,
Step3: Close the style attribute (ie) style=”…” .

EXTERNAL
Step1: Create a CSS file style.css
Step2:Include the styles for HTML elements
Step3: Link the css file in the html file.

PROGRAM:
Style.css:
h3
{
font-family:arial;
font-size:20;
color:cyan
}
table{
border-color:green
}
td
{
font-size:20pt;
color:magenta
}

College.html:
<html>
<head>
<h1>
<center>ALL STYLE SHEETS</center>
</h1>
<title>USE of INTERNAL and EXTERNAL STYLESHEETS </title>
<link rel="stylesheet" href="style.css" type="text/css">
<style type="text/css">
.vid
{
font-family:verdana;
font-style:italic;
color:red;
text-align:center
}
.ani
{
font-family:tahoma;
font-style:italic;
8
font-size:20;
text-align:center;
}
font
7
{
font-family:georgia;
color:blue;
font-size:20
}
ul
{
list-style-type:circle
}
p
{
font-family: georgia, serif;
font-size: x-small;
}
hr
{
color: #ff9900; height: 1px
}
a:hover
{
color: #ff0000;
text-decoration: none
}
</style>
</head>
<body>
<h1 style="color:blue;margin-left:30px;">Welcome</h1>
<ol style="list-style-type:lower-alpha">
<b>Mohammed Sathak A J College of Engineering </b>
<br>
<br>
<br>
<li> EEE</li>
<li> ECE </li>
<li> MECH</li>
<li> CSE</li>
</ol>
<p style="font-size:20pt;color:purple">Details</p>
<p class="ani">Mohammed Sathak A J College of engineering <br>It is approved by AICTE(All India Council
for
Technical Education). It is affliated to Anna University.<br></p>
<h2 class="vid"> Mohammed Sathak A J college of engineering </h2> <br>
<font>It is an ISO certified Institution
</font>
<br>
<br>
<font>
<h2>List of Courses offered</h2>
<ul>
<li>Computer Science and Engineering</li>
<li>Ece</li>
<li>mech</li>
<li>eee</li>
</ul>
</font>
</body>
</html>

OUTPUT:

8
RESULT:
Thus the program on creation of web pages using Cascading Stylesheets
is compiled and executed successfully.

9
Ex. No: 3 VALIDATION USING JAVASCRIPT
Date :

AIM:
To Validate the Registration, user login, user profile and payment by credit card pages using JavaScript.

PROGRAM:

Online.html
<html>
<head><title> payment</title>
<SCRIPT LANGUAGE="JAVASCRIPT">
function essentials_of_validation(form1)
{
var current=new Date(); varreturn_value=true;
var username=form1.txtusername.value; varpassword1=form1.txtpassword1.value; vara=form1.dd.value;
var b=form1.mm.value; var c=form1.yyyy.value; if(isNaN(username))
{
window.alert("Not a valid account number");
}
if(a<32 && b<13&& c>=current.getFullYear())
{
if(c>current.getFullYear())
{
window.alert(" you are validated");
}
else if(c=current.getFullYear())
{
if(b>current.getMonth())
{
window.alert(" you are validated");
}
else if(b=current.getMonth())
{
if(a>current.getDate())
{
window.alert("you are validated");
}
}
}
else
{
window.alert("Your card has expired");
}}
else{
window.alert(" card has expired");
}

}
</script>
</head>

10
<body bgcolor="pink">
<marquee><strong>Enjoy the Shopping with special Offers</strong></marquee>
<form name="form1" onSubmit="essentials_of_validation(this)">
<font size="+2"> Payment Through
<br>
<input name="pay" type="radio" >Credit card
<input name="pay" type="radio" >Debit card
<br> Bank
<select name="bank">
<option selected>sbi
<option>HSBC
<option>ICICI
<option>others
</select>
<br>
Account/Card number:
<input name="txtusername" type="textbox">
<br>
Net banking id/Password<input name="txtpassword1" type="password">
<br>
Enter date of expiryof account/card<input name="dd" type="text" size=2>(dd)
<input name="mm" type="text" size=2>(mm)
<input name="yyyy" type="text" size=4>(yyyy)
<br>
<input type="submit" value="Accept">
<input type="reset" value="Reject">
</form>
<A Href="e:\home.html">Home</A>
<br><A Href="e:\shop.html">back</A>
</body>
</html>

Home.html
<html>
<head><title>HOME PAGE</title></head>
<body>
<A href="registration.html">Register</A>
<A href="user.html">Login</A>
<!--<A href="online.html">Payment</A>-->
</body>
</html>

User.html
<html>
<head>
<SCRIPT LANGUAGE="JAVASCRIPT">
function essentials_of_validation(form1)
{
var return_value=true;
var username=form1.txtusername.value; var password1=form1.txtpassword1.value; var
password2=form1.txtpassword2.value; if(username.length< 8)
{
11
return_value=false;
window.alert("user name less thn 8 chars");
}
if(password1.length<6)
{
return_value=false;
window.alert(" pwd should be > 6 char's "); form1.txtpassword1.value=""; form1.txtpassword2.value="";
}
if(password1!=password2){ return_value=false;
window.alert("ur password mismatched "); form1.txtpassword1.value=""; form1.txtpassword2.value="";

}
return return_value;
}
</script>
</head>
<body bgcolor="skyblue">
<marquee><b><u><font face="comic sans ms" color="light blue">login here</font></u></b></marquee>
<form name="form1" onSubmit="essentials_of_validation(this)"> Username <input type="text"
name="txtusername" size=20>
<br>Password: <input type="password" name="txtpassword1" size=20>
<br>Confirm password:<input type="password" name="txtpassword2" size=20>
<br><br>
<input type="submit" value="submit">
<input type="reset" value="reset">
</form>
</body>
</html>

Registration.html
<html>
<head><title> register</title>
<SCRIPT LANGUAGE="JAVASCRIPT">
function essentials_of_validation(form1)
{
alert("inside");
var return_value=true;
var username1=form1.txtusername1.value;
var username2=form1.txtusername2.value;
var password1=form1.txtpassword1.value;
var password2=form1.txtpassword2.value;
var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if(username1.length < 8){
return_value=false;
window.alert("user name less than 8 chars"); }
if(username1==username2) {
return_value=false;
window.alert("both ids are same"); form1.txtusername2.value="";}
if(password1.length<6){
return_value=false;
window.alert(" pwd should be > 6 char's "); form1.txtpassword1.value=""; form1.txtpassword2.value="";
}
12
if(password1!=password2){ return_ value=false;
window.alert("ur password mismatched ");
form1.txtpassword1.value="";
form1.txtpassword2.value="";
}

if (username1.match(mailformat))
{
alert("You have entered an invalid email address!")
return_value=false;
}
return return_value;
}

</script>
</head>
<body BGCOLOR="YELLOW">
<CENTER><u>
<marquee><font name="mistral" size="+1">REGISTRATION FORM</font></marquee>
</u></center>
<form name="form1" onSubmit="essentials_of_validation(this)">
Name:<input name="name" type="text" size="10">
<br>
Age:<input type="text" size="3">
<br> Sex:<br>
<input name ="gen" type="radio" value="male">male
<input name="gen" type="radio" value="female">female
<br>
Address:
<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<tex
tarea name="address" rows="3" cols="10"></textarea>
<br>
Enter e-mail id :<sup>*</sup>
<input type="text" name="txtusername1"8size="15"><br>

Password:<sup>*</sup>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="Password" name="txtpassword1" size="15">(password
should exceed 6 characters)
<br>
Confirm password:<input type="password" name="txtpassword2" size=20>
<br>
Alternate mail:<sup>*</sup>
<input type="text" name="txtusername2" size="15">
<br>
Known This Site Through
<br>
<input name="things" type="checkbox" value="srts"> internet
<input name="things" type="checkbox" value="sp">newspapers
<input name="things" type="checkbox" value="spor"> friends
<br>
Rate ur site
13
<select name="rating">
<option selected>good
<option>average
<option>bad
<option>no rating
</select><br>
Enter the code<input name="code" type="text" size="5">
<table border="1" width="10%" height="10%">
<thead><tr><th> 1123</th></tr>
</thead>
</table>
<br>
<input type="submit" value="submit ">
<input type ="reset" value="clear ur entries">
</form>
<font size="+1">
<A Href="E:\home.html">Home</A>
<A Href="E:\user.html">Login</A>
</font>
</body>
</html>

OUTPUT:

14
15
RESULT:
Thus the program on validation of using Javascript is compiled and executed successfully.

16
EXP NO:
4 i). INVOKING SERVLETS FROM HTML FORMS
DATE:

AIM:
To write a html program for invoking servlet using html.

ALGORITHM:
HTML FORM:
Step1: In html program, define the html, head and title tag.
Step2: Create a html form and set it’s action to say hello pattern
Step3: Using input tag get the cost,item, quantity.
Step4: Submit the values to servlet program.
SERVLET CODE:
Step1: Create http servlet request and response object
Step2: Get the parameters cost, item, quantity from the html form.
Step3: Calculate the cost for given quantity.
Step4:Display total cost in the html document

PROCEDURE:

1. Open Netbeans IDE, Select File ->NewProject

2. Select Java Web ->Web Application, then click onNext,

17
3. Give a name to your project and click on Next,

4. and then, Click Finish

5. The complete directory structure required for the Servlet Application willbe
created automatically by the IDE.

18
6. To create a Servlet, open Source Package, right click on default packages-
>New ->Servlet.

7. Give a Name to your Servlet class file,

19
8. Now, your Servlet class is ready, and you just need to change themethod
definitions and you will good togo.

importjavax.servlet.*;
importjavax.servlet.http.*;
import java.io.*;
public class MyServlet extends HttpServlet{
public void doPost(HttpServletRequestrequest,HttpServletResponse response)
{ PrintWriter out;
int cost=Integer.parseInt(request.getParameter("cost"));
intquant=Integer.parseInt(request.getParameter("quant"));
String m=request.getParameter("item");
try{ out=response.getWriter(
);
out.println("<html><head><title>Order</title></head><body>");
out.println("Your Order for "+m+" of cost "+cost+" is accepted. Your total Bill is
Rs."+cost*quant+".");
out.println("</body></html>");
}
catch(Exception e){}
}
9. Write some code inside your Servletclass.

20
10. Create an HTML file, right click on Web Pages ->New ->HTML

10. Give it a name. We recommend you to name it index, because browser willalways
pick up the index.html file automatically from a directory. Index file is read as the
first page of the web application.

11. Write some code inside your HTML file. We have created a hyperlink toour
Servlet in our HTML file. (index.html)
<html>
<head>
<title>Ordering Pen</title>
<body>
<form name=order action="http://localhost:8080/first/hello" method=POST>
<input type=radio name=cost value=10>Big<br>
<input type=radio name=cost value=7>Medium<br>
<input type=radio name=costvalue=5>Small<br>
Quantity<input type=textField name=quant><br>
Item<input type=textField name=item><br>
<input type=Submit name=submit value=Submit></form></body></html>
21
12.Edit web.xml file. In the web.xml file you can see, we have specified the url-
pattern and the servlet-name, this means when hellourl is accessed our Servlet file
will be executed.
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaeehttp://java.s
un.com/xml/ns/javaee/web-app_3_0.xsd">
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<session-config>
<session-timeout> 30</session-timeout>
</session-config>
</web-app>
12.Run your application, right click on your Project and select Run

22
Output:
After Submitting:

RESULT:

Thus the program on invoking servlets from HTML form is compiled and executed
successfully.

23
EXP NO: 4 ii). INVOKING SERVLETS FROM APPLETS

DATE:

AIM:
To write a html program for invoking servlet from applet.

ALGORITHM:
HTML:
Step1: In html program, define the html, head and title tag.
Step2: Invoke the applet code using applet tag.
Step3: Close the applet, body, html tags.
SERVLET CODE:
Step1: Create http servlet request and response object
Step2: Get the parameters item, quantity from the html form.
Step3:Display the ‘order accepted’ message in the html document.
APPLET CODE:
Step1: Create a label for “enter quantity”.
Step2: Create a label for “enter item name”.
Step3: Add the action listener for submit and reset button.
Step4: Invoke the servlet code to display the output.
PROCEDURE:
1. File->NewProject
2. Java->Java ClassLibrary->Next
3. Name file asSampleApplet->Finish
4. RightClick the SampleApplet-> PropertiesWindow
5. Sources->Packaging
6. Binary Format(JDK8)->ok
7. Right Click SampleApplet->New->Others->Java->Applet->Next
8. Class name(Sample), Packages(org.me.hello)->finish
9. In Sample.java, type
importjava.awt.*;
importjava.awt.event.*;
importjava.applet.*;
import java.net.*;
public class Sample extends Applet implements ActionListener{String msg=" "; Button
submit,reset;
Label lbl1=new Label("Enter Quantity:");
Label lbl2=new Label("Enter Item Name:");
TextField item=new TextField();
TextField quant=new TextField();
public void init()
{submit=new Button("submit");
reset=new Button("reset");
add(lbl2);
add(item);
add(lbl1);
24
add(quant)
add(submi;
add(reset);
submit.addActionListener(this);
reset.addActionListener(this);
}
public void
actionPerformed(ActionEventae){String
str=ae.getActionCommand();
if(str.equals("submit"))
{msg="Submit";
try
{System.out.println("Hai");
URL myurl=new
URL("http://localhost:8080/servlet/sayhello?
item="+item.getText()+"&quant="+quant.getText());
getAppletContext().showDocument(myurl);
}
catch(Exception e)
{msg=e.toString();}}
elseif(str.equals("reset"))
{ msg="Reset";}
repaint();}
public void paint(Graphicsg)
{g.drawString(msg,6,200);}}

25
10. RightClick Sample.java->Run File (appletstarted)
11. Create WebApplication
12. File->New Project-> Java Web-> WebApplication->Next
13. Name project as HelloSampleApplet->Next->GlassFishServer->Finish
14. RightClickHelloSampleApplet->Properties->Sources->Packaging(to add jar file)
15. Click add project->Select SampleApplet->Add Project Jar File->ok
16. Right Click HelloSampleApplet->Clean andBuild
17. RightClickHelloSampleApplet->New->other->web->html->next
18. Name as MyApplet->Finish
19. MyApplet.htmlcode
<html>
<head>
<title>hai</title>
</head>
<body>
<applet code="org.me.hello.Sample" archives="SampleApplet.jar" width="450"
height="400">
</applet>
</body>
</html>

26
20. RightClick MyApplet.html->RunFile
21. Right Click SampleApplet.java->RunFile
importjavax.servlet.*;
importjavax.servlet.http.*;
import java.io.*;
public class myName extends HttpServlet
{public void doGet(HttpServletRequestrequest,HttpServletResponse response)
{PrintWriter out;
int quant=Integer.parseInt(request.getParameter("quant"));
String myItem=request.getParameter("item");
try
{out=response.getWriter();
out.println("<HTML><HEAD><TITLE>order</TITLE></HEAD><BODY>");
out.println("Your order for"+quant+" number of" +myItem+" is accepted.");
out.println("</BODY></HTML>");
}
catch(Exception e)
{System.out.println(e);
}}}
OUTPUT:
APPLET VIEWER AFTER SUBMITTING:

RESULT:

Thus the program on invoking servlets from applets is compiled and executed successfully.

27
EXP NO:
5. ONLINEEXAMINATION
DATE:

AIM:
To write programs in Java to create three-tier applications using servlets for
conducting on-line examination for displaying student mark list. Assume that student
information is available in a database which has been stored in a database server.

ALGORITHM:
Step1: Create a html file with form tag.
Step2: The form tag action=”http://localhost:8080/example/servlet/exam”.
Step3: Create a two textbox(name & seat number).
Step4: The 5 question are defined into true or false model and close the all tags.
Step5: Import the necessary packages and declare class, class name in exam.
Step6: Declare the connection, statement and result set object.
Step7: Use the deposit () for check the connection in JDBC:ODBC driver.
Step8: The data are inserting into corresponding table.
Step9: The execute update () are update the database.
Step10: Display the table in after html file compilation.

SERVLET CODE:
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class StudentServlet3 extends HttpServlet
{
String message,Seat_no,Name,ans1,ans2,ans3,ans4,ans5;
int Total=0;
Connection connect;
Statement stmt=null;
ResultSetrs=null;
public void doPost(HttpServletRequestrequest,HttpServletResponse
response) throws ServletException,IOException
{try{
String url="jdbc:odbc:NEO";
Class.forNam("sun.jdbc.odbc.JdbcOdbcDriver");
connect=DriverManager.getConnection(url," "," ");
message="Thank you for participating in online Exam";
}
catch(ClassNotFoundExceptioncnfex)
{ cnfex.printStackTrace();

}
catch(SQLExceptionsqlex)
{ system.out.println(e);
}
catch(Exception excp)
{ system.out.println(e);}
Seat_no=request.getParameter("Seat_no");
28
Name=request.getParameter("Name");
ans1=request.getParameter("group1");
ans2=request.getParameter("group2");
ans3=request.getParameter("group3");
ans4=request.getParameter("group4");
ans5=request.getParameter("group5");
if(ans1.equals("True"))
Total+=2;
if(ans2.equals("False"))
Total+=2;
if(ans3.equals("True"))
Total+=2;
if(ans4.equals("False"))
Total+=2;
if(ans5.equals("False"))
Total+=2;
try
{
Statement stmt=connect.createStatement();
String query="INSERT INTOstudent("+"Seat_no,Name,Total"+")
VALUES('"+Seat_no+"','"+Name+"','"+Total+"')";
int result=stmt.executeUpdate(query);stmt.close();
}catch(SQLException ex){
}
response.setContentType("text/html");
PrintWriter out=response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("</head>");
out.println("<body bgcolor=cyan>");
out.println("<center>"); out.println("<h1>"+message+"</h1>\n");
out.println("<h3>Yours results stored in our database</h3>");
out.print("<br><br>");
out.println("<b>"+"Participants and their Marks"+"</b>");
out.println("<table border=5>");
try
{Statement stmt=connect.createStatement(); String query="SELECT *
FROM student"; rs=stmt.executeQuery(query);
out.println("<th>"+"Seat_no"+"</th>");
out.println("<th>"+"Name"+"</th>");
out.println("<th>"+"Marks"+"</th>");
while(rs.next())
{out.println("<tr>");
out.print("<td>"+rs.getInt(1)+"</td>");
out.print("<td>"+rs.getString(2)+"</td>");
out.print("<td>"+rs.getString(3)+"</td>");
out.println("</tr>");
}
out.println("</table>");
}
29
catch(SQLException ex){ } finally
{try{ if(rs!
=null)
rs.close();
if(stmt!=null)
stmt.close();
if(connect!=null)
connect.close();
}
catch(SQLException e){ }
}
out.println("</center>");
out.println("</body></html>");
Total=0; } }
HTML CODE:
<html>
<head>
<title>Database Test</title>
</head>
<body>
<center>
<h1>Online Examination</h1>
</ceter>
<form action="://localhost:8080/servlet/sayhello " method="POST"><div
align="left"><br></div>
<b>Seat Number:</b><input type="text" name="Seat_no"><div align="Right">
<b>Name:</b><input type="text" name="Name" size="50"><br></div>
<b>1. Every host implements transport layer.</b><br/>
<input type="radio" name="group1" value="True">True
<input type="radio" name="group1" value="False">False<br>
<b>2. It is a network layer's responsibility to forward packets reliably from source to
destina-tion</b><br/>
<input type="radio" name="group2" value="True">True
<input type="radio" name="group2" value="False">False<br>
<b>3. Packet switching is more useful in bursty traffic</b><br/>
<input type="radio" name="group3" value="True">True
<input type="radio" name="group3" value="False">False<br>
<b>4. A phone network uses packet switching</b>
<br/><input type="radio" name="group4" value="True">True
<input type="radio" name="group4" value="False">False<br>
<b>5. HTML is a Protocol for describing web contents</b>
<input type="radio" name="group5" value="True">True
<input type="radio" name="group5" value="False">False<br><br><center>
<input type="submit" value="Submit"><br><br></center>
</form>
</body>
</html>

30
Output:
AFTER SUBMITTING

RESULT:

Thus the online examination program is compiled and executed successfully.


31
6. TOMCAT RUNNINGPROCEDURE

How to compile servletprogram:

1. In the command prompt ,move to


C:\program files\apache group\tomcat 4.1\webapps\servlet\WEB-INF \classes.\
2. Set path=c:\j2sdk1.4.2_1 \ bin
3. Set classpath= C:\program files\apache group\tomcat4.1\common\lib\servlet.jar
4. Compile the program by using javacfilename.
Note: 1. Servlet java program should be in the C:\program files\apache group\
tomcat 4.1\webapps\servlet\WEB-INF \classes.\folder
2. Client program(html/java) Should be in the C:\programfiles\apache
group\tomcat 4.1\webapps\servlet\folder
3. Go to web.xml file which is inside of WEB-INF folder modify the<servlet-
class>tag by the servlet classname.
4. In the HTML client file, change the action attributeto
action=”http://localhost:8080/servlet/sayhello

Content of web.xml:

<servlet>
<servlet_name>any name</servlet_name>
<servlet_class>myform</servlet_class>
</servlet>
<servlet_mapping>
<servlet_name>any name</servlet_name>
<url_pattern>/sayhello</url_pattern>//any name different from servlet name
</servlet_mapping>

Start tomcat:

1. Start tomcat startup


2. Goto the Internet Explorer type,
http://localhost:8080/servlet/htmlfile

CREATING DATABASE
1)
Control panel-> Administrative Tools-> Data Sources(ODBC)
-->System DSN-->add (Microsoft Access Driver(*.mdb)finish
 add name ( give database name)
2)
Open Microsoft Access  create new database(give same database name)
add table insert fields and values

32
EXPNO.:
SHOPPING CART
DATE:

AIM:
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:
1. First install the tomcat into thesystem.
2. Then make a subdirectly(eg., tr) in the\tomcat\webapps.
3. Under tr create WEB-INF directory and also place the html files in this tr directory
only.
4. Next under WEB-INF create two subclasses lib,classes and web.xml
5. Next place all the class files under the classes and jar files(servlet-
api.jar,classes12.jar etc…) underlib
6. subdirectories.
7. After this start tomcat by giving the following command at the
instll_dir>tomcat>bin Catalina.batrun
8. At the I.E(web browser) give the url as http;//localhost:8080//tr/htmlfile or servlet
urlpattern
9. Portno 8080 is assigned for thetomcat.
HOME PAGE:
Main.html:
<html>
<body>
<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 id
otherwise press REGISTRATION
</b></pre></h2>
<br /><br /><pre>
<div align="center"><a href="login.html">LOGIN</a><a href="reg.html">
REGISTRATION</a></div>
</pre></body></html>
Login page: Login.html:
<html>
<body><br/><br/><br/>
<form name="myform" method="post"
action="login">
<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()"
/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="reset"
value="clear"/></div>
33
</form>
</body>
</html>
Registration page:
Reg.html:
<html>
<body><br /><br />
<form name="myform" method="post" action="reg">
<table align="center" >
<tr><td>NAME</td>
<td>:<input type="text" name="name" /></td></tr>
<tr><td>ADDRESS</td>
<td>:<input type="text" name="addr" /></td></tr>
<tr><td>CONTACT NUMBER</td>
<td>:<input type="text" name="phno" /></td></tr>
<tr><td>LOGINID</td>
<td>:<input type="text" name="id" /></td></tr>
<tr><td>PASSWORD</td>
<td>:<input type="password" name="pwd" /></td></tr>
</table>
<br /><br />
<div align="center">
<input type="submit" value="ok" onclick="validate()"
/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="reset"
value="clear" />
</div>
</form>
</body>
</html>
User profile page:
Profile.html:
<html>
<body><br /><br /><br />
<form name="myform" method="post" action="profile">
<div align="center"><pre>
LOGIN ID :<input type="text" name="id" /><br />
</pre><br /><br />
</div>
<br /><br />
<div align="center">
<input type="submit" value="ok" onclick="validate()"
/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="reset"
value="clear"/>
</div></form></body></html>
Books catalog page:
Catalog.html:
<html>
<body><br /><br /><br />
<form method="post" action="catalog">
<div align="center"><pre>
BOOK TITLE :<input type="text" name="title" /><br />
</pre><br /><br /></div><br/><br />
34
<div align="center">
<input type="submit" value="ok"
name="button1"/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<input type="reset" value="clear" name="button2"/>
</div>
</form>
</body>
</html>
Shopping cart, Payment by credit card, Order
Conformation page:
Order.html:
<html>
<body><br /><br />
<form method="post" action="order">
<div align="center"><pre>
ID:<input type="text" name="id" /><br />
PASSWORD:<input type="password" name="pwd"/><br/>
TITLE:<input type="text" name="title" /><br/>
NO. OF BOOKS:<input type="text" name="no" /><br />
DATE:<input type="text" name="date" /><br/>
CREDIT CARD NUMBER :<input type="password" name="cno" /><br /></
pre><br /><br />
</div>
<br /><br />
<div align="center">
<input type="submit" value="ok"
name="button1"/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input
type="reset" value="clear" name="button2"/>
</div>
</form></body></html>
Login servlet :
Login.java:
import java.sql.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class login extendsHttpServlet
{
public void service(HttpServletRequestreq,HttpServletResponse resp)
throwsServletException,IOException{
PrintWriter pw=resp.getWriter();
pw.println("<html><body>");
String id=req.getParameter("id");
String pwd=req.getParameter("pwd");
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection
con=DriverManager.getConnection("jdbc:odbc:orcl","scott","tiger ");
Statement stmt=con.createStatement();
String sqlstmt="select id,pwd from login";
ResultSetrs=stmt.executeQuery(sqlstmt);
int flag=0; 35
while(rs.next())
{
if(id.equals(rs.getString(1))&&pwd.equals(rs.getString(2)))
{
flag=1;
}
}
if(flag==0)
{
pw.println("<br><br>SORRY INVALID ID TRYAGAIN
ID<br><br>");
pw.println("<a href=\"login.html\">press LOGINto
RETRY</a>");
}
else
{
pw.println("<br><br>VALID LOGIN ID<br><br>");
pw.println("<h3><ul>");
pw.println("<li><a
href=\"profile.html\"><fontcolor=\"black\">USER
PROFILE</font>
</a></li><br><br>");
pw.println("<li><ahref=\"catalog.html\"><fontcolor=\"black\">BOOKSCATALOG</
font></a></li><br><br>");
pw.println("<li><ahref=\"order.html\"><fontcolor=\"black\">ORDERCONFIRMATION<
/font></a></li></ul><br><br>");
}
pw.println("</body></html>");
}
catch(Exception e)
{resp.sendError(500,e.toString());}
}
}
Registration servlet:
Reg.java :
import java.sql.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class reg extends HttpServlet
{
public void service(HttpServletRequestreq,HttpServletResponse resp)
throws ServletException,IOException
{
PrintWriter pw=resp.getWriter();
resp.setContentType("text/html");
pw.println("<html><body>");
String name=req.getParameter("name");
String addr=req.getParameter("addr");
String phno=req.getParameter("phno"); 36
Stringid1=req.getParameter("id");
String pwd1=req.getParameter("pwd");
int no=Integer.parseInt(phno);
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection
con=DriverManager.getConnection("jdbc:odbc:orcl","scott","tiger ");
Statement stmt=con.createStatement();
String sqlstmt="select id,pwd from login";
ResultSetrs=stmt.executeQuery(sqlstmt);
int flag=0;
while(rs.next())
{
if(id1.equals(rs.getString(1))&&pwd1.equals(rs.getString(2)))
{
flag=1;
}
}
if(flag==1)
{
pw.println("<br><br>SORRY INVALID ID ALREADY
EXITS TRY AGAIN WITH NEW ID<br><br>");
pw.println("<a href=\"reg.html\">press REGISTER to
RETRY</a>");
}
else
{
Statement stmt1=con.createStatement();
stmt1.executeUpdate("insert into
loginvalues('"+name+"','"+addr+"',"+no+",'"+id1+"','"+pwd1+"');
pw.println("<br><br>YOUR DETAILS AREENTERED<br><br>");
pw.println("<a href=\"login.html\">press LOGIN tologin</a>");
}
pw.println("</body></html>");
}
catch(Exception e)
{resp.sendError(500,e.toString());}}
}

Profile servlet:
Profile.java:
import java.sql.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class profile extendsHttpServlet{
public void service(HttpServletRequestreq,HttpServletResponseresp)
throwsServletException,IOException{
PrintWriter pw=resp.getWriter();
pw.println("<html><body>");
37
String id=req.getParameter("id");
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connectioncon=DriverManager.getConnection("jdbc:odbc:orcl","scott","tiger");
Statement stmt=con.createStatement();
String sqlstmt="select * from login where id="+id+"";
ResultSetrs=stmt.executeQuery(sqlstmt);
int flag=0;
pw.println("<br><br><br>");
while(rs.next())
{
pw.println("<div align=\"center\">");
pw.println("NAME :"+rs.getString(1)+"<br>");
pw.println("ADDRESS:"+rs.getString(2)+"<br>");
pw.println("PHONE NO:"+rs.getString(3)+"<br>");
pw.println("</div>");
flag=1;
}
if(flag==0)
{
pw.println("<br><br>SORRY INVALID ID TRY AGAINID<br><br>");
pw.println("<a href=\"profile.html\">press HERE toRETRY</a>");
}
pw.println("</body></html>");
}
catch(Exception e)
{resp.sendError(500,e.toString());}
}
}
Catalog servlet:
Catalog.java:
import java.sql.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class catalog extends HttpServlet
{
public void service(HttpServletRequestreq,HttpServletResponse resp)
throws ServletException,IOException
{
PrintWriter pw=resp.getWriter();
pw.println("<html><body>");
String title=req.getParameter("title");
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connectioncon=DriverManager.getConnection("jdbc:odbc:orcl","scott","tiger");
Statement stmt=con.createStatement();
38
String sqlstmt="select * from book where title=\'"+title+"\'";
ResultSetrs=stmt.executeQuery(sqlstmt); int flag=0;
while(rs.next())
{
pw.println("<div align=\"center\">");
pw.println("TITLE:"+rs.getString(1)+"<br>");
pw.println("AUTHOR :"+rs.getString(2)+"<br>");
pw.println("VERSION :"+rs.getString(3)+"<br>");
pw.println("PUBLISHER :"+rs.getString(4)+"<br>");
pw.println("COST:"+rs.getString(5)+"<br>");
pw.println("</div>");
flag=1;

}
if(flag==0)
{
pw.println("<br><br>SORRY INVALID TITLE TRYAGAIN <br><br>");
pw.println("<a href=\"catalog.html\">press HERE toRETRY</a>");
}
pw.println("</body></html>");
}
catch(Exception e)
{resp.sendError(500,e.toString());}
}
}
Order servlet:
Order.java:
import java.sql.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class order extendsHttpServlet
{
public void service(HttpServletRequestreq,HttpServletResponseresp)
throwsServletException,IOException{
int count;
PrintWriter pw=resp.getWriter();
pw.println("<html><body>");
String id=req.getParameter("id");
String pwd=req.getParameter("pwd");
String title=req.getParameter("title");
String count1=req.getParameter("no");
String date=req.getParameter("date");
String cno=req.getParameter("cno");
try{
count=Integer.parseInt(count1);
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connectioncon=DriverManager.getConnection("jdbc:odbc:orcl","scott","tiger");
Statement stmt=con.createStatement();
String sqlstmt="select id,pwd from login";
ResultSetrs=stmt.executeQuery(sqlstmt);
intflag=0,amount,x; 39
while(rs.next())
{
if(id.equals(rs.getString(1))&&pwd.equals(rs.getString(2)))
{
flag=1;
}
}
if(flag==0)
{
pw.println("<br><br>SORRY INVALID ID TRY AGAINID<br><br>");
pw.println("<a href= \" 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("<br><br>AMOUNT:"+amount+"<br><br><br><br>");
Statement stmt1=con.createStatement();
stmt1.executeUpdate("insert into
detailsvalues('"+id+"','"+title+"',"+amount+",'"+cno+"');");
pw.println("<br>YOUR ORDER has taken<br>");
}
if(flag1==0)
{
pw.println("<br><br><br>SORRY INVALID IDTRY AGAIN ID<br><br>");
pw.println("<a href=\"order.html\">press HERE toRETRY</a>");
}
}
pw.println("</body></html>");
con.close();
}
catch(Exception e)
{
resp.sendError(500,e.toString());
}
}}

40
Web.xml:
<?xml version="1.0"?>
<web-app >
<servlet>
<servlet-name>login</servlet-name>
<servlet-class>login</servlet-class>
</servlet>
<servlet>
<servlet-name>reg</servlet-name>
<servlet-class>reg</servlet-class></servlet><servlet>
<servlet-name>profile</servlet-name>
<servlet-class>profile</servlet-class></servlet><servlet>
<servlet-name>order</servlet-name>
<servlet-class>order</servlet-class>
</servlet>
<servlet>
<servlet-name>catalog</servlet-name>
<servlet-class>catalog</servlet-class></servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>reg</servlet-name>
<url-pattern>/reg</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>profile</servlet-name>
<url-pattern>/profile</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>order</servlet-name>
<url-pattern>/order</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>catalog</servlet-name>
<url-pattern>/catalog</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>main.html</welcome-file></welcome-file-list>
</web-app>

41
OUTPUT
Before Submitting

RESULT:

Thus the program on shopping cart using servlet is compiled and executed successfully.

42
3
6

EXP NO.: 7.JSP


DATE:
AIM: 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 intr1
3) Copy the jsp files also intotr1
4) Start tomcat give the following
command Catalina.batrun
At install-dir/bin
5) at I.E give url as http://localhost:8081/tr1/main.html
HOME PAGE:
Main.html:
<html>
<body>
<br><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 id
Otherwise press REGISTRATION
</b></PRE></h2>
<br><br><pre>
<div align="center"><a href="login.html">LOGIN</a>
<a href="reg.html">REGISTRATION</a></div></pre>
</body></html>
Loginpage:
Login.html:
<html>
<body><br /><br /><br />
<form name="myform" method="post" action="login.jsp">
<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()"
/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="reset" value="clear" />
</div>
</form>
</body></html>
43
Registration
page: Reg.html:

<html>
<body><br /><br />
<form name="myform" method="post" action="reg.jsp">
<table align="center" >
<tr><td>NAME</td>
<td>:<input type="text" name="name" /></td></tr>
<tr><td>ADDRESS</td>
<td>:<input type="text" name="addr" /></td></tr>
<tr><td>CONTACT NUMBER</td>
<td>:<input type="text" name="phno" /></td></tr>
<tr><td>LOGINID</td>
<td>:<input type="text" name="id" /></td></tr>
<tr><td>PASSWORD</td>
<td>:<input type="password" name="pwd" /></td></tr></table><br /><br />
<div align="center">
<input type="submit" value="ok" onclick="validate()"
/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="reset"
value="clear" />
</div>
</form>
</body>
</html>
User profile page:
Profile.html:
<html>
<body><br /><br /><br />
<form name="myform" method="post" action="profile.jsp">
<div align="center"><pre>
LOGIN ID :<input type="text" name="id" /><br />
</pre><br /><br />
</div>
<br /><br />
<div align="center">
<input type="submit" value="ok" onclick="validate()"
/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="reset" value="clear" />
</div>
</form>
</body>
</html>
Books catalog page:
Catalog.html:
<html>
<body><br /><br /><br />
<form method="post" action="catalog.jsp">
<div align="center"><pre>

44
BOOK TITLE :<input type="text" name="title" /><br />
</pre><br /><br />
</div>
<br /><br />
<div align="center">
<input type="submit" value="ok"
name="button1"/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<input type="reset" value="clear" name="button2"/>
</div>
</form>
</body></html>
Shopping cart, Payment by credit card, Order
Conformation page:
Order.html:
<html>
<body><br /><br />
<form method="post" action="order.jsp">
<div align="center"><pre>
ID
:<input type="text" name="id" /><br />
PASSWORD
:<input type="password" name="pwd" /><br/> TITLE
:<input type="text" name="title" /><br /> NO. OF BOOKS :<input type="text"
name="no" /><br />
DATE
:<input type="text" name="date" /><br />
CREDIT CARD NUMBER :<input type="password" name="cno" /><br
/></pre><br /><br />
</div>
<br /><br />
<div align="center">
<input type="submit" value="ok"
name="button1"/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input
type="reset" value="clear" name="button2"/>
</div>
</form>
</body>
</html>
Login JSP:
Login.jsp:
<%@page import="java.sql.*"%>
<%@page import="java.io.*"%>
<% out.println("<html><body>");
Stringid=request.getParameter("id");
String pwd=request.getParameter("pwd");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connectioncon=DriverManager.getConnection("jdbc:odbc:orcl","scott","tiger");
Statementstmt=con.createStatement();
String sqlstmt="select id,pwd from login";
ResultSetrs=stmt.executeQuery(sqlstmt);
int flag=0;
45
while(rs.next())

{
if(id.equals(rs.getString(1))&&pwd.equals(rs.getString(2)))
{
flag=1;
}}
if(flag==0)
{
out.println("<br><br>SORRY INVALID ID TRY AGAINID<br><br>");
out.println("<a href=\"login.html\">press LOGIN toRETRY</a>");
}
else
{
out.println("<br><br>VALID LOGIN ID<br><br>");
out.println("<h3><ul>");
out.println("<li><a
href=\"profile.html\"><fontcolor=\"black\">USERPROFILE</font>
</a></li><br><br>");
out.println("<li><ahref=\"catalog.html\"><fontcolor=\"black\">BOOKS
CATALOG</font></a></li><br><br>");
out.println("<li><ahref=\"order.html\"><fontcolor=\"black\">ORDER
CONFIRMATION</font>
</a></li></ul><br><br>");
}
out.println("</body></html>");
con.close();
%>

Registration JSP:
Reg.jsp :
<%@page import="java.sql.*"%>
<%@page import="java.io.*"%>
<%response.setContentType("text/html");
out.println("<html><body>");
Stringname=request.getParameter("name");
String addr=request.getParameter("addr");
String phno=request.getParameter("phno");
String id1=request.getParameter("id");
String pwd1=request.getParameter("pwd");
intno=Integer.parseInt(phno);
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection
con=DriverManager.getConnection("jdbc:odbc:orcl","scott","tiger"); Statement
stmt=con.createStatement();
String sqlstmt="select id,pwd from login";
ResultSetrs=stmt.executeQuery(sqlstmt);
int flag=0;
while(rs.next())
{ if(id1.equals(rs.getString(1))&&pwd1.equals(rs.getString(2)))
{flag=1;}
46
}
if(flag==1)
{ out.println("<br><br>SORRY INVALID ID ALREADYEXITS TRY AGAIN
WITH NEW ID<br><br>");
out.println("<a href=\"reg.html\">press REGISTER toRETRY</a>");
}
else
{ Statement stmt1=con.createStatement();
stmt1.executeUpdate("insert into login
values('"+name+"','"+addr+"',"+no+",'"+id1+"','"+pwd1+"');");
out.println("<br><br>YOUR DETAILSAREENTERED<br><br>");
out.println("<a href=\"login.html\">press LOGIN tologin</a>");
}
out.println("</body></html>");
con.close();
%>
Profile JSP:
Profile.jsp:
<%@page import="java.sql.*"%>
<%@page import="java.io.*"%>
<% out.println("<html><body>");
String id=request.getParameter("id");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection
con=DriverManager.getConnection("jdbc:odbc:orcl","scott","tiger"); Statement
stmt=con.createStatement();
String sqlstmt="select * from login where id="+id+"";
ResultSetrs=stmt.executeQuery(sqlstmt);
int flag=0;
out.println("<br><br><br>");
while(rs.next())
{
out.println("<div align=\"center\">");
out.println("NAME :"+rs.getString(1)+"<br>");
out.println("ADDRESS
:"+rs.getString(2)+"<br>");
out.println("PHONE NO
:"+rs.getString(3)+"<br>");
out.println("</div>");
flag=1;
}
if(flag==0)
{
out.println("<br><br>SORRY INVALID ID TRY AGAINID<br><br>");
out.println("<a href=\"profile.html\">press HERE toRETRY</a>");
}
out.println("</body></html>");
con.close(); %>
Catalog JSP:
Catalog.jsp:
<%@page import="java.sql.*"%>
47
<%@page import="java.io.*"%>
<% out.println("<html><body>");
String title=request.getParameter("title");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection
con=DriverManager.getConnection("jdbc:odbc:orcl","scott","tiger"); Statement
stmt=con.createStatement();
String sqlstmt="select * from book where title=\'"+title+"\'";
ResultSetrs=stmt.executeQuery(sqlstmt);
int flag=0;
while(rs.next())
{
out.println("<div align=\"center\">");
out.println("TITLE
:"+rs.getString(1)+"<br>");
out.println("AUTHOR :"+rs.getString(2)+"<br>");
out.println("VERSION :"+rs.getString(3)+"<br>");
out.println("PUBLISHER :"+rs.getString(4)+"<br>"); out.println("COST
:"+rs.getString(5)+"<br>");
out.println("</div>");
flag=1;
}
if(flag==0)
{
out.println("<br><br>SORRY INVALID TITLE TRYAGAIN <br><br>");
out.println("<a href=\"catalog.html\">press HERE toRETRY</a>");
}
out.println("</body></html>");
con.close();

Order servlet:
Order.java:
<%@page import="java.sql.*"%>
<%@page import="java.io.*"%>
<% int count; %>
out.println("<html><body>");
String id=request.getParameter("id");
String pwd=request.getParameter("pwd");
String title=request.getParameter("title");
String count1=request.getParameter("no");
String date=request.getParameter("date");
String cno=request.getParameter("cno");
count=Integer.parseInt(count1);
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection
con=DriverManager.getConnection("jdbc:odbc:orcl","scott","tiger"); Statement
stmt=con.createStatement();
String sqlstmt="select id,pwd from login";
ResultSetrs=stmt.executeQuery(sqlstmt);
int flag=0,amount,x;

48
while(rs.next())

{
if(id.equals(rs.getString(1))&&pwd.equals(rs.getString(2)))
{
flag=1;
}
}
if(flag==0)
{
out.println("<br><br>SORRY INVALID ID TRY AGAINID<br><br>");
out.println("<a href= \"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;
out.println("<br><br>AMOUNT
:"+amount+"<br><br><br><br>");
Statement stmt1=con.createStatement();
stmt1.executeUpdate("insert into details
values('"+id+"','"+title+"',"+amount+",'"+cno+"');"); out.println("<br>YOUR ORDER has
taken<br>");
}
if(flag1==0)
{
out.println("<br><br><br>SORRY INVALID IDTRY AGAIN ID<br><br>");
out.println("<a href=\"order.html\">press HERE toRETRY</a>");
}
}
out.println("</body></html>");
con.close();
%>

Output:

49
RESULT:
Thus the program using JSP by converting the static web pages of assignments into dynamic web pages is compiled
and executed successfully.

50
EXPNO.:
8.XML
DATE:

AIM:

Create and Save an XML document at the server, which contains 10 users
information. Write program, which takes user ID as input and returns the user details by
taking the user information from XML Document.

ALGORITHM:
Step 1: Create user info.xml to store the 10 employee details
Step 2: Create user info.html to get the user information
Step 3: Create users.xml to store userid and password
Step 4: Create login form.html to validate the user input

Login Page:
Std.html:
<html>
<head>
<script>
function LoadXmlDoc(dname)
{
xmldoc=new ActiveXObject("Microsoft.XMLDOM");
xmldoc.async="false";
xmldoc.load(dname);
return xmldoc;
}
function validate()
{
var i,k,j=0;
xmldoc=LoadXmlDoc("student.xml");
var v1=myform.n2.value;
if(v1.length==0)
window.alert("enter the roll no.");
else
{
v1=parseInt(v1);
arr=xmldoc.getElementsByTagName("students");
for(i=0;i<arr.length;i++)
{
var txt=xmldoc.getElementsByTagName("rollno")
[i].childNodes[0].nodeValue; if(txt==v1)
{k=i;
j=1;

}
}
51
if(j==1)
{
nam=xmldoc.getElementsByTagName("name")[k].childNodes[0].nodeValue;
rol=xmldoc.getElementsByTagName("rollno")[k].childNodes[0].nodeValue;
per=xmldoc.getElementsByTagName("percentage")[k].childNodes[0].nodeValue; 47
document.write("<body bgcolor='pink'>");
document.write("<table border=1 align='center'><tr><thcolspan='2'>USER
DETAILS</th></tr>");
document.write("<tr><th>Name::</th><td>"+nam+"</td></tr>"); document.write("<tr>

<th>RollNumber::</th><td>"+rol+"</td></tr>");
document.write("<tr><th>Percentage::</th>
<td>"+per+"</td></tr>"); document.write("</table></body>");

}
else
window.alert("roll number not found");
}
}
</script>
</head>
<body bgcolor="pink" text="red">
<form name="myform">
<table align="center">
<tr><td><B>RollNumber</B></td><td><input type="text"
size=15name="n2"></td></tr>
</table>
<br>
<center><input type=submit value="submit" name="b1" onClick="validate()"></center>
</form>
</body>
</html>
Student XML Document:
Student.xml:
<?xml version="1.0" ?>
<cse>
<students>
<rollno>501</rollno>
<name>ABC</name>
<percentage>65%</percentage>
</students>
<students>
<rollno>502</rollno>
<name>DEF</name>
<percentage>67%</percentage>
</students>
<students>
<rollno>503</rollno>

52
<name>GHI</name>
<percentage>69%</percentage>
</students>
<students>
<rollno>504</rollno>
<name>JKL</name>
<percentage>65%</percentage>
</students>
<students>
<rollno>505</rollno>
<name>MNO</name>
<percentage>73%</percentage></students>
<students><rollno>506</rollno><name>PQR</name><percentage>74%</
percentage></students>
<students>
<rollno>507</rollno><name>stu</name><percentage>65%</percentage></
students>
<students>
<rollno>508</rollno><name>VWX</name><percentage>70%</percentage>
</students>
<students>
<rollno>509</rollno><name>YZ</name><percentage>72%</percentage></
students>
<students><rollno>510</rollno>
<name>PQR</name>
<percentage>75%</percentage>
</students>
</cse>
Output:

RESULT:

Thus the creation of an XML document at the server, which contains 10 users
information and the program which takes user ID as input and returns the user details by
taking the user information from XML Document is compiled and executed successfully.
53
EXPNO.:
9.PHP
DATE:

AIM:
To write a program to Validate the form using PHP regular expression.

ALGORITHM:

Step 1: Create a PHP file and embed within HTML Document


Step 2: Validate Name,Gender,E-Mail and Website
Step 3: Use POST method to invoe and validate the inputs
Step 4: Compile and execute the program
Step 5: Give and validate the inputs

PROGRAM:

<!DOCTYPEHTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website ="";

if ($_SERVER["REQUEST_METHOD"] == "POST"){
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z-' ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
54
if (empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
// check if URL address syntax is valid
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0- 9+&@#\/%=~_|]/i",
$website)) {
$websiteErr = "Invalid URL";
}
}

if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}

if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}
}

functiontest_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;

}
?>
<h2>PHP Form Validation Example</h2>
<p><spanclass="error">* required field</span></p>
<formmethod="post"action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?
>">
Name: <inputtype="text"name="name">
<spanclass="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail: <inputtype="text"name="email">
<spanclass="error">* <?php echo $emailErr;?></span>
<br><br>
Website: <inputtype="text"name="website">
<spanclass="error"><?php echo $websiteErr;?></span>
<br><br>

55
Comment: <textareaname="comment"rows="5"cols="40"></textarea>
<br><br>
Gender:
<inputtype="radio"name="gender"value="female">Female
<inputtype="radio"name="gender"value="male">Male
<inputtype="radio"name="gender"value="other">Other
<spanclass="error">* <?php echo $genderErr;?></span>
<br><br>
<inputtype="submit"name="submit"value="Submit">
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>
</body>
</html>

Output:

RESULT:
Thus the program to Validate the form using PHP regular expression is compiled and executed successfully.

56
EXPNO.:
10.WEBSERVICES
DATE:
a) Connecting a web service with database
AIM:
To create a Web Service and the connect that web service to the database using java &
also write a WSDL & SOAP code for that web service.

PROGRAM:
package db;
importjava.sql.*;
import java.util.logging.Level;
importjava.util.logging.Logger;
import javax.jws.WebService;
import javax.jws.WebMethod;
@WebService()
public class
NewWebService{ @WebMethod(operatio
nName = "dbcon") public String dbcon() {
//TODO write your implementation code here:
String s="";
Connection con;
String line;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:student");
Statement st=con.createStatement();
ResultSetrs=st.executeQuery("select * from stud");
line="<br>";
while(rs.next())
{
s += line+"Rollno:" + rs.getString(1)+line;
s += "Name:" + rs.getString(2)+line;
s += "Mark1:" +rs.getString(3)+line;
s += "Mark2:" +rs.getString(4)+line;
s += "Mark3:" +rs.getString(5) +line+line;
}
} catch (Exception ex)
{ Logger.getLogger(NewWebService.class.getName()).log(Level.SEVERE,
null, ex);
}
//TODO write your implementation code here:
return s;
}
}

57
SOAP Request
<?xml version="1.0" encoding="UTF-8"?>
<S:Envelopexmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
<S:Header/>
<S:Body>
<ns2:dbcon xmlns:ns2="http://db/"/>
</S:Body>
</S:Envelope>

SOAP Response
<?xml version="1.0" encoding="UTF-8"?>
<S:Envelopexmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
<S:Body>
<ns2:dbconResponse xmlns:ns2="http://db/">
<return><br>Rollno:34555<br>Name:suresh<br>Mark1:90<br>Mark2:50<br>Mar
k3:60<br><br><br>Rollno:45666<br>Name:ovi<br>Mark1:100<br>Mark2:98<br>Mark3
:90<br><br><br>Rollno:63440<br>Name:nithin<br>Mark1:70<br>Mark2:80<br>Mark3:
75<br><br></return>
</ns2:dbconResponse>
</S:Body>
</S:Envelope

OUTPUT:

RESULT:
Thus the program to create and connect a web service to database using WSDL and SOAP is compiled and executed
successfully.

58
EXP NO:
CONSUMING A WEB SERVICE THROUGH ANAPPLICATION
DATE:

Aim:

To create a web service for adding few numbers using NetBeans and write client side code
to invoke the web service.
Algorithm:
1. Using the Netbeans API create a project of the type web application.
2. Create a web service in the project.
3. Click on the Design tab and design the prototype of the webservice.
4. Click on source tab and modify the application logic of the webservice.
5. Save the project.
6. Right click on the project and click on deploy and undeploy.
7. Then test the web service.
8. Create another web application project and create a jsp
file.
9. Right click on project and click on create web service
client.
10. Browse and choose the web service created i.ewsdlurl
11. Drag and drop the web service reference to the source
code window.
12. Then pass the appropriate parameters to the web service
client and invoke the web service.
STEPS TO CREATE CLIENT SIDE PROJECT:
1.
create the new project as above and give the name as addclient.

2.
addclient project will be created. right click it and choose the following.

59
3.
Then browse and choose the addwebwsdlfile

4.
Then choose the following and add the source code in index.jsp and saveit.

60
Index.jsp source code
<%--Document : index Created on : Jun 19, 2012, 8:46:45 AM Author: surendran--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Hello World!</h1>
<form name="" action="action.jsp" method="post">
Enter No1:<input name="fst" type="text" /><br/>
Enter No2:<input name="sec" type="text" /><br/>
<input name="ok" type="submit" value="check" />
</form>
</body>
</html>

61
5.
Then create an action.jsp asfollows.
Right click web page in addclient and choose new-
>jspName:action
Click finish

6.
click on the action.jsppage..then right click in it and choose web service clientreference
->call web service

62
7.
The invoke the add service.

8.
add the following code in theaction.jsp
<%--
Document : action
Created on : Jun 19, 2012, 8:50:03 AM
Author : surendran
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Hello World!</h1>
<%-- start web service invocation --%><hr/>
<%
String n1=request.getParameter("fst");

int aa=Integer.parseInt(n1);

%>
<%
try
{ perpack.PerfectService service = new perpack.PerfectService();
perpack.Perfect port = service.getPerfectPort();
// TODO initialize WS operation arguments here
int n = aa;
// TODO process result here
java.lang.String result = port.perfectfind(n);
out.println("Result = "+result);
} catch (Exception ex) {
// TODO handle custom exceptions here
}
63
%>
<%-- end web service invocation --%><hr/>
</body>
</html>
8. Finally undeploy and deploy the addclient and run it.

RESULT:

Thus the program to create a Web Service and the connect that web service to the
database using java & also write a WSDL & SOAP code for that web service is compiled
and executed successfully.

64
SESSION TRACKING FOR A HIT COUNT
DATE:

AIM:
To write a servlet code to implement session tracking for a hit count.

ALGORITHM:
Step1: Create a html file with form tag.
Step2: The form tag action=”http://localhost:8080/servlet/say hello”.
Step3: Using input tag submit type invoke the servlet code
Step4: Create the http servlet request and response object.
Step5: Check the tracker count with hit count. If count exceeds the limit then session expired.
Step6: If not, invoke the html code.
Step7: Repeat the step 3 to 6 until session expired

PROGRAM:
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SessionTracker extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
HttpSession session = req.getSession();
Integer count = (Integer)session.getAttribute("tracker.count");
if (count == null)
count = new Integer(1);
else
count = new Integer(count.intValue() + 1);
session.setAttribute("tracker.count", count);
out.println("<HTML><HEAD><TITLE>SessionTracker</TITLE></HEAD>");
out.println("<BODY><H1>Session Tracking Demo</H1>");
out.println("You've visited this page " + count+
((count.intValue() == 1) ? " time." : " times."));
out.println("<P>");
out.println("<H2>Here is your session data:</H2>");
Enumeration enum = session.getAttributeNames();
while (enum.hasMoreElements()) {
String name = (String) enum.nextElement();
out.println(name + ": " + session.getAttribute(name) + "<BR>");
}
out.println("</BODY></HTML>");
}
}
HTML CODE:// HAI.HTML
<html>
<head><title>sessiontracker</title></head>
<body><h3>session tracking demo</h3>
65
<<form name=order action="http://localhost:8080/servlet/sayhello" method=GET>
</form>
</body></html>

OUTPUT:

RESULT:
Thus the program to create Session tracking using hidden form fields and Session tracking
for a hit count is compiled and executed successfully.

66
Date: CONTENT BEYOND THE SYLLABUS

1. Develop an applet that receives an integer in one text field, and computes its
factorial Value and returns it in another text field, when the button
named“Compute” isclicked.

AIM:
To Develop an applet that receives an integer in one text field, and computes its factorial
Value and returns it in another text field, when the button named “Compute” is clicked
PROGRAM:
import java.awt.*;
import java.applet.Applet;
public class SimpleApplet extends Applet
{
public void paint(Graphics g)
{
g.drawString("welcome to Applets",50,50);
}
}
/*<applet code="SimpleApplet.class" height=200 width=400>
</applet>*/
Output:
E:\java programs>javac SimpleApplet.java E:\
java programs>appletviewer SimpleApplet.java
Program:
import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
public class Fact extends Applet implements ActionListener
{
Label l1,l2;
TextField t1,t2;
Button b1;
public voidinit()
{
l1=new Label("enter thevalue");
add(l1);
t1=newTextField(10);
add(t1);
b1=new Button("Factorial");
add(b1);
b1.addActionListener(this);
l2=new Label("Factorial of given no is");
add(l2);

67
t2=newTextField(10);
add(t2);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==b1)
{
int fact=fact(Integer.parseInt(t1.getText()));
t2.setText(String.valueOf(fact));
}
}
int fact(int f)
{
int s=0;
if(f==0)
return 1;
else
return f*fact(f-1);

}
}
/*<applet code="Fact.class" height=300 width=300>
</applet>*/

Output:
E:\java programs>javac Fact.java E:\
java programs>appletviewerFact.java

RESULT:
Thus the program on developing an applet which receives an integer in one text
field, and computes its factorial Value and returns it in another text field is compiled and
executed successfully.
68
EXPNO.: 2. Write an HTML page including any required java script that
breaks a number from one text field in a range of 0 to 999 and
DATE: shows it in another text field in words.if the number is out of
range it should show “out of range” and if it is not a number
it should show “not a number”, in the resultbox.

AIM:
To write an HTML page including any required java script that breaks a number from one
text field in a range of 0 to 999 and shows it in another text field in words.if the number is
out of range it should show “out of range” and if it is not a number it should show “not a
number”, in the result box.

PROGRAM:
<html>
<head>
<title>Example1</title>
<script>
function checkfun()
{
var num = document.f1.num1.value;
var a= new RegExp("[0-9]");
if(!a.test(num))
alert("enter numbers only");
if(num.length>3)
alert("out of range");
var SingleDigits = new Array("Zero", "One", "Two", "Three", "Four", "Five", "Six",
"Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen",
"Sixteen", "Seventeen", "Eighteen", "Nineteen");
var DoubleDigits = new Array("Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy",
"Eighty", "Ninety");
var Words = "";
var St;
for (var i = 9; i>= 1; i--) {
if (num >= i * 100){
Words += SingleDigits[i];
St = 1;
Words += " hundred";
if (num != i * 100) Words += " and ";
{ num -= i*100; }
i=0;}
}
//alert(Words);
for (var i = 9; i>=2;i--) {
if (num >= i * 10)
{ Words +=(St?DoubleDigits[i-2].toLowerCase():DoubleDigits[i-2]);
69
St =1;
if (num != i * 10) Words += "-";
{ num -=i*10;
}
i=0;
} }
//alert(Words);
for (var i = 1; i< 20; i++)
{
if (num == i)
{
Words += (St?SingleDigits[i].toLowerCase():SingleDigits[i]);
}
}
//alert(Words);
f1.res.value = Words;
//document.f1.res.value = Words;
}

</script>
</head>
<body>
<form name="f1">
<font background-color=pink color=green>
enter a num<input type=text name=num1>
<input type="button" value=validate onclick="checkfun()">
result<textarea name=res></textarea>
</font>
</form>
</body>
</html>

OUTPUT:

67 SIXSEVEN

RESULT:
Thus the program to write an HTML page including any required java script is compiled and executed
successfully.

70

You might also like