Download as pdf or txt
Download as pdf or txt
You are on page 1of 71

Nadar Saraswathi College of Engineering and Technology

Vadapudupatti,Theni -625531.

Department of Computer Science and Engineering


(Regulation -2017)

IIIrd Year / VIth Sem


CS8661
INTERNET PROGRAMMING
LABORATORY
MANUAL

Prepared By :Mr.R.Udhaya Kumar AP/CSE

Page 1
CS8661 INTERNET PROGRAMMING LABORATORY LTPC
0 0 42

OBJECTIVES:
 To be familiar with Web page design using HTML/XML and style sheets
 To be exposed to creation of user interfaces using Java frames and applets.
 To learn to create dynamic web pages using server side scripting.
 To learn to write Client Server applications.
 To be familiar with the PHP programming.
 To be exposed to creating applications with AJAX

LIST OF EXPERIMENTS
1. Create a web page with the following using HTML
a. To embed a map in a web page
b. To fix the hot spots in that map
c. Show all the related information when the hot spots are clicked.
2. Create a web page with the following.
a. Cascading style sheets.
b. Embedded style sheets.
c. Inline style sheets. Use our college information for the web pages.
3. Validate the Registration, user login, user profile and payment by credit card pages using
JavaScript.
4. Write programs in Java using Servlets:
i. To invoke servlets from HTML forms
ii. Session tracking using hidden form fields and Session tracking for a hit count
5. 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.
6. Install TOMCAT web server. Convert the static web pages of programs into dynamic web
pages using servlets (or JSP) 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.
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. i. Validate the form using PHP regular expression. ii. PHP stores a form data into database.
10. Write a web service for finding what people think by asking 500 people„s opinion for any
consumer product.
TOTAL: 60 PERIODS
OUTCOMES: Upon Completion of the course, the students will be able to:
 Construct Web pages using HTML/XML and style sheets.
 Build dynamic web pages with validation using Java Script objects and by
applying different event handling mechanisms.
 Develop dynamic web pages using server side scripting.
 Use PHP programming to develop web applications.
 Construct web applications using AJAX and web services.
SOFTWARE REQUIRED: Dream Weaver or Equivalent, MySQL or Equivalent, Apache
Server, WAMP/XAMPP.

Page 2
Ex. No: 1 IMAGE MAPPING DATE:
AIM:
To write a map and fix the hotspots to show the information of it in a web page.

ALGORITHM:
1. Start the program.
2. Get the india map image and link it to the package.
<img src="flag.jpg">
<img align="right" src = "India Map.gif" usemap="#india">
3. Fix the hotspots in that image.
4. Map the reference of the hotspots in the image.
<area shape="circle" coords="274,745,20" href="tn.html">
5. Mention the derived link.
6. Click the link to get the desired image.
7. Stop the program.

SOURCE CODE:
Main.html
<html>
<head>
<BODY bgcolor="#gop6876cgdt5564ss">
<img src ="indiamap.jpeg" usemap="indiamap" />
<map name=indiamap>
<AREA SHAPE="rect" COORDS="190,477,251,562" HREF="tamilnadu.html"
target="tamilnadu.html" >
<AREA SHAPE="rect" COORDS="158,477,195,564" HREF="kerala.html"
target="kerala.html" >
<AREA SHAPE="rect" COORDS="217,378,238,472,350,361" HREF="andhra.html"
target="andhra.html" >
<AREA SHAPE="rect" COORDS="160,474,212,401,189,436" HREF="karnataka.html"
target="karnataka.html" >
<AREA SHAPE="rect" COORDS="137,382,219,311,129,331" HREF="maharashtra.html"
target="maharashtra.html" >
<AREA SHAPE="rect" COORDS="392,319,334,304,309,362," HREF="orissa.html"
target="orissa.html" >
<AREA SHAPE="rect" COORDS="232,244,238,306,168,283"
HREF="madhayapradesh.html"
target="madhayapradesh.html" >
</map>
</head>
</html>

Tamiladu.html
<html>
<head>
<body bgcolor="#fggbhjgdhg"/>
<center><h2>it is a tamilnadu,here maximum tamilan living and capital of tamilnadu is
</h2><h1>chennai<h1></center>
</head>
</html>

Page 3
Kerala.html
<html>
<head>
<body bgcolor="#7674dshddf"/>
<center>it is a kerala,here maximum malaiyalees living and capital of kerala is
<h1>Thiruvananthapuram</h1></center>
</head>
</html>

Karataka.html
<html>
<head>
<body bgcolor="#7674dshddf"/>
<center>it is a karnataka,here maximum kannadam living and capital of karnataka is
<h1>Bangalore</h1></center>
</head>
</html>

Madhyapradesh.html
<html>
<head>
<body bgcolor="blue"/>
<center>it is a madhyapradesh,here maximum maratiyam living and capital of
madhyapradesh
is <h1>BHOPAL</h1></center>
</head>
</html>

Maharastra.html
<html>
<head>
<body bgcolor="blue"/>
<center>it is a maharashtra,here maximum maratiyam living and capital of maharashtra is
<h1>Mumbai</h1></center>
</head>
</html>

Orissa.html
<html>
<head>
<body bgcolor="blue"/>
<center><h2>it is a orissa,here maximum oreya living and capital of orissa is</h2>
<h1>Bhubaneswar</h1></center></head></html>

Output:

Page 4
Page 5
RESULT:
Thus the web page is created and the image is embedded with hot spot and the linking
ages successfully, and the output is verified.

Page 6
Ex. No: 2 STYLE SHEET DATE:

