Web Technologies Lab Manual
Web Technologies Lab Manual
Aim:
To create a web page which includes a map and display the related information
when a hot spot is clicked in the map.
Procedure:
Create a html file with map tag
Set the source attribute of the img tag to the location of the image and also set
the use map attribute
Specify an area with name, shape and href set to the appropriate values
Repeat step 3 as many hot spots you want to put in the map
Create html files for each and every hot spot the user will select
Program:
ImageMap.html
<HTML>
<HEAD>
<TITLE>Image Map</TITLE>
</HEAD>
<BODY>
<img src="india_map.jpg" usemap="#metroid" ismap="ismap" >
<map name="metroid" id="metroid">
<area href='TamilNadu.html' shape='circle' coords='175,495,30' title='TamilNadu'/>
<area href = "Karnataka.html" shape = "rect" coords = "100,400,150,450" title =
"Karnataka" /> <area href = "AndhraPradesh.html" shape = "poly" coords = "150,
415, 175,348,265,360,190,420,190,440" title = "Andhra Pradesh" />
<area href = "Kerala.html" shape = "poly" coords =
"108,455,150,515,115,490,148,495,110,448,155,501" title
= "Kerala" /> </map>
</BODY>
</HTML>
TamilNadu.html
<HTML>
<HEAD>
<TITLE>About Tamil Nadu</TITLE>
</HEAD>
<BODY>
<CENTER><H1>Tamil Nadu</H1></CENTER> <HR>
<UL>
<LI>Area : 1,30,058 Sq. Kms.</LI>
<LI>Capital : Chennai</LI>
1
<LI>Language : Tamil</LI>
<LI>Population : 6,21,10,839</LI> </UL><hr>
<a href='ImageMap.html'>India Map</a>
</BODY>
</HTML>
Karnataka.html
<HTML>
<HEAD>
<TITLE>About Karnataka</TITLE> </HEAD>
<BODY>
<CENTER><H1>Karnataka</H1></CENTER>
<HR>
<UL>
<LI>Area : 1,91,791 Sq. Kms</LI>
<LI>Capital : Bangalore</LI>
<LI>Language : Kannada</LI>
<LI>Population : 5,27,33,958</LI>
</UL>
<hr>
<a href='ImageMap.html'>India Map</a>
</BODY>
</HTML>
AndhraPradesh.html
<HTML>
<HEAD>
<TITLE>About Andhra Pradesh</TITLE> </HEAD>
<BODY>
<CENTER><H1>Andhra Pradesh</H1></CENTER> <HR>
<UL>
<LI>Area : 2,75,068 Sq. Kms</LI>
<LI>Capital : Hyderabad</LI>
<LI>Language : Telugu</LI>
<LI>Population : 7,57,27,541</LI>
</UL>
<hr>
<a href='ImageMap.html'>India Map</a>
</BODY>
</HTML>
Kerala.html
<HTML>
<HEAD>
<TITLE>About Kerala</TITLE>
</HEAD>
2
<BODY>
<CENTER>
<H1>Kerala</H1></CENTER>
<HR>
<UL>
<LI>Area : 38,863 Sq. Kms.</LI>
<LI>Capital : Thiruvananthapuram</LI>
<LI>Language : Malayalam</LI>
<LI>Population : 3,18,38,619</LI>
</UL>
<hr>
<a href='ImageMap.html'>India Map</a>
</BODY>
</HTML>
Output:
3
Result:
Thus the creation of a web page which includes a map and display the related
in-formation when a hot spot is clicked in the map was executed successfully
4
2. CASCADING STYLE SHEETS
Aim:
To create a web page that displays college information using various style sheet
Procedure:
Create a web page with frame sets consisting two frames
In the first frame include the links
In the second frame set display the web page of the link
Create a external style sheets
Create a embedded style sheets
Create a inline and internal style sheets and make it link to the external style
sheets
Program:
CSS CODE:
External.css
h3{font-family:arial;font-size:20;color:cyan}
table{border-color:green}
td{font-size:20pt;color:magenta}
HTML CODE:
Style.html
<html>
<head><h1><center>ALL STYLE SHEETS</center></h1>
<title>USE of STYLESHEETS
</title>
<link rel="stylesheet" href="External.css" type="text/css"> <!-- External Style Sheet
-->
<style type="text/css"> <!-- Internal Style Sheet -->
.S1{font-family:verdana; font-style:italic; color:red; text-align:center}
.S2{font-family:tahoma; font-style:italic; font-size:20; text-align:center;}
font{font-family:georgia; color:blue; font-size:20}
ul{list-style-type:circle}
</style>
</head>
<body>
<ol style="list-style-type:lower-alpha">
<b> Anna University </b><br><br><br>
<li> University College of Engineering, Nagercoil
<li> University College of Engineering, Nellai
<li> University College of Engineering, Tuticorin
</ol>
5
<p style="font-size:20pt;color:purple">
University College of Engineering</p> <!-- InlineStyle Sheet -->
<p class="S2"> Run by Anna University, Chennai<br>
It is approved by AICTE.
<br>
</p>
Output:
Result:
Thus the creation of a web page that displays college information using various
style sheet was successfully executed and verified.
7
3 RETRIEVING USER INFORMATION FROM XML DOCUMENT
Aim:
To create and save an XML document at the server, which contain ten users
information. To write a program which takes user id as an input and returns the user
details by taking the user information from the XML document.
Procedure:
Save Students information in the XML file on the specific location.
Create and establish the connection between html file and XML file.
Get the user ID as input
Display the student’s information.
StudentDetails.xml :
<?xml version="1.0" encoding="UTF-8"?>
<Student>
<PersonDetails>
<id>101</id>
<name>Anand</name>
<city>Madurai</city>
<Branch>CSE</Branch>
<Year>I</Year>
</PersonDetails>
<PersonDetails>
<id>102</id>
<name>Anu</name>
<city>Konam</city>
<Branch>CSE</Branch>
<Year>II</Year>
</PersonDetails>
<PersonDetails>
<id>103</id>
<name>Archana</name>
<city>Madurai</city>
<Branch>CSE</Branch>
<Year>I</Year>
</PersonDetails>
<PersonDetails>
<id>104</id>
<name>Monica</name>
<city>Nellai</city>
<Branch>CSE</Branch>
<Year>III</Year>
</PersonDetails>
</Student>
8
LogIn.html :
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script type="text/javascript">
function Display()
if(window.XMLHttpRequest)
xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","UserInfo.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
var x=xmlDoc.getElementsByTagName("PersonDetails");
var key_id=document.getElementById("key").value;
for(i=0;i<x.length;i++)
if(key_id.match(x[i].getElementsByTagName("id")[0].childNodes[0].nodeValue))
j=i;
document.write(x[j].getElementsByTagName("id")[0].childNodes[0].nodeValue);
document.write("</br> Name=");
document.write(x[j].getElementsByTagName("name")[0].childNodes[0].nodeValue);
9
document.write("</br> City=");
document.write(x[j].getElementsByTagName("city")[0].childNodes[0].nodeValue);
document.write("</br> Branch=");
document.write(x[j].getElementsByTagName("Branch")[0].childNodes[0].nodeValue);
document.write("</br> Year=");
document.write(x[j].getElementsByTagName("Year")[0].childNodes[0].nodeValue);
document.write("</br> ");
</script>
<form name='myform'>
Enter ID:
</form>
</body>
</html>
Output:
10
Result:
Thus the Program takes user id as an input and returns the user details by taking
the user information from the XML document has been executed successfully.
11
4. CREATING SIMPLE CHAT APPLICATION
Aim:
Write a program in Java for creating simple chat application with datagram sockets
and datagram packets.
Procedure:
Server Side:
step 1: Import net and io packages and class
step 2: Create a datagram socket object.
step 3: Create datagram packet to send result to client using the send()method
step 4: Send the data to client.
step 5: Repeat step 3 and 4 until process completes.
Step 6: When process finished close the connection.
Client Side:
step 1: Import net and io packages
step 2: Create a datagram socket object
step 3: Create datagram packet to receive data from other clients
step 4: Listen for the packet from client using the receive() method.
Step5: Process received packets.
Step6: When process finished close the connection.
Step7: Exit the chat room after chatting.
Server Program:
import java.io.*;
import java.util.*;
import java.net.*;
Client Program:
import java.io.*;
import java.net.*;
clientPort = (int)(50000*Math.random());
while(true)
{
try
{
clientSocket = new DatagramSocket(clientPort);
}
catch(BindException e)
{
clientPort = (int)(50000*Math.random());
while(clientPort<1023 || clientPort>65536)
{
clientPort = (int)(50000 * Math.random());
}
continue;
}
break;
}
14
System.out.println("\nSession for clients has started.You can terminate it by
typing/exit");
System.out.print("\nEnter your name:");
BufferedReader buff = new BufferedReader(new InputStreamReader(System.in));
String clientName = buff.readLine();
String startmsg = clientName+"$##$"+clientPort;
byte sendBuffer[] = startmsg.getBytes();
clientSocket.connect(InetAddress.getLocalHost(),1024);
clientSocket.send(new DatagramPacket(sendBuffer,sendBuffer.length));
Thread th = new Thread(new Client());
th.start();
while(true)
{
String msg = buff.readLine();
msg = "!$"+clientName+"!$"+msg;
sendBuffer = msg.getBytes();
clientSocket.send(new DatagramPacket(sendBuffer,sendBuffer.length));
if(msg.indexOf("/exit")!=-1)
break;
}
th.join();
buff.close();
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
finally
{
clientSocket.close();
}
}
static DatagramSocket clientSocket = null;
static int clientPort;
Output:
Result:
Thus the Java program for creating simple chat application with datagram sockets and
datagram packets has been executed successfully.
16
5.1 INVOKING SERVLETS FROM HTML FORM
Aim:
To write a java program to invoke servlets from HTML form.
Procedure:
client.html:
(1) Create a web page using HTML form that contains the fields such as label,text
and one submit
button.
(2) Set the URL of the server as the value of form’s action attribute.
(3) Run the HTML program.
(4) Submit the form data to the server.
server.java:
(1) Define the class server that extends the property of the class GenericServlet.
(2) Handle the request from the client by using the method service() of
GenericServlet class.
(3) Get the parameter names from the HTML form by using the method
getParameterNames().
(4) Get the parameter values from the HTML forms by using the method
getParameter().
(5) Send the response to the client by using the method of PrintWriter class.
Program:
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServletHtmlDemo extends HttpServlet
{
public void service(HttpServletRequest req,HttpServletResponse res) throws
ServletException,IOException
{
PrintWriter out = res.getWriter();
Enumeration en = req.getParameterNames();
while(en.hasMoreElements())
{
String name=(String)en.nextElement();
out.print(name+"=");
String value=req.getParameter(name);
out.println(value);
out.println(" ");
}
}
17
}
web.xml:
<web-app>
<servlet>
<servlet-name>MyServletHtmlDemo</servlet-name>
<servlet-class>MyServletHtmlDemo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyServletHtmlDemo</servlet-name>
<url-pattern>/MyServletHtmlDemo</url-pattern>
</servlet-mapping>
</web-app>
MyServletHtmlDemo.HTML:
<html>
<head>
<title>Student Information Form</title>
</head>
<body>
<form name="form1" acti
<center>
on="MyServletHtmlDemo">
<h3>Enter student information in following fields</h3>
<table>
<tr>
<td><b>Roll Number</b></td>
<td><input type="text" name="Roll Number" size="25" value=""></td>
</tr>
<tr>
<td><b>Student Name</b></td>
<td><input type="text" name="Student Name" size="25" value=""></td>
</tr>
<tr>
<td><b>Student Address</b></td>
<td><input type="text" name="Address" size="25" value=""></td>
</tr>
<tr>
<td><b>Phone</b></td>
<td><input type="text" name="Phone" size="25" value=""></td>
</tr>
<tr>
<td><b>Total Marks</b></td>
<td><input type="text" name="Total Marks " size="25" value=""></td>
</tr>
18
</table>
<input type="submit" value="submit">
</form>
</center>
</body>
</html>
Output:
Result:
Thus the java program to invoke servlets from HTML form has been executed
successfully.
19
5. SESSION TRACKING USING HIDDEN FORM FIELDS
Aim:
To perform session tracking using hidden form fields.
Procedure:
1. Create a html file which contains user information.
2. The first servlet will receive these values.
3. First servlet stores them in the hidden form fields.
4. The second servlet will display the user information with greeting message.
Program:
HTML CODE
<html>
<head>
<title>Session Tracking Using Hidden Form Field</title>
</head>
<body>
<form action="Servlet1">
Enter Name:<input type="text" name="username"/><br/>
Enter city:<input type="text" name="usercity"/><br/>
<input type="submit" value="submit"/>
</form>
</body>
</html>
SERVLET1
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Servlet1 extends HttpServlet
{
public void doGet(HttpServletRequest request,HttpServletResponse response)
{
try
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("username");
String c=request.getParameter("usercity");
out.print("<form action=\"Servlet2\">");
out.print("<input type='hidden' name='uname' value="+n+"'>");
out.print("<input type='submit' value='Just click here'>");
out.print("</form>");
20
out.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
SERVLET2
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
Output
21
Result:
Thus the Java Program for Session Tracking Using Hidden Form Fields has
been executed successfully.
22
5.3 SESSION TRACKING A HIT COUNT
Aim:
To write a Java Program for Session tracking a hit count. This servlet uses
session tracking to count the number of times a client has accessed it.
Procedure:
1. Servlet program to keep track of user visiting the page.
2. The count is incremented by one when user visits.
3. The output displays the greeting message.
4. The number of previous access is also displayed.
Program:
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SessionServletDemo extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse res) throws
ServletException,IOException
{
res.setContentType("text/html");
HttpSession session = req.getSession();
String heading;
Integer cnt=(Integer)session.getAttribute("cnt");
if(cnt==null)
{
cnt=new Integer(0);
heading="Welcome you are accessing the page for the first time";
}
else
{
heading="Welcome once again";
cnt=new Integer(cnt.intValue()+1);
}
session.setAttribute("cnt",cnt);
PrintWriter out = res.getWriter();
out.println("<html>");
out.println("<head>");
out.println("</head>");
23
out.println("<body>");
out.println("<center>");
out.println("<h1>"+heading);
out.println("<h2>The number of previous access="+cnt);
out.println("</center>");
out.println("</body>");
out.println("</html>");
}
}
Output:
Result:
Thus the Java program for Session tracking a hit count has been executed
successfully.
24
6. THREE-TIER APPLICATIONS USING SERVLETS
Aim:
To write java servlet programs to conduct online examination and to display
student mark list available in a database
Procedure:
Client:
In index.html on the client side declare the contents that you like to transfer to
the server using html form and input type tags.
Create a submit button and close all the included tags.
Server:
Import all necessary packages
Define a class that extends servlet
In the doPost() method, do the following:
i) Set the content type of the response to "text/html"
ii) Create a writer to the response
iii) Get a paratmeter from the request
iv) If its value is equal to right answer then add 5 to mark variable
v) Similarly repeat step
vi) for all parameters
vii) Display the result in an html format using the writer
Student Mark List Database:
Import necessary to java packages and javax packages and classes
Create a class that extends HttpServlet and implements ServletException
and IOException
In the doGet() method, do the following:
i) Create a PrintWriter object
ii) Open a connection with the data source name
iii) Write a sql query and execute to get the resultset
iv) Display the resultset information in html form
Program:
SERVLET CODE:
import java.io.*; import java.sql.*; import javax.servlet.*;
import javax.servlet.http.*;
public class StudentServlet3 extends HttpServlet
{
String message,Seat_no,Name,ans1,ans2,ans3,ans4,ans5; int Total=0;
Connection connect; Statement stmt=null; ResultSet rs=null;
public void doPost(HttpServletRequest request,HttpServletResponse response) throws
ServletExcep-tion,IOException
{
try
25
{
String url="jdbc:odbc:NEO"; Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
connect=DriverManager.getConnection(url," "," "); 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("False"))
Total+=2;
if(ans3.equals("True"))
Total+=2;
if(ans4.equals("False"))
Total+=2;
if(ans5.equals("False"))
Total+=2; try
{
Statement stmt=connect.createStatement();
String query="INSERT INTO student("+"Seat_no,Name,Total"+") VAL-
UES('"+Seat_no+"','"+Name+"','"+Total+"')";
int result=stmt.executeUpdate(query); stmt.close();
}catch(SQLException ex){
}
response.setContentType("text/html"); PrintWriter out=response.getWriter();
out.println("<html>"); out.println("<head>"); out.println("</head>"); out.println("<body
bgcolor=cyan>"); out.println("<center>"); out.println("<h1>"+message+"</h1>\n");
26
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;
}}
HTML CODE:
<html><head><title>Database Test</title></head> <body>
<center><h1>Online Examination</h1> </center>
<form action="StudentServlet3.view" 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. It is a network layer's responsibility to forward packets reliably from source to
destina-tion</b><br/>
<input type="radio" name="group2" value="True">True
<input type="radio" name="group2" value="False">False<br>
<b>3. Packet switching is more useful in bursty traffic</b><br/> <input type="radio"
27
name="group3" value="True">True<input type="radio" name="group3"
value="False">False<br> <b>4. A phone network uses packet switching</b><br/>
<input type="radio" name="group4" value="True">True <input type="radio"
name="group4" value="False">False<br>
<b>5. HTML is a Protocol for describing web contents</b><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>
Output:
Result:
Thus to write java servlet programs to conduct online examination and to
display student mark list available in a database was successfully executed and
verified
28
CONVERTING STATIC WEB PAGES TO DYNAMIC WEB PAGES
Aim:
To convert the static web pages into dynamic web pages using servlets (or JSP)
and cookies.
Procedure:
step1: we will create ahtml form for entering the user name,password and card
ID.
Step2:From the above HTML form, the servlet program is invoked in which
the validity of the user name,password and card id is checked.if it is a valid user then
the welcome message will be displayed otherwise the “invalid user” message will be
displayed. In this servlet we set the cookies in which the current user name is stored.
Step3: compile the above servlet Login servlet.java and copy its class file in
tomcats folder at c:\tomcatdirectory\webapps\examples\WEB-INF\classes.
Then edit the web.xml in WEB-INF folder.We must store he user information
such as user name,password and card id in the web.xml using init-param.
Step4: On successful login , the information from the cookie is checked and
shopping cart page for corressponding user can be displayed.
Step5:Compile the above servlet LoginSuccess.java and copy its class file in
the tomcat's folder at c:\tomcatdirectory\webapps\examples\WEB-INF\classes.
Then edit the web.xml in WEB-INF folder.
Step6:Start tomcat web server.Open the web browser and display the login
form created in step1.
Index.jsp
<html>
<head>
<body>
<form action="http://localhost:8084/ddd/LoginServlet" method="post">
Enter username:
<input type="text" value""name="user">
<br>
Enter Password:
<input type="password" value""name="password">
<br>
Enter Card ID:
29
<input type="text" value""name="cardID">
<br>
<br> <br> <br>
<input type="submit" value="login">
</form>
</body>
Loginservlet.html
import java.io.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
String usr=request.getParameter("user");
String pwd=request.getParameter("password");
String card=request.getParameter("cardID");
boolean flag=true;
String[] userID=getInitParameter("usernames").split(",");
String[] password=getInitParameter("passwords").split(",");
String[] cardids=getInitParameter("cardIDs").split(",");
int i;
for(i=0;i<userID.length;i++)
{
if(userID[i].equals(usr)&&password[i].equals(pwd)&&cardids[i].equals(card))
{
flag=false;
Cookie MyCookie=new Cookie("CurrentUser", usr);
MyCookie.setMaxAge(60*60);
response.addCookie(MyCookie);
response.sendRedirect("http://localhost:8084/ddd/LoginSuccess");
30
}
}
if(flag==true)
{
out.print("Error");
out.println("<h4>Invalid user,please try again by clicking following
link</h4>");
out.println("<a href='http://localhost:8084/ddd/'>"+"LoginForm.html");
}
}
finally {
out.close();
}
}
LoginSuccess.java
import java.io.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class LoginSuccess extends HttpServlet {protected void
doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Cookie[] my_cookies=request.getCookies();
response.setContentType("text/html");
PrintWriter out=response.getWriter();
out.print("Login Success");
out.println("<b>");
String userName=null;
if(my_cookies!=null)
{
for(Cookie cookie:my_cookies)
{
if(cookie.getName().equals("currentUser"))
userName=cookie.getValue();
}
}
out.print("<h3>Login Success!!!Welcome</h3>");
31
out.print("<h2>This is a Shopping cart for"+userName+"</h2>");
out.close();
}
}
Web.xml
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>LoginServlet</servlet-class>
<init-param>
<param-name>usernames</param-name>
<param-value>user1,user2,user3</param-value>
</init-param>
<init-param>
<param-name>passwords</param-name>
<param-value>pwd1,pwd2,pwd3</param-value>
</init-param>
<init-param>
<param-name>cardIDs</param-name>
<param-value>111,222,333</param-value>
</init-param>
</servlet>
<servlet>
<servlet-name>LoginSuccess</servlet-name>
<servlet-class>LoginSuccess</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>LoginSuccess</servlet-name>
<url-pattern>/LoginSuccess</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
32
</session-config>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
Output:
33
34
Result:
Thus the conversion of the static web pages into dynamic web pages using servlets
cookies has been executed successfully.
35
3.2.2 AJAX PROGRAM FOR GETTING INSTANT LOGIN FEEDBACK
Aim:
To write Ajax Program for Getting instant login feedback.
Procedure:
Type the wrong login name, get a new page explaining the problem, have to log
in on another page.
Enter an incorrect username and password, and the application says
immediately that user name or password Error.
Program:
Login.php
<?php
if ($_GET[“qu”] == “steve”){
echo “taken”;
}
else {
echo “ok”;
}
?>
Login.html
<body>
<H1>Choose a username</H1>
Enter your new username <input id = “textField” type = “text”
name = “textField” onkeyup = “checkUsername(event)”>
<div id = “targetDiv”><div></div></div>
</body>
function checkUsername(keyEvent)
{
keyEvent = (keyEvent) ? keyEvent: window.event;
input = (keyEvent.target) ? keyEvent.target :
keyEvent.srcElement;
if (keyEvent.type == “keyup”) {
var targetDiv = document.getElementById(“targetDiv”);
targetDiv.innerHTML = “<div></div>”;
if (input.value) {
getData(“login.php?qu=” +
input.value);
36
}}}
function getData(dataSource)
{
if(XMLHttpRequestObject) {
XMLHttpRequestObject.open(“GET”, dataSource);
XMLHttpRequestObject.onreadystatechange = function()
{
if (XMLHttpRequestObject.readyState == 4 &&
XMLHttpRequestObject.status == 200) {
if(XMLHttpRequestObject.responseText == “taken”){
var targetDiv = document.getElementById(“targetDiv”);
targetDiv.innerHTML = “<div>That username is taken.</div>”;
}}}
XMLHttpRequestObject.send(null);
}}
Output:
Result:
Thus the Ajax Program for Getting instant login feedback has been executed
successfully.
37
3.4 WRITE A WEB SERVICES FOR PREDICTING FOR ANY PRODUCT
SALES
Aim:
To write a web services for predicting for any product sales
Procedure:
Open the Home page.
View the 2 products.
Put the rating by user.
Display the high rating product on the top of the page.
Program:
Page.html
<!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>
$('.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'
38
);
});
$('.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());
}
);
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) {
$(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;
40
}
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
41
class ratings {
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() {
$ID = $this->widget_id;
# Update the record if it exists
if($this->data[$ID]) {
$this->data[$ID]['number_votes'] += 1;
42
$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;
}
file_put_contents($this->data_file, serialize($this->data));
$this->get_ratings();
}
# ---
# end class
}
Output:
Result:
43
Thus the web services for predicting for any product sales has been executed
successfully.
44