Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Prepared By: CS8661 Internet Programming Lab Manual

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

NADAR SARASWATHI COLLEGE OF ENGINEERING &

TECHNOLOGY

Vadapudupatti, Theni - 625531

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

Regulation 2017

CS8661
INTERNET PROGRAMMING LAB MANUAL

III Year / VI Sem

Prepared By
S.Arthy, AP/CSE
NADAR SARASWATHI COLLEGE OF ENGINEERING AND TECHNOLOGY

VISION

 Place for Technology Revolution

MISSION

 Promote and undertake all – inclusive developments.

 Develop high quality technical education with academic excellence and

innovative research with ethics.

 Create an atmosphere where teacher enjoys facilitation and

learners(students) enjoy learning through foster innovation.

 Collaborate with industry and academic to meet the changing needs of

society.

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

VISION

 Become an International hub for computer architects (or soft computing

professionals)

MISSION

 Providing a strong theoretical and practical background with an emphasis

on software development.

 Encourage self-learning, foster Interactions and partnerships with world

class computer technocrats for technical growth.

 Inculcating professional behaviour, strong ethical values, innovative

research capabilities and leadership abilities


PROGRAM EDUCATIONAL OBJECTIVES (PEOs)
1. To enrich the knowledge of students to get graduation in the field of computer science and
engineering and pursue professional development in the software field or as entrepreneurs.
2. To participate in research and thrive in multi-disciplinary, systems oriented work
environment in team work with professional ethics.
3. To contribute the solution to the complex problems as a professional engineer for society
and strive to promote a practice of integrity, tolerance, leadership and respect in the work
place.
PROGRAM OUTCOMES (POs)
Engineering Graduates will be able to:
1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering
fundamentals and an engineering specialization to the solution of complex engineering
problems.
2. Problem analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of
mathematics, natural sciences, and engineering sciences.
3. Design/development of solutions: Design solutions for complex engineering problems and
design system components or processes that meet the specified needs with appropriate
consideration for the public health and safety, and the cultural, societal, and environmental
considerations.
4. Conduct investigations of complex problems: Use research-based knowledge and
research methods including design of experiments, analysis and interpretation of data, and
synthesis of the information to provide valid conclusions.
5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modeling to complex engineering activities
with an understanding of the limitations.
6. The engineer and society: Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to
the professional engineering practice.
7. Environment and sustainability: Understand the impact of the professional engineering
solutions in societal and environmental contexts, and demonstrate the knowledge of, and need
for sustainable development.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.
9. Individual and team work: Function effectively as an individual, and as a member or leader
in diverse teams, and in multidisciplinary settings.
10. Communication: Communicate effectively on complex engineering activities with the
engineering community and with society at large, such as, being able to comprehend and write
effective reports and design documentation, make effective presentations, and give and receive
clear instructions.
11. Project management and finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one ‘s own work, as a member and
leader in a team, to manage projects and in multidisciplinary environments.
12. Life-long learning: Recognize the need for, and have the preparation and ability to engage
in independent and life-long learning in the broadest context of technological change.
PROGRAM SPECIFIC OBJECTIVES (PSOs)
1. To analyze, design and develop computing solutions by applying foundational concepts of
Computer Science and Engineering.
2. To apply software engineering principles and practices for developing quality software for
scientific and business applications.
3. To adapt to emerging Information and Communication Technologies (ICT) to innovate ideas
and solutions to existing/novel problems
SYLLABUS

CS8661 INTERNET PROGRAMMING LABORATORY LTPC


0 0 4 2
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 online
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.

CO – PO, PSO Correlation Matrix: (3- > Strong, 2- > Moderate, 1 – >Low)

CO-PO,PSO PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12 PSO1 PSO2 PSO3

C607.1 3 1 3 3 1 3 3 2 1 3

C607.2 3 2 2 3 2 3 2 2

C607.3 3 3 3 1 1 2

C607.4 3 2 3 3 2 2 1

C607.5 3 2 3 3 2 1 2
EX.NO:1 IMAGE MAPPING
AIM
To write a map and fix the hotspots to show the information of it in a web page.
PROCEDURE
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.
PROGRAM

indiamap.jpeg

mainpage.html
<html>
<head>
<title>India Map</title>
<head>
<body bgcolor="PINK">
<font face="Monotype Corsiva" color="BLUE" size="6">
<marquee direction="left" behavior="alternate">INDIA MAP
</marquee>
</font>
<hr size="6" color="RED">
<map name="pagemap">
<area shape="rect" title="Orissa" coords="330,325,340,340" href="orissa.html">
<area shape="rect" title="Maharashtra" coords="168,330,175,360"
href="maharashtra.html">
<area shape="rect" title="Karnataka" coords="168,432,176,442" href="karnataka.html">
<area shape="rect" title="Kerala" coords="170,510,185,530" href="kerala.html">
<area shape="rect" title="Tamilnadu" coords="210,505,220,520" href="tamilnadu.html">
<area shape="rect" title="Madhyapradesh" coords="223,268,240,275"
href="madhyapradesh.html">
</map>
<img src="indiamap.jpeg" usemap="#pagemap">
</body>
<font color="#ff0000" size="5">
<p><b>Hints:</b><i>Click on the Name of the Cities in the map to know its
description</i></p>
</html>
tamilnadu.html
<html>
<head>
<body bgcolor="#FFE4C4"/>
<center><h2>It is a tamilnadu, here maximum tamilan living and capital of tamilnadu is
</h2><h1>chennai<h1></center>
</head>
</html>
orissa.html
<html>
<head>
<body bgcolor="#DDA0DD"/>
<center><h2>It is a orissa,here maximum oreya living and capital of orissa is</h2>
<h1>Bhubaneswar</h1></center></head></html>
maharashtra.html
<html>
<head>
<body bgcolor="#FFB6C1"/>
<center>It is a maharashtra,here maximum maratiyam living and capital of maharashtra is
<h1>Mumbai</h1></center>
</head>
</html>
madhyapradesh.html
<html>
<head>
<body bgcolor="lightskyblue"/>
<center>It is a madhyapradesh,here maximum maratiyam living and capital of
Madhyapradesh is <h1>BHOPAL</h1></center>
</head>
</html>
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>
karnataka.html
<html>
<head>
<body bgcolor="#90EE90"/>
<center>It is a karnataka,here maximum kannadam living and capital of karnataka is
<h1>Bangalore</h1></center>
</head>
</html>
OUTPUT