AIM:
To write a webpage that displays college information using various style sheet.

ALGORITHM:
1. Start the program.
2. Create a web page with framesets consisting two frames.
3. In the first frame include the links.
4. In the second frameset display the webpage of the link.
5. Create a external style sheets.
6. Create a inline and internal style and make a link to the external style sheet.
7. Stop the program.

SOURCE CODE:
<html>
<head>
<title>Cascading Style Sheets</title>
</head>
<body alink="blue" vlink="brown">
<h1><u><b><font face="Monotype corsiva" color="red">
Different types of Cascading Style Sheets</font> </b></u></h1>
<br />
<font face="Arial"size="6">
<a href ="inline.html" style="text-decoration :none;"> 1. Inline Style Sheet</a><br />
<a href ="embedded.html" style="text-decoration :none;"> 2. Embeded Style
Sheet</a><br />
<a href ="external.html" style="text-decoration :none;"> 3. External Style
Sheet</a><br />
<a href ="import.html" style="text-decoration :none;"> 4. Imported Style
Sheet</a><br /></font>
</body>
</html>

Inline.html
<html>
<head>
<title>Inline Style Sheet</title>
</head>
<body>
<ol class="decimal">
<h1 style="font-family :Monotype Corsiva ;background-color:antiquewhite ;"><li>
Inline Style Sheet</li></h1>
<h3>
<p style="text-indent :30pt;color:blue;font-family :arial;">
Inine Style is the style attached to one specific element.
The style is specified directly in the start tag as a value of the style attribute well apply
exclusively to this specific element occurrence.
</p></h3>
</ol>
</body>
</html>

Page 7
Embedded.html
<html>
<head>
<title>Embeded Style Sheet</title>
<style type="text/css">
ol{list-style-type:decimal}
h1{text-align: left; background:antiquewhite;font-family:monotype corsiva;color:red}
h3{text-align: right; font-family:arial;color:blue}
</style>
</head>
<body>
<ol class="lroman"><h1>
<li>Embedded style sheet</li></h1>
<br />
Embedded style is the style attached to one specific document.
The information is specified as a content of the style element
inside the head element and wil apply to the entire documents.
</h3></ol>
</body>
</html>

External.html
<html>
<head>
<title>External Style Sheet</title>
<link rel=Stylesheet href="style1.css" type="text/css" />
</head>
<body>
<h1>1. External Style Sheet</h1><br />
<h3>
An external style sheet is a template documents/files
containing style info which can be linked with any number
of the documents. This is a very convenient way of formating
the entire site as well as restyling it by editing just one file</h3>
</body>
</html>

Import.html
<html>
<head><title>Imported Style Sheet</title>
<link rel= stylesheet href="style2.css" type="text/css">
</head>
<body>
<h1>1. Imported Style Sheet</h1>
<h3> Imported style sheet is a shet that can be imported to another sheet.
This alignes exacting one main sheet containing declarations that apply to
the whle site and partial sheets containing declarations that apply to specific
elements.</h3>
</body>
</html>

Page 8
Output:

Page 9
Page 10
RESULT:
Thus the web page is created using all tyes of cascading style sheets successfully and the
output is also verified.

Page 11
EX NO : 3 Website Validation Using Java Script DATE :
AIM: Validate the Registration, user login, user profile and payment by credit card pages
using JavaScript.
PROCEDURE:
1. Start the program.
2. Create a web page with framesets consisting two frames.
3. In the first frame include the links.
4. In the second frameset display the webpage of the link.
5. Create a scripting code for form validation for registration, user login, user profile and
payment by credit card pages using java script.
6. valid the logic and verify it .
7. Stop the program.

SOURCE CODE:
Home page
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>

Page 12
Left.html:
<html>
<body bgcolor=”pink”>
<h3>
<ul>
<li><a href=”login.html” target=”right”><font color=”black”>
LOGIN</font></a></li><br><br>
<li><a href=”profile.html” target=”right”><fontcolor=”black”> USER
PROFILE</font></a></li><br>
<br>
<li><a href=”catalog.html” target=”right”><fontcolor=”black”> BOOKS
CATALOG</font></a></li>
<br><br>
<li><a href=”scart.html” target=”right”><font color=”black”>
SHOPPINGCART</font></a></li><br>
<br>
<li><a href=”payment.html” target=”right”><fontcolor=”black”>
PAYMENT</font></a></li><br><br>
<li><a href=”order.html” target=”right”><font color=”black”> ORDER
CONFIRMATION</font></a>
</li><br><br>
</ul>
</body>
</html>
Registration and user Login
Login.html:
<html>
<body bgcolor="pink"><br><br><br>
<script language="javascript">
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>

Page 13
<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()">&nbsp;&nbsp;&nbsp;&nbsp;
<input type="reset" value="clear" >
</form>
</body>
</html>
User profile page
Profile.html:
<html>
<body bgcolor=”pink”><br><br>
<script language=”javascript”>
function validate()
{
var flag=1;
if(document.myform.name.value==””||
document.myform.addr.value==””||
document.myform.phno.value==””||
document.myform.id.value==””||
document.myform.pwd.value==””)
{
flag=0;
}
var str=document.myform.phno.value;
var x;
for(var i=0;i<str.length;i++)
{
x=str.substr(i,1)
if(!(x<=9))
{
flag=0;
break;
}
}
if(flag==1)
{
alert("VALID INPUT");
}
else
{
alert("INVALID INPUT");
document.myform.focus();
}}
</script>
<form name="myform">