Main Page

Tamilnadu

Karnataka
Madhyapradesh

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.
EX.NO:2 STYLE SHEET
AIM
To write a webpage that displays college information using various style sheet.
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 an external style sheets.
6. Create an inline and internal style and make a link to the external style sheet.
7. Stop the program.
PROGRAM

mainpage.html

<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 :underline;"> 1. Inline Style Sheet</a><br />
<a href ="embedded.html" style="text-decoration :underline;"> 2. Embeded Style
Sheet</a><br />
<a href ="external.html" style="text-decoration :underline;"> 3. External Style
Sheet</a><br />
</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>
external.html
<html>
<head>
<title>External Style Sheet</title>
<link rel=Stylesheet href="mystyle.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 formatting the
entire site as well as restyling it by editing just one file</h3>
</body>
</html>
mystyle.css
body {
background-color: lightblue;
}
h1 {
color: white;
text-align: center;
}
h3{
font-family: verdana;
font-size: 20px;
}

embed.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 />
<h3>
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 will apply to the entire documents.
</h3></ol>
</body>
</html>

OUTPUT
Main Page

Inline Style Sheet


Embedded Style Sheet

External Style Sheets


RESULT
Thus the web page is created using all types of cascading style sheets successfully and the
output is also verified.

EX.NO:3 WEBSITE VALIDATION USING JAVA SCRIPT


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.
PROGRAM

mainpage.html
<html>
<frameset rows="25%,*">
<frame src="top.html" name="top" scrolling ="no" frameborder ="0">
<frameset cols="25%,75%">
<frame src="left.html" name="left" scrolling ="no" frameborder ="0">
<frame src="right.html" name="right" scrolling ="auto" frameborder ="0">
</frameset>
</frameset>
</html>
left.html
<html>
<body bgcolor="green">
<h3>
<ul>
<li><a href="profile.html" target="right"><fontcolor="blue"> USER
PROFILE</font></a></li><br>
<br>
<li><a href="login.html" target="right"><font color="blue">
LOGIN</font></a></li><br><br>
<li><a href="catalog.html" target="right"><fontcolor="blue"> BOOKS
CATALOG</font></a></li>
<br><br>
<li><a href="scart.html" target="right"><font color="blue">
SHOPPINGCART</font></a></li><br>
<br>
<li><a href="payment.html" target="right"><fontcolor="blue">
PAYMENT</font></a></li><br><br>
<li><a href="order.html" target="right"><font color="blue"> ORDER
CONFIRMATION</font></a>
</li><br><br>
</ul>
</body>
</html>

right.html
<html>
<body bgcolor="green">
<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>
top.html
<html>
<body bgcolor="yellowgreen">
<br><br>
<marquee><h1 align="left"><b><u>ONLINE BOOK STORAGE</u></b></h1></marquee>
</body>
</html>
profile.html
<html>
<body bgcolor="lightskyblue"><br><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">
<div align="center"><pre>
NAME :<input type="text" name="name"><br>
ADDRESS :<input type="type" name="addr"><br>
PHONE NUMBER :<input type="text" name="phno"><br>
LOGINID :<input type="text" name="id"><br>
PASSWORD :<input type="password" name="pwd"></pre><br><br>
</div>
<br><br>
<div align="center">
<input type="submit" value="ok" onClick="validate()">
<input type="reset" value="clear">
</form></body></html>
login.html
<html>
<body bgcolor="lightskyblue"><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>
<form name="myform">
<div align="center"><pre>
LOGIN ID :<input type="text" name="id"><br>
PASSWORD :<input type="password" name="pwd">
</pre><br><br>
</div>
<br><br>
<div align="center">
<input type="submit" value="ok" onClick="validate()">
<input type="reset" value="clear" >
</form>
</body>
</html>
catalog.html
<html>
<body bgcolor="lightskyblue"><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");
}
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()">
<input type="reset" value="clear">
</form>
</body>
</html>
scart.html
<html>
<body bgcolor="lightskyblue"><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>
<form name="myform" >
<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" onClick="validate()">
<input type="reset" value="clear">
</form>
</body>
</html>

payment.html
<html>
<body bgcolor="lightskyblue"><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=new RegExp("\\d","g");
if(!(str.match(x)))
{ flag=0;
}
var str1=document.myform.num.value;
var x1=new RegExp("\\d","g");
if(!(str.match(x1)))
{ flag=0;
}
if(flag==1)
{
alert("VALID INPUT");
window.self.location.href="order.html";
}
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="button" value="ok" onClick="validate()">&nbsp;&nbsp;&nbsp;&nbsp;
<input type="reset" value="clear" >
</form>
</body>
</html>
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>
OUTPUT