Page 14
<div align="center"><pre>
NAME :<input type="text" name="name"><br> ADDRESS :<input type="type"
name="addr"><br>
CONTACT NUMBER:<iput type="text" name="phno"><br> LOGINID :<input type="text"
name="id">
<br> 19
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;
<input type="reset" value="clear">
</form></body></html>
Books catalog :
Scart.html:
<html>
<body bgcolor="pink"><br><br><br>
<script language="javascript">
function validate()
{
var flag=1;
if(document.myform.title.value=="")
{
flag=0;
}
str=document.myform.title.value;
if(str=="c")
{
document.writeln("<body bgcolor=pink>");
document.writeln("title-->c"+" cost-->444");
}
else if(str=="jsp")
{
document.writeln("<body bgcolor=pink>");
document.writeln("title-->jsp"+" cost-->555");
}
else
{
flag=0;
}
if(flag==1)
{
alert("VALID INPUT");
}
else
{
alert("INVALID INPUT");
document.myform.focus();
}
}
</script>

Page 15
<form name="myform" >
<div align="center"><pre>
BOOK TITLE :<input type="text" name="title"><br> 21
</pre><br><br>
</div>
<br><br>
<div align="center">
<input type="submit" value="ok" onClick="validate()">&nbsp;&nbsp;&nbsp;&nbsp;
<input type="reset" value="clear">
</form>
</body>
</html>