Main Page
User Profile
Login Page
Books Catalog
Shopping Cart

Payment Page
Order Conformation

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
EX.NO:4 INVOKE SERVLETS FROM HTML FORMS
AIM
To write a java program for invoking servlet from HTML form.
PROCEDURE
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.
PROGRAM
index.html
<html>
<form action="servlet1">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
</html>

FirstServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(urlPatterns = {"/FirstServlet"})
public class FirstServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response){
try{

response.setContentType("text/html");
PrintWriter out = response.getWriter();

String n=request.getParameter("userName");
out.print("Welcome "+n);

//creating form that have invisible textfield


out.print("<form action='servlet2'>");
out.print("<input type='hidden' name='uname' value='"+n+"'>");
out.print("<input type='submit' value='go'>");
out.print("</form>");
out.close();

}catch(Exception e){System.out.println(e);}
}
}
SecondServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
import java.util.Enumeration;
/**
*
* @author CSE
*/
@WebServlet(urlPatterns = {"/SecondServlet"})
public class SecondServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
HttpSession session = request.getSession(true);
Date createTime = new Date(session.getCreationTime());
Date lastAccessTime = new Date(session.getLastAccessedTime());

String title = "Welcome Back to my website";


Integer visitCount = new Integer(0);
String visitCountKey = new String("visitCount");
String userIDKey = new String("userID");
String userID = new String("ABCD");

// Check if this is new comer on your web page.


if (session.isNew())
{
title = "Welcome to my website";
session.setAttribute(userIDKey, userID);
}
else {
visitCount = (Integer)session.getAttribute(visitCountKey);
visitCount = visitCount + 1;
userID = (String)session.getAttribute(userIDKey);
}
session.setAttribute(visitCountKey, visitCount);
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("uname");
out.print("Hello "+n);
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\n";

out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +

"<body bgcolor = \"#f0f0f0\">\n" +


"<h1 align = \"center\">" + title + "</h1>\n" +
"<h2 align = \"center\">Session Infomation</h2>\n" +
"<table border = \"1\" align = \"center\">\n" +

"<tr bgcolor = \"#949494\">\n" +


" <th>Session info</th><th>value</th> </tr>\n" +

"<tr>\n" +
" <td>id</td>\n" +
" <td>" + session.getId() + "</td> </tr>\n" +

"<tr>\n" +
" <td>Creation Time</td>\n" +
" <td>" + createTime + " </td> </tr>\n" +

"<tr>\n" +
" <td>Time of Last Access</td>\n" +
" <td>" + lastAccessTime + " </td> </tr>\n" +

"<tr>\n" +
" <td>User ID</td>\n" +
" <td>" + userID + " </td> </tr>\n" +

"<tr>\n" +
" <td>Number of visits</td>\n" +
" <td>" + visitCount + "</td> </tr>\n" +
"</table>\n" +
"</body> </html>"
);
}
}
web.xml
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>

<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
</web-app>
OUTPUT
RESULT

Thus the program for invoking servlet from HTML form was executed and the output
was verified.
EX.NO:5 THREE TIER APPLICATION USING JSP
AIM
To write the Servlet program for online examination.
PROCEDURE
1. Start the xampp control panel then select admin from mysql to create database and table.
Created new database onlinexam and the table name login with three empty column such as
Seat_No, Name and Total

2. Enable Netbeans IDE to create new project


3. Select services tab and then right click on Databases to click new connection
4. Select driver as Mysql(connector/Jdriver) then click next button
5. Change the database name as ‘onlinexam’ and then click Test connection to check the
connectivity. Press finish button once u get connection successes.
6. Create new java web application project. Select Tomcat Server and then select hibernate
framework. In that framework select database connection link that have database name
onlineexam

6. Create the forms in index.html


7. Right click on source packages then select new and then select servlet to give name as
“StudentServlet3” and write a coding for database connectivity.
8. Right click on Libraries to select Add Library. It will display global library box, from that
select Mysql JDBC Driver.
9. Execute the program.
PROGRAM
index.html
<html>
<head>
<title>Database Test</title>
</head>
<body>
<center><h1>Online Examination</h1> </center>

<form action="StudentServlet3" 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>

<br><br>

<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. Operating System is a </b><br/>


<input type="radio" name="group2" value="Hardware">Hardware
<input type="radio" name="group2" value="Softwar">Software<br>

<b>3. Developers of C Language is </b><br/>


<input type="radio" name="group3" value="Dennis Richee">Dennis Richee
<input type="radio" name="group3" value="James Thompson">James Thompson<br>

<b>4. Father of Computer is </b><br/>


<input type="radio" name="group4" value="Charless Babbage">Charless Babbage
<input type="radio" name="group4" value="Charless Dickson">Charless Dickson<br>

<b>5. HTML is a Protocol for describing web contents</b><br/>


<input type="radio" name="group5" value="True">True
<input type="radio" name="group5" value="False">False<br> <br><br><br>

<center>

<input type="submit" value="Submit"><br><br> </center>

</form></body></html>

StudentServlet3
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
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; ResultSet rs=null;
/**
*
* @param request
* @param response
* @throws ServletExcep
*/
@Override
public void doPost(HttpServletRequest request,HttpServletResponse response) throws
ServletException,IOException
{
try
{
Class.forName("com.mysql.jdbc.Driver");
connect =
DriverManager.getConnection("jdbc:mysql://localhost:3306/onlineexam?zeroDateTimeBeha
vior=convertToNull","root","");
message="Thank you for participating in online Exam";
}
catch(ClassNotFoundException cnfex){ cnfex.printStackTrace();
}
catch(SQLException sqlex){ sqlex.printStackTrace();
}
catch(Exception excp){ excp.printStackTrace();
}
Seat_no=request.getParameter("Seat_no");
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("Software"))
Total+=2;
if(ans3.equals("Dennis Richee"))

Total+=2;

if(ans4.equals("Charless Babbage"))
Total+=2;
if(ans5.equals("False"))
Total+=2;

try
{

Statement st=connect.createStatement();
String query="Insert into login(Seat_No,Name,Total)"+"
values('"+Seat_no+"','"+Name+"','"+Total+"');";

st.executeUpdate(query);
st.close();
}
catch(Exception excp){
excp.printStackTrace();
}

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 Seat_No, Name, Total FROM login WHERE Name='"+Name+"';";
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>");
}
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;
}
}
OUTPUT
RESULT

Thus the Servlet program for online examination was executed by connecting the
SQLSERVER and result was verified
EX.NO: 6 DYNAMIC WEB PAGE USING SERVLETS

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. Start the xampp control panel then select admin from mysql to create database and table.
Created new database dynamic and create three table such as
a) Table - profile (attributes – name, address, phno, id, pwd as empty column)
b) Table - book (attributes – title, author, publisher, cost with some data’s)
c) Table - details (attributes – id, title, amount, cno as empty column)
2. Enable Netbeans IDE to create new project
3. Select services tab and then right click on Databases to click new connection
4. Select driver as Mysql(connector/Jdriver) then click next button
5. Change the database name as ‘dynamic’ and then click Test connection to check the
connectivity. Press finish button once u get connection successes.
6. Create new java web application project. Select Tomcat Server and then select hibernate
framework. In that framework select database connection link that have database name as
‘jdbc:mysql://localhost:3306/dynamic?zeroDateTimeBehavior=convertToNull [root on
Default schema]’.
6. Create the forms in index.html, login.html, reg.html, catalog.html, profile.html, order.html
7. Right click on source packages then select new and then select servlet to give name as
“login.java”, order.java, catalog.java, reg1.java, profile.java and also select ‘Add information to
deployment descriptor web.xml’ and write a coding for database connectivity.
8. Right click on Libraries to select Add Library. It will display global library box, from that
select Mysql JDBC Driver.
9. Execute the program.
PROGRAM
index.html - Home Page
<!DOCTYPE html>
<html>
<body bgcolor="cyan">
<br /><br /><br /><br /><br />
<h1 align="center"><U>ONLINE BOOK STORAGE</U></h1><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/><pre>
<div align="center"><a href="login.html">LOGIN</a><br><br>
<a href="reg.html">REGISTRATION</a></div>
</pre>
</body>
</html>
reg.html - Registration Page
<!DOCTYPE html>
<html>
<body bgcolor="cyan"><br /><br />
<form name="myform" method="post" action="reg1">
<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()" />
<input type="reset" value="clear" />
</div>
</form>
</body>
</html>

login.html - Login Page


<!DOCTYPE html>
<html>
<body bgcolor="cyan"><br /><br /><br />
<form name="myform" method="post" action="login">
<div align="center"><pre>
LOGIN ID :<input type="text" name="id" /><br /><br><br>
PASSWORD :<input type="password" name="pwd"/></pre><br /><br />
</div>
<br /><br />
<div align="center">
<input type="submit" value="ok" onclick="validate()" />
<input type="reset" value="clear" />
</div>
</form>
</body>
</html>

profile.html - User Profile Page


<!DOCTYPE html>
<html>
<body bgcolor="cyan"><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()" />
<input type="reset" value="clear" />
</div>
</form>
</body>
</html>

catalog.html - Books Catalog Page


<!DOCTYPE html>
<html>
<body bgcolor="cyan"><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"/>
<input type="reset" value="clear" name="button2"/>
</div>
</form>
</body>
</html>

order.html - Order Conformation Page


<!DOCTYPE html>
<html>
<body bgcolor="cyan"><br /><br />
<form method="post" action="order">
<div align="center"><pre>
ID:<input type="text" name="id" /><br />
TITLE:<input type="text" name="title" /><br />
NO. OF BOOKS:<input type="text" name="no" /><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"/>
<input type="reset" value="clear"
name="button2"/>
</div>
</form></body></html>

Servlet Programs

reg1.java - Registration Servlet


import java.sql.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class reg1 extends HttpServlet
{
ResultSet rs=null;
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");
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/dynamic?zeroDateTimeBehavio
r=convertToNull","root","");
Statement stmt1=con.createStatement();
String sqlstmt="select id,pwd from profile";
rs=stmt1.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("<body bgcolor=pink>");
pw.println("<div align=\"center\">");
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 stmt=con.createStatement();
String query1= "Insert into profile (name,address,phno,id,pwd)" + "
values('"+name+"','"+addr+"','"+phno+"','"+id1+"','"+pwd1+"');";
stmt.executeUpdate(query1);
pw.println("<body bgcolor=pink>");
pw.println("<div align=\"center\">");
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());
}
}
}

login.java - Login Servlet


import java.sql.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
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("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/dynamic?zeroDateTimeBehavio
r=convertToNull","root","");
Statement stmt=con.createStatement();
String sqlstmt="select id,pwd from profile";
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("<body bgcolor=pink>");
pw.println("<div align=\"center\">");
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><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)
{
resp.sendError(500,e.toString());
}
}
}