Shopping cart:
Catalog.html:
<html>
<body bgcolor="pink"><br><br><br>
<script language="javascript">
function validate()
{
var flag=1;
if(document.myform.id.value==""||
document.myform.title.value==""||
document.myform.no.value==""||
document.myform.cost.value==""||
document.myform.date.value=="")
{
flag=0;
}
var str=document.myform.no.value;
var x;
for(var i=0;i<str.length;i++)
{
x=str.substr(i,1)
if(!(x<=9))
{
flag=0;
break;
}
}
str=document.myform.title.value;
var str1=document.myform.cost.value;
if(!((str=="c"&& str1==444) || (str=="jsp" && str1==555)))
{
flag=0;
}
if(flag==1)
{
alert("VALID INPUT");
}

Page 16
else
{
alert("INVALID INPUT");
document.myform.focus();
}
}
</script>
<form name="myform" >
<div align="center"><pre>
LOGIN ID :<input type="text" name="id"><br> TITLE :<input type="text"
name="title"><br> NO.OF
BOOKS
:<input type="text" name="no"><br>
COST OF BOOK
:<input type="text"name="cost"><br>
DATE :<input type="text" name="date"><br></pre><br><br>
</div>
<br><br>
<div align="center">
<input type="submit" value="ok" onClick="validate()">&nbsp;&nbsp;&nbsp;&nbsp;
<input type="reset" value="clear">
</form>
</body>
</html>
Payment by credit card
Payment.html:
<html>
<body bgcolor="pink"><br><br><br>
<script language="javascript">
function validate()
{
var flag=1;
if(document.myform.id.value==""||
document.myform.pwd.value==""||
document.myform.amount.value==""||
document.myform.num.value=="")
{
flag=0;
}
var str=document.myform.amount.value;
var x;
for(var i=0;i<str.length;i++)
{
x=str.substr(i,1);
if(!(x<=9))
{
flag=0;
break;
}
}
str=document.myform.num.value;

Page 17
for(var i=0;i<str.lenght;i++)
{
x=str.substr(i,1);
if(!(x<=9))
{
flag=0;
break;
}
}
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">
<br> AMOUNT :<input type="text" name="amount"><br>
CREDITCARDNUMBER:<input
type="PASSWORD"
name="num+"><br></pre><br><br>
</div>
<br><br>
<div align="center">
<input type="submit" value="ok" onClick="validate()">&nbsp;&nbsp;&nbsp;&nbsp;
<input type="reset" value="clear" >
</form>
</body>
</html>
Order Conformation
Order.html:
<html>
<head><title>order conformation</title><M/head>
<body bgcolor="cyan">
<center>
<h1><b>AMAZON</h1>
<pre><strong>
<b>Your order Is Conformed
</strong></pre>
<h2><b>THANK YOU</h2>
</center>
</body>
</html>

Page 18
Result: Thus the Validation of the Registration, user login, user profile and payment by
credit card pages using JavaScript was performed and the output was verified.

Page 19
Ex No :4A Invoke Servlets From HTML Forms Date :

AIM:
To write a java program for invoking servlet from HTML form.

ALGORITHM:
1. Start the program.
2. Create the form as ResponseDemoServlet with textfield,submit
Button and reset button.
3. The class ResponseDemoServlet implements the interface servlet.
4. Create the out object for the PrintWriter class and call the method
Getwriter as response.getwriter.
5. Display the server port, server name, protocol, character encoding, content length.
6. Create the class as enumeration with parameters as object.
7. Stop the program.

SOURCE CODE:
Client Page:
<HTML>
<HEAD>
<TITLE>Sending a request</TITLE>
</HEAD>
<BODY>
<FORM ACTION= ResponseDemoServlet METHOD="POST">
<BR><BR>
Author: <INPUT TYPE="TEXT" NAME="Author">
<INPUT TYPE="SUBMIT" NAME="Submit">
<INPUT TYPE="RESET" VALUE="Reset">
</FORM>
</BODY>
</HTML>

Server Page:
importjavax.servlet.*;
importjava.io.PrintWriter;
importjava.io.IOException;
importjava.util.Enumeration;
public class ResponseDemoServlet implements Servlet {
public void init(ServletConfigconfig) throws ServletException {
} public void destroy() { }
public void service(ServletRequest request, ServletResponse response)
throwsServletException, IOException {
PrintWriter out = response.getWriter();
out.println("<HTML>");
out.println("<HEAD>");
out.println("<TITLE>");
out.println("ServletResponse");
out.println("</TITLE>");
out.println("</HEAD>");
out.println("<BODY>");
out.println("<B>Demonstrating the ServletResponse object</B>");

Page 20
out.println("<BR>");
out.println("<BR>Server Port: " + request.getServerPort());
out.println("<BR>Server Name: " + request.getServerName());
out.println("<BR>Protocol: " + request.getProtocol());
out.println("<BR>Character Encoding: " + request.getCharacterEncoding());
out.println("<BR>Content Type: " + request.getContentType());
out.println("<BR>Content Length: " + request.getContentLength());
out.println("<BR>Remote Address: " + request.getRemoteAddr());
out.println("<BR>Remote Host: " + request.getRemoteHost());
out.println("<BR>Scheme: " + request.getScheme());
Enumeration parameters = request.getParameterNames();
while (parameters.hasMoreElements()) {
String parameterName = (String) parameters.nextElement();
out.println("<br>Parameter Name: " + parameterName);
out.println("<br>Parameter Value: " +
request.getParameter(parameterName));
}
Enumeration attributes = request.getAttributeNames();
while (attributes.hasMoreElements()) {
String attribute = (String) attributes.nextElement();
out.println("<BR>Attribute name: " + attribute);
out.println("<BR>Attribute value: " + request.getAttribute(attribute));
}
out.println("</BODY>");
out.println("</HTML>");
}
public String getServletInfo() {
return null;
}
publicServletConfiggetServletConfig() {
return null;
}
}

OUTPUT:

Page 21
RESULT:
Thus the program for invoking servlet from HTML form was executed and the output
was verified.

Page 22
EX NO : 4B Invoking Servlet from Servlet forms Date :

AIM:
To write a program for invoking servlet from Servlet form.
ALGORITHM:
1. Start the program.
2. Create the class as Loginservlet.
3. Enter the username and password in the form.
4. If username and password are correct then the welcome servlet page is opened.
5. Else the message “Loginfailed” will be displayed.
6. RequestDispatcher is used to transfer messages efficiently.
7. Stop the program.
SOURCE CODE:
LOGIN Page:
importjavax.servlet.*;
importjavax.servlet.http.*;
import java.io.*;
importjava.util.*;
public class LoginServlet extends HttpServlet {
private void sendLoginForm(HttpServletResponse response,
booleanwithErrorMessage)
throwsServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<HTML>");
out.println("<HEAD>");
out.println("<TITLE>Login</TITLE>");
out.println("</HEAD>");
out.println("<BODY>");
if (withErrorMessage)
out.println("Login failed. Please try again.<BR>");
out.println("<BR>");
out.println("<BR>Please enter your user name and password.");
out.println("<BR><FORM METHOD=POST>");
out.println("<BR>User Name: <INPUT TYPE=TEXT NAME=userName>");
out.println("<BR>Password: <INPUT TYPE=PASSWORD NAME=password>");
out.println("<BR><INPUT TYPE=SUBMIT VALUE=Submit>");
out.println("</FORM>");
out.println("</BODY>");
out.println("</HTML>");
}public void doGet(HttpServletRequest request, HttpServletResponse response)
throwsServletException, IOException {
sendLoginForm(response, false);}
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throwsServletException, IOException {
String userName = request.getParameter("userName");
String password = request.getParameter("password");
if (userName!=null && password!=null &&

Page 23
userName.equals("jamesb") &&password.equals("007")) {
RequestDispatcherrd = request.getRequestDispatcher("WelcomeServlet");
rd.forward(request, response);
}else {
sendLoginForm(response, true);
} }}
Response Page for Login:
importjavax.servlet.*;
importjavax.servlet.http.*;
import java.io.*;
public class WelcomeServlet extends HttpServlet {
public void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<HTML>");
out.println("<HEAD>");
out.println("<TITLE>Welcome</TITLE>");
out.println("</HEAD>");
out.println("<BODY>");
out.println("<P>Welcome to the Bulbul's and Boni's Web Site.</P>");
out.println("</BODY>");
out.println("</HTML>");
}
}

OUTPUT:

Page 24
RESULT:
Thus the program for login page and its response was done successfully and the output
was verified.

Page 25
EX NO : 5 Three Tier Application Using JSP Date :

AIM:
To write the JSP program for online examination.

ALGORITHM:
1. Start the program.
2. With the scriplet tag, include information like document
Created on and author.
3. Set the content type using page content type=”txt\html”.
4. Include the doctype with transitional flavour.
5. Get the input as regno , name and store in the table.
6. Create the forms as exam and index.
7. Click the submit button, after completing all the questions. If the answers are
correct it will display as correct else incorrect.
8. Stop the program.

SOURCE CODE:

Newjsp.jsp:
<%--
Document : exam
Created on : Feb 23, 2011, 7:19:15 PM
Author : A
--%>
<%@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>Examination Panel</title>
</head>
<body bgcolor="cyan">
<%@ page language="java" %>
<%@ page import ="java.sql.*" %>
<%
String reg= request.getParameter("txt_reg");
String name = request.getParameter("txt_name");
out.println("<h2>Welcome" + name + "...Your Register number is " + reg +
"!!</h2><br><br><br>");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String sTable = "exam";
String sSql = "SELECT * FROM " + sTable + "";
String database = "jdbc:odbc:sDBQ";
Connection cn = null;
Statement st = null;
ResultSet rs = null;
try {
cn = DriverManager.getConnection( database ,"sa","");

Page 26
st = cn.createStatement();
rs = st.executeQuery( sSql );
ResultSetMetaData rsmd = rs.getMetaData();
String s1,s2,s3,s4;
int i=1;
while(rs.next())
{
out.println("<form name='exam' action='newjsp2.jsp' method='post'><b>"+i+" . " +
rs.getString(1) + "</b><br><br>");
s1 = rs.getString(2);
s2 = rs.getString(3);
s3 = rs.getString(4);
s4 = rs.getString(5);
out.println("<input type=radio name=opt"+i+" value="+s1+" CHECKED>"+ s1 +"
<br><br>");
out.println("<input type=radio name=opt"+i+" value="+s2+">" + s2 +"<br><br>");
out.println("<input type=radio name=opt"+i+" value="+s3+">" + s3 +"<br><br>");
out.println("<input type=radio name=opt"+i+" value="+s4+">" + s4 +"<br><br>");
i++;
}
out.println("<input name ='submit' value='Submit' type='submit'/>");
/*int n = rsmd.getColumnCount();
out.println( "<table border=1 cellspacing=3><tr>" );
for( int i=1; i<=n; i++ ) // Achtung: erste Spalte mit 1 statt 0
out.println( "<th>" + rsmd.getColumnName( i ) + "</th>" );
while( rs.next() )
{out.println( "</tr><tr>" );
for( int i=1; i<=n; i++ ) // Achtung: erste Spalte mit 1 statt 0
o ut.println( "<td nowrap>" + rs.getString( i ) + "</td>" );
}
out.println( "</tr></table>" );*/
}finally {
try { if( null != rs ) rs.close(); } catch( Exception ex ) {}
try { if( null != st ) st.close(); } catch( Exception ex ) {}
try { if( null != cn ) cn.close(); } catch( Exception ex ) {}
}
%> </body>
</html>

Newjsp1.jsp
<%--
Document : index
Created on : Feb 9, 2011, 6:50:54 PM
Author : A
--%>
<%@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>Welcome to Online Examination</title>

Page 27
</head>
<body bgcolor="cyan">
<form name="index" action="newjsp.jsp" method="post">
<center><h1><span><font color="red">Welcome to Online
Examination</font></span></h1>
<br>
<h2><u><span><font color="blue">Instructions to the
Candidates</font></span></u></h2>
<br><h3><ol><li>Fill the correct Registration number.</li>
<br><li>Enter your name.</li>
<br><li>Read the questions carefully.</li>
<br><li>No negative marking.</li></ol></h3>
<br>
<b>Enter your Register number</b>
<input type="text" name="txt_reg">
<b>Enter your Name</b>
<input type="text" name="txt_name"><br><br>
<input name ="submit" value="Submit" type="submit"/>
</center>
</form>
</body>
</html>

Newjsp2.jsp
<%--
Document : report
Created on : Feb 23, 2011, 9:09:37 PM
Author : A
--%>
<%@page import="com.sun.java.swing.plaf.windows.resources.windows_es"%>
<%@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>Exam Report</title>
</head>
<body bgcolor="cyan">
<center><h1>Your Report Card</h1></center>
<%@ page language="java" %>
<%@ page import ="java.sql.*" %>
<%
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String sTable = "exam";
String sSql = "SELECT * FROM " + sTable + "";
String database = "jdbc:odbc:sDBQ";
Connection cn = null;
Statement st = null;
ResultSet rs = null;
try {
cn = DriverManager.getConnection( database ,"sa","");

Page 28
st = cn.createStatement();
rs = st.executeQuery( sSql );
ResultSetMetaData rsmd = rs.getMetaData();
String s1,s2,s3,s4;
int i=1;
int correct=0,incorrect=0,total=0;
out.println("<h2><br><br><center><table border=1 cellpadding=2
cellspacing=2><tr><th>Question</th><th>Your Answer</th><th>Correct
Answer</th><th>Status</th></tr>");
while(rs.next())
{
total++;
s1 = rs.getString(1);
s2 = request.getParameter("opt"+i);
s3 = rs.getString(6);
if(s2.equals(s3))
{ s4="Correct";
correct++;
}
else
{ s4="Incorrect";
incorrect++;
}
out.println("<tr><td>"+s1+"</td><td>"+s2+"</td><td>"+s3+"</td><td>"+s4+"</td></tr
>");
i++;
}
out.println("</table><br><br><table><b><tr><td>Correct
Answers</td><td>"+correct+"</td></tr>");
out.println("<tr><td>Incorrect Answers</td><td>"+incorrect+"</td></tr>");
out.println("<tr><td>Total
Questions</td><td>"+total+"</td></tr></table></b></center></h2>");
}
finally {
try { if( null != rs ) rs.close(); } catch( Exception ex ) {}
try { if( null != st ) st.close(); } catch( Exception ex ) {}
try { if( null != cn ) cn.close(); } catch( Exception ex ) {}
}
%>
</body>
</html>

Page 29
OUTPUT:

Page 30
Page 31
RESULT:
Thus the JSP program for online examination was executed by connecting the SQLSERVER
and result was verified

Page 32
EX NO :6 Dynamic Web Page using Servlets Date :

AIM:
Install TOMCAT web server. Convert the static webpages of program 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 the system.
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…) under lib
6. subdirectories.
7. After this start tomcat by giving the following command at the instll_dir>tomcat>bin
Catalina.bat run
8. At the I.E(web browser) give the url as http;//localhost:8080//tr/htmlfile or servlet url
pattern
9. Portno 8080 is assigned for the tomcat.

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()" />

Page 33
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="reset" value="clear" />
</div>
</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" />

Page 34
</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 />
<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.*;

Page 35
public class login extends HttpServlet
{
public void service(HttpServletRequest req,HttpServletResponse resp)
throws ServletException,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";
ResultSet rs=stmt.executeQuery(sqlstmt);
int flag=0;
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 AGAIN
ID<br><br>");
pw.println("<a href=\"login.html\">press LOGIN to
RETRY</a>");
}
else
{
pw.println("<br><br>VALID LOGIN ID<br><br>"); 58
pw.println("<h3><ul>");
pw.println("<li><a
href=\"profile.html\"><fontcolor=\"black\">USER
PROFILE</font>
</a></li><br><br>");
pw.println("<li><a
href=\"catalog.html\"><fontcolor=\"black\">BOOKS
CATALOG</font></a></li><br><br>");
pw.println("<li><a
href=\"order.html\"><fontcolor=\"black\">ORDER
CONFIRMATION</font>
</a></li></ul><br><br>");
}
pw.println("</body></html>");
}
catch(Exception e)

Page 36
{
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(HttpServletRequest req,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");
String id1=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";
ResultSet rs=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();

Page 37
stmt1.executeUpdate("insert into login
values('"+name+"','"+addr+"',"+no+",'"+id1+"','"+pwd1+"')
;");
pw.println("<br><br>YOUR DETAILS ARE
ENTERED<br><br>");
pw.println("<a href=\"login.html\">press LOGIN to
login</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 extends HttpServlet
{
public void service(HttpServletRequest req,HttpServletResponse resp)
throws ServletException,IOException
{
PrintWriter pw=resp.getWriter();
pw.println("<html><body>");
String id=req.getParameter("id");
try
{
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+""; ResultSet
rs=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;
}

Page 38
if(flag==0)
{
pw.println("<br><br>SORRY INVALID ID TRY AGAIN
ID<br><br>");
pw.println("<a href=\"profile.html\">press HERE to
RETRY</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(HttpServletRequest req,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");
Connection
con=DriverManager.getConnection("jdbc:odbc:orcl","scott","tiger
");
Statement stmt=con.createStatement();
String sqlstmt="select * from book where title=\'"+title+"\'"; ResultSet
rs=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)
{

Page 39
pw.println("<br><br>SORRY INVALID TITLE TRY
AGAIN <br><br>");
pw.println("<a href=\"catalog.html\">press HERE to
RETRY</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 extends HttpServlet
{
public void service(HttpServletRequest req,HttpServletResponse resp)
throws ServletException,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");
Connection
con=DriverManager.getConnection("jdbc:odbc:orcl","scott","tiger
");
Statement stmt=con.createStatement();
String sqlstmt="select id,pwd from login";
ResultSet rs=stmt.executeQuery(sqlstmt);
int flag=0,amount,x;
while(rs.next())
{
if(id.equals(rs.getString(1))&&pwd.equals(rs.getString(2)))
{
flag=1;
}
}
if(flag==0)

Page 40
{
pw.println("<br><br>SORRY INVALID ID TRY AGAIN
ID<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 details
values('"+id+"','"+title+"',"+amount+",'"+cno+"');"); pw.println("<br>YOUR ORDER has
taken<br>");
}
if(flag1==0)
{
pw.println("<br><br><br>SORRY INVALID ID
TRY AGAIN ID<br><br>");
pw.println("<a href=\"order.html\">press HERE to
RETRY</a>");
}
}
pw.println("</body></html>");
con.close();
}
catch(Exception e)
{
resp.sendError(500,e.toString());
}
}
}

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>

Page 41
<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>

Output:

Page 42
Page 43
Page 44
Page 45
Result :

Thus Installing TOMCAT web server and Conversion of the static web pages of
program into dynamic web pages using servlets and cookies was Performed.

Page 46
Ex No : 7 Dynamic Webpage Using 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 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

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>

Login page: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>

Page 47
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>

Page 48
Books catalog page: Catalog.html:
<html>
<body><br /><br /><br />
<form method="post" action="catalog.jsp">
<div align="center"><pre>
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 Confirmation 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>");
String id=request.getParameter("id");
String pwd=request.getParameter("pwd");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection

Page 49
con=DriverManager.getConnection("jdbc:odbc:orcl","scott","tiger"); Statement
stmt=con.createStatement();
String sqlstmt="select id,pwd from login";
ResultSet rs=stmt.executeQuery(sqlstmt);
int flag=0;
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 AGAIN
ID<br><br>");
out.println("<a href=\"login.html\">press LOGIN to
RETRY</a>");
}
else
{
out.println("<br><br>VALID LOGIN ID<br><br>"); out.println("<h3><ul>");
out.println("<li><a
href=\"profile.html\"><fontcolor=\"black\">USER
PROFILE</font>
</a></li><br><br>");
out.println("<li><a
href=\"catalog.html\"><fontcolor=\"black\">BOOKS
CATALOG</font></a></li><br><br>");
out.println("<li><a
href=\"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>");
String name=request.getParameter("name");
String addr=request.getParameter("addr");
String phno=request.getParameter("phno");
String id1=request.getParameter("id");
String pwd1=request.getParameter("pwd");
int no=Integer.parseInt(phno);
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection
con=DriverManager.getConnection("jdbc:odbc:orcl","scott","tiger"); Statement

Page 50
stmt=con.createStatement();
String sqlstmt="select id,pwd from login";
ResultSet rs=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)
{ out.println("<br><br>SORRY INVALID ID ALREADY
EXITS TRY AGAIN WITH NEW ID<br><br>");
out.println("<a href=\"reg.html\">press REGISTER to
RETRY</a>");
}
else
{ Statement stmt1=con.createStatement();
stmt1.executeUpdate("insert into login
values('"+name+"','"+addr+"',"+no+",'"+id1+"','"+pwd1+"');"); out.println("<br><br>YOUR
DETAILS
ARE
ENTERED<br><br>");
out.println("<a href=\"login.html\">press LOGIN to
login</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+""; ResultSet
rs=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>");

Page 51
flag=1;
}
if(flag==0)
{
out.println("<br><br>SORRY INVALID ID TRY AGAIN
ID<br><br>");
out.println("<a href=\"profile.html\">press HERE to
RETRY</a>");
}
out.println("</body></html>");
con.close(); %>

Catalog JSP: Catalog.jsp:


<%@page import="java.sql.*"%>
<%@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+"\'"; ResultSet
rs=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 TRY
AGAIN <br><br>");
out.println("<a href=\"catalog.html\">press HERE to
RETRY</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>");

Page 52
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";
ResultSet rs=stmt.executeQuery(sqlstmt);
int flag=0,amount,x;
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 AGAIN
ID<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 ID
TRY AGAIN ID<br><br>");
out.println("<a href=\"order.html\">press HERE to
RETRY</a>");
}

Page 53
}
out.println("</body></html>");
con.close();
%>

Output:

Page 54
Page 55
Page 56
Result :

Thus Installing TOMCAT web server and Conversion of the static web pages of
program into dynamic web pages using JSP was Performed.

Page 57
EX.No : 8 Information Retrieval from XML Server 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.
Procedure:

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;
}
}
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><th colspan='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>");

Page 58
}
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=15
name="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>
<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>

Page 59
<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 Creation and Saving of 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, was performed.

Page 60
Ex No : 9A Validate the form using PHP regular expression DATE :

Aim:
To write a Program for validate the form using PHP regular expressions

Source Code :

<!DOCTYPE HTML>
<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";
}
}

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";
}

Page 61
}

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"]);
}
}

function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>

<h2>PHP Form Validation Example</h2>


<p><span class="error">* required field</span></p>
<form method="post" action="<?php echo
htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail: <input type="text" name="email">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Website: <input type="text" name="website">
<span class="error"><?php echo $websiteErr;?></span>
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"></textarea>
<br><br>
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<input type="radio" name="gender" value="other">Other
<span class="error">* <?php echo $genderErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>

<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;

Page 62
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>

</body>
</html>

Result :
Thus the Program to validate PHP regular Expression was performed and the output is
verified.

Page 63
Ex. No : 9B PHP stores a form data into database Date :

AIM:

To create a PHP Prohram to store the form data into database and access it.

SOURCE CODE:

<html>
<head>
<title> PHP rEGULATION AND DB UPDATE</title>
<?php
$errname = "";
$errage = "";
$errmobile = "";

if($_POST["ac"]=="login"){
// Full Name must be letters, dash and spaces only
if(preg_match("/^[A-Z][a-zA-Z -]+$/", $_POST["name"]) === 0)
$errname = '<p class="errText">Please enter your full name </p>';
// age must be 2 digits
if(preg_match("/^\d{2}$/", $_POST["age"]) === 0)
$errage = '<p class="errText">Age must be 2 digits</p>';
// Mobile mask 050-0000000
if(preg_match("/^\d{3}-\d{7}$/", $_POST["mobile"]) === 0)
$errmobile = '<p class="errText">Mobile must be in this format: 050-0000000</p>';

// contact to database

$connect = mysql_connect("localhost", "root", "") or die ("Error , check your server


connection.");

mysql_select_db("career_system");

//Get data in local variable

$v_name=$_POST['name'];

$v_age=$_POST['age'];

$v_gender=$_POST['gender'];

$v_mobile =$_POST['mobile'];

$query="insert into applicant(name, age, gender, mobile ) values ('$v_name', '$v_age',


'$v_gender','$v_mobile ')";

mysql_query($query) or die(mysql_error());
}

Page 64
echo "Your information has been received";
}

?>

</head>

<body>
<div align="center">
<p>&nbsp;</p>
</div>
<form name="form1" action="<?php echo $PHP_SELF; ?>" method="POST">
<p>
<input type="hidden" name="ac" value="login">
</p>
<table width="485" border="0">
<tr>
<td width="48">Full Name</td>
<td width="150"><input name="name" type="text" id="name" value="<?php echo
$_POST["name"]; ?>"></td>
<td width="273"><?php if(isset($errname)) echo $errname; ?></td>
</tr>
<tr>
<td>Age</td>
<td><input name="age" type="text" id="age" value="<?php echo $_POST["age"];
?>"></td>
<td><?php if(isset($errage)) echo $errage; ?></td>
</tr>
<tr>
<td>Gender</td>
<td><input name="gender" type="radio" value="Male" checked>
Male
<input name="gender" type="radio" value="Female">
Female</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>Mobile</td>
<td><input name="mobile" type="text" id="mobile" value="<?php echo
$_POST["mobile"]; ?>"></td>
<td><?php if(isset($errmobile)) echo $errmobile; ?></td>
</tr>
<tr>
<td>&nbsp;</td>
<td><input type="submit" name="Submit" value="Submit">
<input name="reset" type="reset" id="reset" value="Reset"></td>
<td>&nbsp;</td>
</tr>
</table>
</form>
</body>

Page 65
</html>

or

$errors = array();

if ($_POST["ac"]=="login") {

if (!preg_match("/^[A-Z][a-zA-Z -]+$/", $_POST['name']))


$errors['name'] = '<p class="errText">Please enter your full name </p>';

if (!preg_match("/^\d{2}$/", $_POST['age']))
$errors['age'] = '<p class="errText">Age must be 2 digits</p>';

// etc...

if (!$errors) {
$query = "
insert into applicant
(name, age, gender, mobile )
values
(
'".mysql_real_escape_string($v_name)."',
'".mysql_real_escape_string($v_age)."',
'".mysql_real_escape_string($v_gender)."',
'".mysql_real_escape_string($v_mobile)."'
)
";

mysql_query($query);
}

// etc...
}

// Later in your HTML:

<tr>
<td>Mobile</td>
<td><input name="mobile" type="text" id="mobile" value="<?php echo
$_POST["mobile"]; ?>"></td>
<td><?php if(isset($errors['mobile'])) echo $errors['mobile'] ?></td>
</tr>

or

Make sure to escape data before sending it to the database (hence, the
mysql_real_escape_string calls)! An important piece of advice would be to actually abandon

Page 66
the mysql_ functions as they are antiquated. You should use PDO instead. It's much easier,
more efficient and eliminates much of the SQL injection threat with little effort:

try {
$dbh = new PDO("mysql:host=localhost;dbname=mydb", 'username', 'password');
} catch(PDOException $e) {
die('Could not connect to database!');
}

$stm = $dbh->prepare('INSERT INTO applicant (name, age, gender, mobile ) VALUES (?, ?,
?, ?)');
$stm->execute(array($v_name, $v_age, $v_gender, $v_mobile));

Result : Thus the PHP Program on storing the data into database was created.

Page 67
Ex No : 10 Web Service for Customer Product Date :

AIM:
To implement a application using the web services.

ALGORITHM:
1.Start the program
2.Create a root rocess for reservation
3.Create a service with focus on each item
4.Run the program, display the result
5.Stop the program.

SOURCE CODE:
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!-- Solution11.16 -->
<!-- Airline Reservation System-->
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>Airline Reservation System</title>
<script type = "text/javascript">
<!--
var input;
var secondInput;
var element;
var secondElement;
var firstCount = 0;
var economyCount = 0;
var seats = [ ,0,0,0,0,0,0,0,0,0,0]; //allocate 10-element Array
function startArray()
{
for(var i=0; i<11; i++)
{
input = window.prompt("Please type 1 for First Class and Please type 2 for Economy.","0");
if (input == 1 || input == 2)
{
element = linearSearch(seats);
if(element==-1&&input==1)
{
document.writeln("The First Class is already fully
booked<br/>");
secondQuestion(seats);
}
else if (element ==-1 && input == 2)
{
document.writeln("The Economy Class is already fully
booked<br/>");
secondQuestion(seats);

Page 68
}
else
boarding Pass(input);
}
//to terminate the program
else
{
window.status="Bye-bye!";
System.exit(0);
}
}
}
function linear Search(the Array)
{
if (input == 1)
{
for (var n=0; n<6 ; n++)
if (the Array [n] == 0)
return n;
}
else if (input == 2)
{
for (var n=6; n<11 ; n++)
if (the Array [n] == 0)
return n;
}
return -1;
}
function boarding Pass(the Input)
{
if (input ==1)
{
document.writeln("----------BOARDING PASS----------<br/>");
document.writeln("You are allocated in the First Class<br/>");
document.writeln("Your seat number is "+ element+"<br/>");
document.writeln("-----------------------------------------<br/>");
seats[element]= 1;
firstCount++;
}
else if (input ==2)
{
document.writeln("----------BOARDING PASS----------<br/>");
document.writeln("You are allocated in the EconomyClass<br/>"); document.writeln("Your
seat
number is "+ element +"<br/>");
document.writeln("-----------------------------------------<br/>");
seats[element]= 1;
economyCount++;
}
}
functionsecondQuestion(theArray)
{

Page 69
if (input == 1)
{
for (var n=6; n<11 ;n++)
{
if (theArray [n] == 0)
{
second Input = window.prompt("Do you want to move to Economy Class?
(If YES, please press 1. If NO, please press 2)","0");
if ( second Input == 1)
{
input = 2;
element=linear Search(seats);
document.writeln("You have been allocated to Economy
Class<br/>");
boardingPass(input);
break;
}
else if (secondInput == 2)
{
document.writeln("Next flight leaves in 3 hours<br/>"); break;
}
}
}
}
else if (input == 2)
{
for (var n=0; n<6 ;n++)
{
if (theArray [n] == 0)
{
secondInput = window.prompt("Do you want to move to First Class? (If YES,
please press 1. If NO, please press 2)","0");
for (var n=0; n<6 ;n++)
{
if (theArray [n] == 0)
{
secondInput = window.prompt("Do you want to move to First Class? (If YES, please press 1.
If
NO, please press 2)","0");
boarding Pass(input); break;
}
else if (secondInput == 2)
{
document.writeln("Next flight leaves in 3 hours<br/>");
break;
}
}}
}
}
//-->
</script>
</head>

Page 70
<body onload = "startArray()"></body>
</html>

OUTPUT:

RESULT:
Thus the program is executed and verified successfully.

Page 71

You might also like