profile.java - Profile Servlet


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("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/dynamic?zeroDateTimeBehavio
r=convertToNull","root","");
Statement stmt=con.createStatement();
String sqlstmt="select * from profile where id='"+id+"';";
ResultSet rs=stmt.executeQuery(sqlstmt);
int flag=0;
pw.println("<br><br><br>");
while(rs.next())
{
pw.println("<body bgcolor=pink>");
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("<body bgcolor=pink>");
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.java - Catalog Servlet


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("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/dynamic?zeroDateTimeBehavio
r=convertToNull","root","");
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("<body bgcolor=pink>");
pw.println("<div align=\"center\">");
pw.println("TITLE:"+rs.getString(1)+"<br>");
pw.println("AUTHOR :"+rs.getString(2)+"<br>");
pw.println("PUBLISHER :"+rs.getString(3)+"<br>");
pw.println("COST:"+rs.getString(4)+"<br>");
pw.println("</div>");
flag=1;
}
if(flag==0)
{
pw.println("<body bgcolor=pink>");
pw.println("<div align=\"center\">");
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.java - Order servlet


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 title=req.getParameter("title");
String count1=req.getParameter("no");
String cno1=req.getParameter("cno");
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/dynamic?zeroDateTimeBehavio
r=convertToNull","root","");
Statement stmt1=con.createStatement();
stmt1.executeUpdate("insert into details values('"+id+"','"+title+"',"+count1+",'"+cno1+"');");
pw.println("<body bgcolor=pink>");
pw.println("<div align=\"center\">");
pw.println("<br>YOUR ORDER has taken<br>");
pw.println("</body></html>");
con.close();
}
catch(Exception e)
{
resp.sendError(500,e.toString());
}
}
}

OUTPUT
Home Page
User Registration Page
Login Page
User Profile
Books Catalog
Order Conformation
Database Details

Profile Table

Books Table
Details Table (Order Detail)

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.
EX.NO:7 DYNAMIC WEBPAGE USING JSP

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. Start the xampp control panel then select admin from mysql to create database and table.
Created new database dynamic and create three table such as
a) Table - profile (attributes – name, address, phno, id, pwd as empty column)
b) Table - book (attributes – title, author, publisher, cost with some data’s)
c) Table - details (attributes – id, title, amount, cno as empty column)
2. Enable Netbeans IDE to create new project
3. Select services tab and then right click on Databases to click new connection
4. Select driver as Mysql(connector/Jdriver) then click next button
5. Change the database name as ‘dynamic’ and then click Test connection to check the
connectivity. Press finish button once u get connection successes.
6. Create new java web application project. Select Tomcat Server and then select hibernate
framework. In that framework select database connection link that have database name as
‘jdbc:mysql://localhost:3306/jspdynamic?zeroDateTimeBehavior=convertToNull [root on
Default schema]’.
6. Create the forms in index.html, login.html, reg.html, catalog.html, profile.html, order.html
7. Right click on source packages then select new and then select servlet to give name as
“login.jsp”, order.jsp, catalog.jsp, reg.jsp, profile.jsp and also select ‘Add information to
deployment descriptor web.xml’ and write a coding for database connectivity.
8. Right click on Libraries to select Add Library. It will display global library box, from that
select Mysql JDBC Driver.
9. Execute the program.
PROGRAM
Home page: index.html:
<!DOCTYPE html>
<html>
<body bgcolor="cyan">
<br>
<h1 align="center"><u>ONLINE BOOK STORAGE</u></h1><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><pre>
<div align="center"><a href="login.html">LOGIN</a> <br>
<a href="reg.html">REGISTRATION</a></div></pre>
</body></html>

Login page: login.html:


<!DOCTYPE html>
<html>
<body bgcolor="cyan"> <br /><br /><br />
<form name="myform" method="post" action="login.jsp">
<div align="center"><pre>
LOGIN ID :<input type="text" name="id" /><br/>
<br>
PASSWORD :<input type="password" name="pwd"/></pre><br /><br />
</div>
<br /><br />
<div align="center">
<input type="submit" value="ok" onclick="validate()" />
<input type="reset" value="clear" />
</div>
</form>
</body>
</html>

Registration page: reg.html:


<!DOCTYPE html>
<html>
<body bgcolor="cyan"> <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> <br>
<tr>
<td>ADDRESS</td>
<td>:<input type="text" name="addr" /></td><br>
</tr>
<tr>
<td>CONTACT NUMBER</td>
<td>:<input type="text" name="phno" /></td><br>
</tr>
<tr>
<td>LOGIN ID</td>
<td>:<input type="text" name="id" /></td>
</tr>
<tr>
<td>PASSWORD</td>
<td>:<input type="password" name="pwd" /></td><br>
</tr>
</table>
<br /><br />
<div align="center">
<input type="submit" value="ok" onclick="validate()" />
<input type="reset" value="clear" />
</div>
</form>
</body>
</html>
User profile page: profile.html:
<!DOCTYPE html>
<html>
<body bgcolor="cyan"> <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()" />
<input type="reset" value="clear" />
</div>
</form>
</body>
</html>

Books catalog page: catalog.html:


<!DOCTYPE html>
<html>
<body bgcolor="cyan"><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"/>
<input type="reset" value="clear" name="button2"/>
</div>
</form>
</body> </html>

Shopping cart, Payment by credit card, Order Confirmation page: order.html:


<!DOCTYPE html>
<html>
<body bgcolor="cyan"><br /><br />
<form method="post" action="order.jsp">
<div align="center"><pre>
ID:<input type="text" name="id" /><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"/>
<input type="reset" value="clear"
name="button2"/>
</div>
</form>
</body>
</html>

Login JSP: login.jsp


<%@ page import="java.io.*,java.util.*,java.sql.*" %>
<%@ page import="javax.servlet.http.*,javax.servlet.*"%>
<% out.println("<html><body>");
String id=request.getParameter("id");
String pwd=request.getParameter("pwd");
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/jspdynamic?zeroDateTimeBeha
vior=convertToNull","root","");
Statement stmt=con.createStatement();
String sqlstmt="select id,pwd from profile";
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("<body bgcolor=pink>");
out.println("<div align=\"center\">");
out.println("<br><br>SORRY INVALID ID TRY AGAIN ID<br><br>");
out.println("<a href=\"login.html\">Press LOGIN to RETRY</a>");
}
else
{
Statement stmt1=con.createStatement();
String sql= "select name from profile where id = \'"+id+"\'";
ResultSet rs1=stmt1.executeQuery(sql);
out.println("<body bgcolor=pink>");
out.println("<div align=\"center\">");
out.println("<br><br>VALID LOGIN ID<br><br>");
while(rs1.next())
{
out.println("Welcome :"+rs1.getString(1)+"<br><br>");
}
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


<% 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");
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/jspdynamic?zeroDateTimeBeha
vior=convertToNull","root","");
Statement stmt=con.createStatement();
String sqlstmt="select id,pwd from profile";
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("<body bgcolor=pink>");
out.println("<div align=\"center\">");
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 profile
values('"+name+"','"+addr+"',"+phno+",'"+id1+"','"+pwd1+"');");
out.println("<body bgcolor=pink>");
out.println("<div align=\"center\">");
out.println("<br><br>YOUR DETAILS ARE ENTERED SUCCESSFULLY<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.io.*,java.util.*,java.sql.*" %>
<%@ page import="javax.servlet.http.*,javax.servlet.*"%>
<% out.println("<html><body>");
String id=request.getParameter("id");
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/jspdynamic?zeroDateTimeBeha
vior=convertToNull","root","");
Statement stmt=con.createStatement();
String sqlstmt="select * from profile where id=\'"+id+"\'";
ResultSet rs=stmt.executeQuery(sqlstmt);
int flag=0;
out.println("<br><br><br>");
while(rs.next())
{
out.println("<body bgcolor=pink>");
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("<body bgcolor=pink>");
out.println("<div align=\"center\">");
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.io.*,java.util.*,java.sql.*" %>
<%@ page import="javax.servlet.http.*,javax.servlet.*"%>
<% out.println("<html><body>");
String title=request.getParameter("title");
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/jspdynamic?zeroDateTimeBeha
vior=convertToNull","root","");
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("<body bgcolor=pink>");
out.println("<div align=\"center\">");
out.println("TITLE:"+rs.getString(1)+"<br>");
out.println("AUTHOR :"+rs.getString(2)+"<br>");
out.println("PUBLISHER :"+rs.getString(3)+"<br>");
out.println("COST:"+rs.getString(4)+"<br>");
out.println("GO BACK <br>");
flag=1;
}
if(flag==0)
{
out.println("<body bgcolor=pink>");
out.println("<div align=\"center\">");
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.jsp


<%@ page import="java.io.*,java.util.*,java.sql.*" %>
<%@ page import="javax.servlet.http.*,javax.servlet.*"%>
<% out.println("<html><body>");
out.println("<html><body>");
out.println("<body bgcolor=pink>");
out.println("<div align=\"center\">");
String id=request.getParameter("id");
String title=request.getParameter("title");
String count=request.getParameter("no");
String date=request.getParameter("date");
String cno=request.getParameter("cno");
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/jspdynamic?zeroDateTimeBeha
vior=convertToNull","root","");
Statement stmt1=con.createStatement();
stmt1.executeUpdate("insert into details
values('"+id+"','"+title+"',"+count+",'"+date+"','"+cno+"');");
out.println("<br>YOUR ORDER HAS TAKEN SUCCESSFULLY<br>");
out.println("</body></html>");
con.close();
%>
OUTPUT

Main Page

Registration Page
Login Page
Profile Page
Books Catalog
Order Conformation
Database Details

Profile Table
Book Table

Details Table

RESULT

Thus Installing TOMCAT web server and Conversion of the static web pages of program
into dynamic web pages using JSP was Performed.
EX.NO:8 Information Retrieval from XML Server
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.
PROCEDUR
1) Create a simple Java project through java application. We have created the class file with
the name JavaStudents.
2) Create an XML file in any folder using notepad. We have created an XML file with
name XMLFile.xml and write the following data into it.
3) Download dom-2.3.0-jaxb-1.0.6.jar file
4) Add jar file through Libraries.
5) Run the project
PROGRAM
XMLFile.xml
<?xml version="1.0" encoding="UTF-8"?>
<students>
<student id="501">
<firstName>Sunil</firstName>
<lastName>Yadav</lastName>
<percentage>72%</percentage>
</student>
<student id="502">
<firstName>Trilok</firstName>
<lastName>Reddy</lastName>
<percentage>86%</percentage>
</student>
<student id="503">
<firstName>Mallikarjun</firstName>
<lastName>Tiger</lastName>
<percentage>98%</percentage>
</student>
<student id="504">
<firstName>Neelima</firstName>
<lastName>Lakshmi</lastName>
<percentage>MP</percentage>
</student>
<student id="505">
<firstName>Abhi</firstName>
<lastName>Shambu</lastName>
<percentage>55%</percentage>
</student>
</students>
JavaStudents.java
package javastudents;
import java.io.BufferedReader;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.File;
import java.io.InputStreamReader;
public class JavaStudents
{
public static void main(String[] args)
{
try
{
File file = new File("D:\\XMLFile.xml");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(file);
Element root = document.getDocumentElement();
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter User Id");
String id=br.readLine();
NodeList nList = document.getElementsByTagName("student");
System.out.println(root.getNodeName());
System.out.println("============================");
for (int temp = 0; temp < nList.getLength(); temp++)
{
Node node = nList.item(temp);
System.out.println("");
if (node.getNodeType() == Node.ELEMENT_NODE)
{
Element eElement = (Element) node;
if(eElement.getAttribute("id").equals(id))
{
System.out.println("Student id : " + eElement.getAttribute("id"));
System.out.println("First Name : " +
eElement.getElementsByTagName("firstName").item(0).getTextContent());
System.out.println("Last Name : " +
eElement.getElementsByTagName("lastName").item(0).getTextContent());
System.out.println("Percentage : " +
eElement.getElementsByTagName("percentage").item(0).getTextContent());
}
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
OUTPUT

RESULT

Thus Creation and Saving of an XML document at the server, which contains 10 user’s
information. Write program, which takes user ID as input and returns the user details by taking
the user information from XML Document, was performed.
EX.NO: 9 (i) VALIDATE THE FORM USING PHP REGULAR EXPRESSION

AIM
To write a Program for validate the form using PHP regular expressions
PROCEDURE
1. Start
2. Choose php application from PHP in NetBeans
3. PHP validates the data at the server-side, which is submitted by HTML form.
4. Need to validate a few things:
i) Empty String
ii) Validate String
iii) Validate Numbers
iv) Validate Email
v) Validate URL
vi) Input length
5. Validates that the user clicks on submit button and send the form data to the server one
of the following method - get or post
6. Create a registration form using HTML and perform server-side validation
7. Apply all these validations to an HTML form to validate the fields
PROGRAM
<!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";
}
}
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
if(isset($_POST['submit']))
{
if($nameErr == "" && $emailErr == "" && $genderErr == "" && $websiteErr == "" )
{
echo "<h3 color = #FF0001> <b>You have sucessfully registered.</b> </h3>";
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
}
else
{
echo "<h3> <b>You didn't filled up the form correctly.</b> </h3>";
}
}
?>
</body>
</html>

OUTPUT
RESULT

Thus the Program to validate PHP regular Expression was performed and the output is verified.
EX.NO: 9(ii) PHP STORES A FORM DATA INTO DATABASE

AIM
To create a PHP Program to store the form data into database and access it

PROCEDURE

1. Start XAMPP Server.


2. Open localhost/phpmyadmin in your web browser.
3. Create database of name staff and table of Name College.
4. Write HTML and PHP code in your php application in a netbeans.
5. Submit data through HTML Form.
6. Verify the results

PROGRAM
index.php

<!DOCTYPE html>
<html lang="en">

<head>
<title>GFG- Store Data</title>
</head>

<body>
<center>
<h1>Storing Form data in Database</h1>

<form action="insert.php" method="post">

<p>
<label for="firstName">First Name:</label>
<input type="text" name="first_name" id="firstName">
</p>

<p>
<label for="lastName">Last Name:</label>
<input type="text" name="last_name" id="lastName">
</p>

<p>
<label for="Gender">Gender:</label>
<input type="text" name="gender" id="Gender">
</p>

<p>
<label for="Address">Address:</label>
<input type="text" name="address" id="Address">
</p>
<p>
<label for="emailAddress">Email Address:</label>
<input type="text" name="email" id="emailAddress">
</p>
<input type="submit" value="Submit">
</form>
</center>
</body>
</html>

insert.php
<!DOCTYPE html>
<html>
<head>
<title>Insert Page page</title>
</head>

<body>
<center>
<?php

// servername => localhost


// username => root
// password => empty
// database name => staff
$conn = mysqli_connect("localhost", "root", "", "staff");

// Check connection
if($conn === false)
{
die("ERROR: Could not connect . " . mysqli_connect_error());
}

// Taking all 5 values from the form data(input)


$first_name = $_REQUEST['first_name'];
$last_name = $_REQUEST['last_name'];
$gender = $_REQUEST['gender'];
$address = $_REQUEST['address'];
$email = $_REQUEST['email'];

// Performing insert query execution


// here our table name is college
$sql = "INSERT INTO college VALUES ('$first_name',
'$last_name','$gender','$address','$email')";

if(mysqli_query($conn, $sql))
{
echo "<h3>data stored in a database successfully."
. " Please browse your localhost php my admin"
. " to view the updated data</h3>";
echo nl2br("\n$first_name\n $last_name\n "
. "$gender\n $address\n $email");
}
else
{
echo "ERROR: Hush! Sorry $sql . " . mysqli_error($conn);
}

// Close connection
mysqli_close($conn);
?>
</center>
</body>

</html>

OUTPUT
Database

RESULT

Thus the PHP Program on storing the data into database was created.
EX.NO:10 WEB SERVICE FOR CUSTOMER PRODUCT

AIM
To implement an application using the web services.

PROCEDURE
1. Start the program
2. Create a php project
3. Create a service with focus on each item using index.php and ratings.php
4. Create some image using star in png form such as star_full, star_empty and
star_highlight. Store these images in same project folder.
5. Run the program, display the result
6. Stop the program.

PROGRAM

index.php
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd"
>
<html lang="en">
<head>
<title>AJAX 5 Star Rating</title>

<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>

// This is the first thing we add ------------------------------------------


$(document).ready(function() {

$('.rate_widget').each(function(i) {
var widget = this;
var out_data = {
widget_id : $(widget).attr('id'),
fetch: 1
};
$.post(
'ratings.php',
out_data,
function(INFO) {
$(widget).data( 'fsr', INFO );
set_votes(widget);
},
'json'
);
});

$('.ratings_stars').hover(
// Handles the mouseover
function() {
$(this).prevAll().andSelf().addClass('ratings_over');
$(this).nextAll().removeClass('ratings_vote');
},
// Handles the mouseout
function() {
$(this).prevAll().andSelf().removeClass('ratings_over');
// can't use 'this' because it wont contain the updated data
set_votes($(this).parent());
}
);

// This actually records the vote


$('.ratings_stars').bind('click', function() {
var star = this;
var widget = $(this).parent();

var clicked_data = {
clicked_on : $(star).attr('class'),
widget_id : $(star).parent().attr('id')
};
$.post(
'ratings.php',
clicked_data,
function(INFO) {
widget.data( 'fsr', INFO );
set_votes(widget);
},
'json'
);
});

});

function set_votes(widget) {

var avg = $(widget).data('fsr').whole_avg;


var votes = $(widget).data('fsr').number_votes;
var exact = $(widget).data('fsr').dec_avg;

window.console && console.log('and now in set_votes, it thinks the fsr is ' +


$(widget).data('fsr').number_votes);

$(widget).find('.star_' + avg).prevAll().andSelf().addClass('ratings_vote');
$(widget).find('.star_' + avg).nextAll().removeClass('ratings_vote');
$(widget).find('.total_votes').text( votes + ' votes recorded (' + exact + ' rating)' );
}
// END FIRST THING
</script>
<style>
.rate_widget {
border: 1px solid #CCC;
overflow: visible;
padding: 10px;
position: relative;
width: 180px;
height: 32px;
}
.ratings_stars {
background: url('star_empty.png') no-repeat;
float: left;
height: 28px;
padding: 2px;
width: 32px;
}
.ratings_vote {
background: url('star_full.png') no-repeat;
}
.ratings_over {
background: url('star_highlight.png') no-repeat;
}
.total_votes {
background: #eaeaea;
top: 58px;
left: 0;
padding: 5px;
position: absolute;
}
.movie_choice {
font: 10px verdana, sans-serif;
margin: 0 auto 40px auto;
width: 180px;
}
h1 {
text-align: center;
width: 400px;
margin: 20px auto;
}
</style>
</head>
<body>
<h1> Rate the following movies! </h1>
<div class='movie_choice'>
Rate: Raiders of the Lost Ark
<div id="r1" class="rate_widget">
<div class="star_1 ratings_stars"></div>
<div class="star_2 ratings_stars"></div>
<div class="star_3 ratings_stars"></div>
<div class="star_4 ratings_stars"></div>
<div class="star_5 ratings_stars"></div>
<div class="total_votes">vote data</div>
</div>
</div>

<div class='movie_choice'>
Rate: The Hunt for Red October
<div id="r2" class="rate_widget">
<div class="star_1 ratings_stars"></div>
<div class="star_2 ratings_stars"></div>
<div class="star_3 ratings_stars"></div>
<div class="star_4 ratings_stars"></div>
<div class="star_5 ratings_stars"></div>
<div class="total_votes">vote data</div>
</div>
</div>
</body>
</html>

ratings.php

<?php

$rating = new ratings($_POST['widget_id']);

isset($_POST['fetch']) ? $rating->get_ratings() : $rating->vote();

class ratings {

var $data_file = './ratings.data.txt';


private $widget_id;
private $data = array();

function __construct($wid) {

$this->widget_id = $wid;

$all = file_get_contents($this->data_file);

if($all) {
$this->data = unserialize($all);
}
}
public function get_ratings() {
if($this->data[$this->widget_id]) {
echo json_encode($this->data[$this->widget_id]);
}
else {
$data['widget_id'] = $this->widget_id;
$data['number_votes'] = 0;
$data['total_points'] = 0;
$data['dec_avg'] = 0;
$data['whole_avg'] = 0;
echo json_encode($data);
}
}
public function vote() {

# Get the value of the vote


preg_match('/star_([1-5]{1})/', $_POST['clicked_on'], $match);
$vote = $match[1];

$ID = $this->widget_id;
# Update the record if it exists
if($this->data[$ID]) {
$this->data[$ID]['number_votes'] += 1;
$this->data[$ID]['total_points'] += $vote;
}
# Create a new one if it doesn't
else {
$this->data[$ID]['number_votes'] = 1;
$this->data[$ID]['total_points'] = $vote;
}

$this->data[$ID]['dec_avg'] = round( $this->data[$ID]['total_points'] / $this-


>data[$ID]['number_votes'], 1 );
$this->data[$ID]['whole_avg'] = round( $this->data[$ID]['dec_avg'] );

file_put_contents($this->data_file, serialize($this->data));
$this->get_ratings();
}

# ---
# end class
}
OUTPUT
- star_full

- star_highlight

- star_empty

Result:
Thus the web services for predicting for any product sales has been executed
successfully.

You might also like