You are on page 1of 123

1.

1 WEB PAGE CREATION USING HTML

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

5
</ol>

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

<h2 class="S1"> University College of Engineering</h2>


<br>
<font>Located in Konam, Nagercoil</font><br>
<br>
<font>
<h2>List of Courses offered</h2>
<ul>
<li>CSE</li>
<li>IT</li>
<li>ECE</li>
<li>EEE</li>
<li>MECH</li>
<li>Civil</li>
</ul>
</font>
<h3>Pass percentage in year 2015</h3>
<table width="100%" cellspacing="2" cellpadding="2" border="5">
<tr>
<th>Sl.No</th>
<th>Dept</th>
<th>Pass Percentage</th>
</tr>
<tr>
<td align="center">1</td>
<td align="center">CSE</td>
<td align="center">80</td>
</tr>
<tr>
<td align="center">2</td>
<td align="center">ECE</td>
<td align="center">78</td>
</tr>
<tr>
<td align="center">3</td>
<td align="center">Mech</td>
<td align="center">75</td>
6
</tr>

</table>
</body>
</html>

Output:

Result:
Thus the creation of a web page that displays college information using various
style sheet was successfully executed and verified.

7
1.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("<h3>User Details are...</h3> <hr> Registeration ID=");

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:

<input type='text' id='key'/><br/>

<input type='button' value='submit' onclick='Display()'/>

</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
2.1.1. HTTP REQUEST

Aim:
To write a java socket program to demonstrate HTTP Request.

Algorithm:
 Import all the necessary packages
 Create an URL to the server specifying the html page
 Get the host and port details from the URL
 Request the file from the server using GET method of HTTP Request
 Receive the response from the server
 Display the response on the console

Program:
import java.io.*;
import java.net.*;
public class HTTP
{
public static void main(String[] args)
{
try
{
OutputStream to_file = new FileOutputStream("f:\\temp.txt");
URL url = new
URL("http://www.msn.com/news/results.aspx");
String protocol = url.getProtocol();
String host = url.getHost();
int port = url.getPort();
if(port == -1) port = 80;
String filename =url.getFile();
System.out.println(filename);
Socket socket = new Socket(host, port);
InputStream from_server = socket.getInputStream();
PrintWriter to_server = new PrintWriter(socket.getOutputStream());
to_server.print("Get" + filename +"\n\n");
to_server.flush();
byte[] buffer = new byte[4096];
int byte_read;
while((byte_read = from_server.read(buffer)) != -1)
{
to_file.write(buffer,0,byte_read);
System.out.print((char)byte_read);
}
socket.close();

12
to_file.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}}

Output:

Result:
Thus the java socket program to demonstrate HTTP Request has been executed
successfully.

13
2.1.2 FTP – FILE TRANSFER PROTOCOL

Aim:
To write a java program to demonstrate a simple FTP operation.

Algorithm:

Procedure:
FTP Client:
Step 1: Establish a connection with the server at a particular port
Step 2: Specify the name of the file to be read
Step 3: Receive the contents of the file from the server
FTP Server:
Step 1: Accept the connection with the client
Step 2: Listen to the port for the name of the file to be sent
Step 3: Send the file character by character
Step 4: Terminate the connection

Program:
//FTP Client:
import java.io.*;
import java.net.*;
public class FTPClient
{
public static void main(String[] args)
{
try
{
Socket client = new Socket("127.0.0.1",10000);
PrintWriter writer = new PrintWriter(client.getOutputStream());
writer.println("f:/demo/HTTP.java");
writer.flush();
InputStreamReader stream = new InputStreamReader(client.getInputStream());
BufferedReader reader = new BufferedReader(stream);
String str = null;
while((str = reader.readLine()) != null)
{
System.out.println(str);
}
reader.close();
}
catch(Exception e)
{
System.out.println("Connection is terminated by the Server");
}}}
14
FTP Server:
import java.io.*;
import java.net.*;
public class FTPServer
{
public static void main(String[] arg)
{
try
{
ServerSocket server = new ServerSocket(10000);
Socket client;
client= server.accept();
InputStreamReader stream = new InputStreamReader(client.getInputStream());
BufferedReader reader = new BufferedReader(stream);
String filename = reader.readLine();
PrintWriter writer = new PrintWriter(client.getOutputStream());
FileInputStream fileStream = new FileInputStream(new File(filename));
int ch;
while((ch = fileStream.read()) != -1)
{
writer.write(ch);
writer.flush();
}
writer.close();
}
catch(Exception e)
{
e.printStackTrace();
}}}

Output:

15
Result:
Thus the java program to demonstrate a simple FTP operation has been
executed successfully.

2.1.3. SMTP-SIMPLE MAIL TRANSFER PROTOCOL

Aim:
To write a java socket program to implement a simple SMTP client.

Algorithm:
Step 1: Import all necessary packages
Step 2: Establish a connection with the server
Step 3: Read the acceptance from the server
Step 4: Say HELO to the server
Step 5: Read the greeting from the server
Step 6: Send sender address to server
Step 7: Read the verification of sender from server
Step 8: Send recipient address to server
Step 9: Read the verification of recipient from server
Step 10: Send DATA command to the server
Step 11: Read the start indication from server
Step 12: Send the message to the server
Step 13: Read the acceptance of message from server
Step 14: Close the connection

16
Program:
import java.io.*;
import java.net.Socket;
public class SMTPClient {
public static void main(String[] args) throws Exception {
String results = send("smpt.gmail.com",
25,
"sender@gmail.com",
"receiver@gmail.com",
"Test Email",
"<b>You got mail!</b>");
System.out.println(results);
}
public static String send(String host,int port,String from,String to,String subject,
String message) throws Exception
{
StringBuffer buffer = new StringBuffer();
try {
Socket smtpSocket = new Socket(host, port);
DataOutputStream output = new
DataOutputStream(smtpSocket.getOutputStream());
BufferedReader input =new BufferedReader(new InputStreamReader(
new
DataInputStream(smtpSocket.getInputStream())));
try {
read(input, buffer);
send(output, "HELLO localhost.localdomain\r\n", buffer);
read(input, buffer);
send(output, "MAIL FROM: " + from + "\r\n", buffer);
read(input, buffer);
send(output, "RCPT to: " + to + "\r\n", buffer);
read(input, buffer);
send(output, "DATA\r\n", buffer);
read(input, buffer);
send(output, "Subject: " + subject + "\r\n", buffer);
send(output, message, buffer);
send(output, "\r\n.\r\n", buffer);
read(input, buffer);
smtpSocket.close();
}
catch (IOException e) {
System.out.println("Cannot send email as an error occurred.");
}
}
catch (Exception e) {
17
System.out.println("Host unknown");
}
return buffer.toString();
}
private static void send(DataOutputStream output,String data,StringBuffer buffer)
throws IOException
{
output.writeBytes(data);
buffer.append(data);
}
private static void read(BufferedReader br, StringBuffer buffer) throws IOException
{
int c;
while ((c = br.read()) != -1)
{
buffer.append((char) c);
if (c == '\n')
{
break;
}}}}

Output:

HELLO localhost.localdomain
250 smtp.gmail.com at your service
MAIL FROM : sender@gmail.com
RCPT TO : receiver@gmail.com
Subject : Test Email
You got mail!

Result:
Thus the Java socket program to implement a simple SMTP client has been
executed successfully.

2.1.4. POP3- Post Office Protocol

Aim:
To write a java socket program to implement a POP3 Client.

Algorithm:
Step 1: Get the host name, mailbox user name and password
18
Step 2: Establish the connection with the server
Step 3: Get the number of messages
Step 4: Retrieve a message whose number is specified by the user
Step 5: Repeat steps 3 and 4 until the user enters Q to quit

Program:
import java.io.*;
import java.net.*;
import java.util.*;
public class Pop3ClientDemo
{
protected int port = 110;
protected String hostname = "localhost";
protected String username = "";
protected String password = "";
protected Socket socket;
protected BufferedReader br;
protected PrintWriter pw;
// Constructs a new instance of the POP3 client
public Pop3ClientDemo() throws Exception
{
try
{
// Get user input
getInput();
// Get mail messages
displayEmails();
}
catch(Exception e)
{
System.err.println ("Error occured - details follow");
e.printStackTrace();
System.out.println(e.getMessage());
}
}
// Returns TRUE if POP response indicates success, FALSE if failure
protected boolean responseIsOk() throws Exception
{
String line = br.readLine();
System.out.println("< "+line);
return line.toUpperCase().startsWith("+OK");
}
// Reads a line from the POP server, and displays it to screen
protected String readLine(boolean debug) throws Exception
{
19
String line = br.readLine();
// Append a < character to indicate this is a server protocol response
if (debug)
System.out.println("< "+line);
else
System.out.println(line);
return line;
}
// Writes a line to the POP server, and displays it to the screen
protected void writeMsg(String msg) throws Exception
{
pw.println(msg);
pw.flush();
System.out.println("> "+msg);
}
// Close all writers, streams and sockets
protected void closeConnection() throws Exception
{
pw.flush();
pw.close();
br.close();
socket.close();
}
// Send the QUIT command, and close connection
protected void sendQuit() throws Exception
{
System.out.println("Sending QUIT");
writeMsg("QUIT");
readLine(true);
System.out.println("Closing Connection");
closeConnection();
}
// Display emails in a message
protected void displayEmails() throws Exception
{
BufferedReader userinput = new BufferedReader( new InputStreamReader
(System.in) );
System.out.println("Displaying mailbox with protocol commands and responses
below");
System.out.println("--------------------------------------------------------------");
// Open a connection to POP3 server
System.out.println("Opening Socket");
socket = new Socket(this.hostname, this.port);
br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
pw = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
20
// If response from server is not okay
if(! responseIsOk())
{
socket.close();
throw new Exception("Invalid POP3 Server");
}
// Login by sending USER and PASS commands
System.out.println("Sending username");
writeMsg("USER "+this.username);
if(!responseIsOk())
{
sendQuit();
throw new Exception("Invalid username");
}
System.out.println("Sending password");
writeMsg("PASS "+this.password);
if(!responseIsOk())
{
sendQuit();
throw new Exception("Invalid password");
}
// Get mail count from server ....
System.out.println("Checking mail");
writeMsg("STAT");
// ... and parse for number of messages
String line = readLine(true);
StringTokenizer tokens = new StringTokenizer(line," ");
tokens.nextToken();
int messages = Integer.parseInt(tokens.nextToken());
int maxsize = Integer.parseInt(tokens.nextToken());
if (messages == 0)
{
System.out.println ("There are no messages.");
sendQuit();
return;
}
System.out.println ("There are " + messages + " messages.");
System.out.println("Press enter to continue.");
userinput.readLine();
for(int i = 1; i <= messages ; i++)
{
System.out.println("Retrieving message number "+i);
writeMsg("RETR "+i);
System.out.println("--------------------");
line = readLine(false);
21
while(line != null && !line.equals("."))
{
line = readLine(false);
}
System.out.println("--------------------");
System.out.println("Press enter to continue. To stop, type Q then enter");
String response = userinput.readLine();
if (response.toUpperCase().startsWith("Q"))
break;
}
sendQuit();
}
public static void main(String[] args) throws Exception
{
Pop3ClientDemo client = new Pop3ClientDemo();
}
// Read user input
protected void getInput() throws Exception
{
String data=null;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Please enter POP3 server hostname:");
data = br.readLine();
if(data == null || data.equals("")) hostname="localhost";
else
hostname=data;
System.out.print("Please enter mailbox username:");
data = br.readLine();
if(!(data == null || data.equals("")))
username=data;
System.out.print("Please enter mailbox password:");
data = br.readLine();
if(!(data == null || data.equals("")))
password=data;
}}

Output:
Please enter POP3 server hostname:localhost
Please enter mailbox username:sender@gmail.com
Please enter mailbox password:4210
Displaying mailbox with protocol commands and responses below
--------------------------------------------------------------
Opening Socket
Checking mail
There are 2 messages
22
Press enter to continue
Retrieving message number 2
-------------------------------------
sender@yahoo.com: hi
sender@yahoo.com: hello
-------------------------------------
Q

Result:
Thus the java socket program to implement a POP3 Client has been executed
successfully.

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

23
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.*;

public class Server


{
static DatagramSocket serverSocket = null;
static LinkedList portNoList = null;
static HashMap portNos = null;

static public void SendMessage(String msg,int portNo) throws IOException


{
byte sendbuffer[] = msg.getBytes();
serverSocket.send(new
DatagramPacket(sendbuffer,sendbuffer.length,InetAddress.getLocalHost(),portNo));
}

static public void sendToAll(String msg,int SpecialPortNo) throws IOException


{
byte sendbuffer[] = msg.getBytes();
Iterator itr = portNoList.iterator();
while(itr.hasNext())
{
String strPortNo = (String)itr.next();
int portNo = Integer.parseInt(strPortNo);
if(SpecialPortNo!=portNo)
serverSocket.send(new DatagramPacket
(sendbuffer,sendbuffer.length,InetAddress.getLocalHost(),portNo));
}
}

public static void main(String args[])


{
try
{
serverSocket = new DatagramSocket(1024);
portNoList = new LinkedList();
portNos = new HashMap();
System.out.println("The chat server started...");
while(true)
{
24
byte buffer[] = new byte[1024];
DatagramPacket pkt = new DatagramPacket(buffer,buffer.length);
serverSocket.receive(pkt);
String clientMsg = new String(pkt.getData(),0,pkt.getLength());
if(clientMsg.indexOf("$##$")!=-1)
{
StringTokenizer st = new StringTokenizer(clientMsg,"$##$");
String clientName = st.nextToken();
String strPortNo = st.nextToken();
int clientPortNumber = Integer.parseInt(strPortNo);
portNoList.add(strPortNo);
portNos.put(clientName,strPortNo);
SendMessage("---------Welcome"+clientName+"!!!-----",clientPortNumber);
sendToAll(clientName+"has joined the chat room!!!",clientPortNumber);
}
else if(clientMsg.indexOf("!$")!=-1)
{
StringTokenizer st = new StringTokenizer(clientMsg,"$!");
String clientName = st.nextToken();
String msg ="<"+clientName+">"+st.nextToken();
String portNo = (String)portNos.get(clientName);
if(msg.indexOf("/exit")!=-1)
{
SendMessage("/exit",Integer.parseInt(portNo));
portNoList.remove(portNo);
portNos.remove(clientName);
msg="----------"+clientName+"has left the chat room!!!"+"---------";
}
sendToAll(msg,Integer.parseInt(portNo));
}
}
}
catch(Exception ex)
{
System.out.println(ex.getMessage());
}
}
}

Client Program:
import java.io.*;
import java.net.*;

public class Client implements Runnable


{
25
public static void main(String args[])
{
try
{

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;
}
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();
26
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
finally
{
clientSocket.close();
}
}
static DatagramSocket clientSocket = null;
static int clientPort;

public void run()


{
byte ReceiveBuffer[] = new byte[1024];
while(true)
{
DatagramPacket pkt = new
DatagramPacket(ReceiveBuffer,ReceiveBuffer.length);
try
{
clientSocket.receive(pkt);
}
catch(IOException e)
{
e.printStackTrace();
}
String msg = new String(pkt.getData(),0,pkt.getLength());
if(msg.indexOf("/exit")!=-1)
break;
System.out.println(msg+"\n");
}
}
}

27
Output:

Result:

28
Thus the Java program for creating simple chat application with datagram sockets and
datagram packets has been executed successfully.

2.3.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
{
29
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(" ");
}
}
}

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>
<center>
<form name="form1" action="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>
30
<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>
</table>
<input type="submit" value="submit">
</form>
</center>
</body>
</html>

Output:

31
Result:
Thus the java program to invoke servlets from HTML form has been executed
successfully.

32
2.3.2. INVOKING SERVLETS FROM APPLETS

Aim:
To write a java program that invokes servlet from applet.

Procedure:
1. Create the java program with the following
a) Define the class MyApplet which extends the property of the class Applet
b) Set the URL of the servlet program by using the object of the class URL.
e) Define the object for AppletContext in order to display the output of the
servlet on new
browser window.
2. Create HTML file that contains the applet tag and pass the class name to that
applet code.
3. Create the simple servlet program that contains any response message
4. Open the applet window in order to invoke the servlet program.

Program:
//AppletServlet.java:
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class AppletServlet extends HttpServlet


{
public void service(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException
{
ObjectOutputStream output = null;
try
{
output = new ObjectOutputStream(response.getOutputStream());
String str =new String("Welcome to this servlet");
output.writeObject(str);
output.flush();
output.close();
System.out.println("Message:"+str);
}
catch(Exception e)
{
e.printStackTrace();
}
33
}
}

web.xml:

<web-app>
<servlet>
<servlet-name>AppletServlet</servlet-name>
<servlet-class> AppletServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name> AppletServlet</servlet-name>
<url-pattern>/AppletServlet</url-pattern>
</servlet-mapping>
</web-app>

MyApplet.java:

import java.io.*;
import java.awt.*;
import java.net.*;
import java.applet.*;
/*
<applet code="MyApplet" width=500 height=500>
</applet>
*/
public class MyApplet extends Applet{
URL url=null;
URLConnection MyConnection = null;
public void paint(Graphics g)
{
try
{
g.drawString("Applet Servlet Communication",50,50);
g.drawString("Invoking Servlet",50,90);
String str = new String("Welcome to this servlet");
g.drawString("Message Obtained from servlet:"+str,50,120);
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
34
Output:

35
Result:
Thus the java program that invokes servlet from applet has been executed
successfully.

2.4. 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
36
 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
{
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"))
37
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");

out.println("<h3>Yours results stored in our database</h3>"); out.print("<br><br>");


out.println("<b>"+"Participants and their Marks"+"</b>"); out.println("<table
border=5>");
try
{
Statement stmt=connect.createStatement(); String query="SELECT * FROM
student"; rs=stmt.executeQuery(query); out.println("<th>"+"Seat_no"+"</th>");
out.println("<th>"+"Name"+"</th>"); out.println("<th>"+"Marks"+"</th>");
while(rs.next())
{
out.println("<tr>");
out.print("<td>"+rs.getInt(1)+"</td>");
out.print("<td>"+rs.getString(2)+"</td>");
out.print("<td>"+rs.getString(3)+"</td>");
out.println("</tr>");
}
out.println("</table>");
}
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>");
38
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"
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>

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

40
2.5. LOCKING AND UNLOCKING SERVLET

Aim:
To write a Java Program for lock and Unlock servlet itself to a particular server
IP address and port number.

Procedure:
 check the piracy should not be done in init
 Check if the init parameter "key" unlocks this server
o if Key fits to server print valid
o else print Pirated
 match a key with server host and port
 check the key must be a 64-bit number equal to the logical not (~) of the 32-bit
IP address concatenated with the 32-bit port number.
 Get the 32-bit IP address
 Concatentate the 32-bit port number
 check the key match
o if key is matched display valid
o else print Pirated

Program:
//KeyedServerLock.java

import java.io.*;
import java.net.*;
import java.util.*;
import javax.servlet.*;

public class KeyedServerLock extends GenericServlet {

// This servlet has no class or instance variables


// associated with the locking, so as to simplify
// synchronization issues.

public void service(ServletRequest req, ServletResponse res)


throws ServletException, IOException {
res.setContentType("text/plain");
PrintWriter out = res.getWriter();

41
// The piracy check shouldn't be done in init
// because name/port are part of request.
String key = getInitParameter("key");
String host = req.getServerName();
int port = req.getServerPort();

// Check if the init parameter "key" unlocks this server.


if (! keyFitsServer(key, host, port)) {
// Explain, condemn, threaten, etc.
out.println("Pirated!");
}
else {
// Give 'em the goods
out.println("Valid");
// etc...
}
}

// This method contains the algorithm used to match a key with


// a server host and port. This example implementation is extremely
// weak and should not be used by commercial sites.
//
private boolean keyFitsServer(String key, String host, int port) {

if (key == null) return false;

long numericKey = 0;
try {
numericKey = Long.parseLong(key);
}
catch (NumberFormatException e) {
return false;
}

// The key must be a 64-bit number equal to the logical not (~)
// of the 32-bit IP address concatenated with the 32-bit port number.

byte hostIP[];
try {
hostIP = InetAddress.getByName(host).getAddress();
}
catch (UnknownHostException e) {
return false;
}
42
// Get the 32-bit IP address
long servercode = 0;
for (int i = 0; i < 4; i++) {
servercode <<= 8;
servercode |= hostIP[i];
}
// Concatentate the 32-bit port number
servercode <<= 32;
servercode |= port;

// Logical not
long accesscode = ~numericKey;

// The moment of truth: Does the key match?


return (servercode == accesscode);
}}

//KeyedServerUnlock.java

import java.io.*;
import java.net.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class KeyedServerUnlock extends HttpServlet {

public void doGet(HttpServletRequest req, HttpServletResponse res)


throws ServletException, IOException {
PrintWriter out = res.getWriter();

// Get the host and port


String host = req.getParameter("host");
String port = req.getParameter("port");

// Convert the port to an integer


int numericPort;
try {
numericPort = Integer.parseInt(port);
}
catch (NumberFormatException e) {
numericPort = 80; // default
43
}

// Generate and print the key


// Any KeyGenerationException is caught and displayed
try {
long key = generateKey(host, numericPort);
out.println(host + ":" + numericPort + " has the key " + key);
}
catch (KeyGenerationException e) {
out.println("Could not generate key: " + e.getMessage());
}
}

// This method contains the algorithm used to match a key with


// a server host and port. This example implementation is extremely
// weak and should not be used by commercial sites.
//
// Throws a KeyGenerationException because anything more specific
// would be tied to the chosen algorithm.
//
private long generateKey(String host, int port) throws KeyGenerationException {

// The key must be a 64-bit number equal to the logical not (~)
// of the 32-bit IP address concatenated by the 32-bit port number.

byte hostIP[];
try {
hostIP = InetAddress.getByName(host).getAddress();
}
catch (UnknownHostException e) {
throw new KeyGenerationException(e.getMessage());
}

// Get the 32-bit IP address


long servercode = 0;
for (int i = 0; i < 4; i++) {
servercode <<= 8;
servercode |= (hostIP[i] & 255);
}

// Concatentate the 32-bit port number


servercode <<= 32;
servercode |= port;

// The key is the logical not


44
return ~servercode;
}
}

class KeyGenerationException extends Exception {

public KeyGenerationException() {
super();
}

public KeyGenerationException(String msg) {


super(msg);
}
}

45
<servlet>
<init-param>
<param-name>key</param-name>
<param-value>-9151314447111823253</param-value>
</init-param>
<servlet-name>KeyedServerLock</servlet-name>
<servlet-class>KeyedServerLock</servlet-class>
</servlet>

<servlet>
46
<init-param>
<param-name>key</param-name>
<param-value>-9151314447111823256</param-value>
</init-param>
<servlet-name>KeyedServerLock</servlet-name>
<servlet-class>KeyedServerLock</servlet-class>
</servlet>

http://localhost:8084/KeyedServerUnlock/?host=localhost&port=8084

47
<servlet>
<init-param>
<param-name>key</param-name>
<param-value>-9151314447111823253</param-value>
</init-param>
<servlet-name>KeyedServerLock</servlet-name>
<servlet-class>KeyedServerLock</servlet-class>
</servlet>

48
Result:
Thus the Java Program for lock and Unlock servlet itself to a particular server
IP address and port number.

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

49
<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>");
out.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}

SERVLET2
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class Servlet2 extends HttpServlet


50
{
public void doGet(HttpServletRequest request,HttpServletResponse response)
{
try
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("uname");
out.println("Hello"+n);
String c=request.getParameter("usercity");
out.print("you are from"+c);
out.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}

Output

51
Result:
Thus the Java Program for Session Tracking Using Hidden Form Fields has
been executed successfully.

52
2.6.2 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>");

53
out.println("<head>");
out.println("</head>");
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:

54
Result:
Thus the Java program for Session tracking a hit count has been executed
successfully.

2.7 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>

55
<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:
<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(",");

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

57
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>");
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>

58
<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>
</session-config>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

Output:

59
60
Result:

Thus the conversion of the static web pages into dynamic web pages using servlets
cookies has been executed successfully.

61
3.1.1. STRUTS WEB FRAMEWORK
Aim:
To build a simple MVC application that displays a login page and returns a
success page upon submitting data that passes validation.

Procedure:
 Overview of the Application
 Setting Up a Struts Application
 Creating JSP Pages
 Creating a Login Page
 Creating a Success Page
 Creating an ActionForm Bean
 Creating an Action Class
 Implementing Validation
 Accessing Bean Data and Preparing a Forwarding Condition
 Setting Up an Error Message
 Adding forward Entries to struts-config.xml
 Configuring and Running the Application
 Setting the Welcome Page
 Attaching a Stylesheet
 Running the Application

Setting Up a Struts Application


1. Choose File > New Project (Ctrl-Shift-N) from the main menu. Select Java
Web in the list of Categories and then select Web Application in the list of
Projects. Click Next.
2. In the Name and Location panel, enter MyStrutsApp for Project Name and click
Next.
3. In the Server and Settings panel, select the server to which you want to deploy
your application. Only servers that are registered with the IDE are listed. (To
register a server, click Add next to the Server drop-down list.) Also, note that
the Context Path to your deployed application becomes /MyStrutsApp. Click
Next.

62
4. Select Struts in the Frameworks panel. 

For purposes of this execution, do not change any of the configuration values in
the lower region of this panel. The wizard displays the following configuration
options.
 Action Servlet Name: The name of the Struts action servlet used in the
application. The web.xml deployment descriptor contains an entry for the action
servlet and specifies the appropriate Struts-specific parameters, such as the path
to the servlet class within the Struts library and to the struts-
config.xmlconfiguration file within the application.
 Action URL Pattern: Specifies the patterns of incoming requests which
are mapped to the Struts action controller. This generates a mapping entry in the
deployment descriptor. By default, only the *.do pattern is mapped.
 Application Resource: Lets you specify the resource bundle which will
be used in the struts-config.xml file for localizing messages. By default, this
iscom.myapp.struts.ApplicationResource.
 Add Struts TLDs: Lets you generate tag library descriptors for the Struts
tag libraries. A tag library descriptor is an XML document which contains
additional information about the entire tag library as well as each individual tag.
In general this is not necessary, because you can refer to on-line URIs rather
than local TLD files.
. Click Finish. The IDE creates the project folder in your file system. As with any
web application in the IDE, the project folder contains all of your sources and
the IDE's project metadata, such as the Ant build script. However, your web
application in addition has all of the Struts libraries on its classpath. Not only
are they on the application's classpath, but they are included in the project and
will be packaged with it later when you build the project.
63
The project opens in the IDE. The Projects window is the main entry point to your
project sources. It shows a logical view of important project contents. For example, if
you expand several nodes within the new project, it may appear as follows:

Note: Use the Files window (Window > Files) to see all of your project contents in a
directory-based view.
The Struts-specific configuration files, as well as the application's deployment
descriptor, are conveniently placed within the Configuration Files folder. Open the
deployment descriptor (double-click the web.xml file node to have it display in the
Source Editor). In order to handle Struts processing, a mapping is provided for the
Struts controller servlet.
<servlet>
<servlet-name>action</servlet-name>

64
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<init-param>
<param-name>debug</param-name>
<param-value>2</param-value>
</init-param>
<init-param>
<param-name>detail</param-name>
<param-value>2</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>

Above, the Struts controller servlet is named action and is defined in the Struts


library (org.apache.struts.action.ActionServlet). It is set to handle all requests that
satisfy the *.do mapping. In addition, initialization parameters for the servlet are
specified by means of the struts-config.xml file, also contained in the WEB-
INFfolder.
Creating JSP Pages
Begin by creating two JSP pages for the application. The first displays a form. The
second is the view returned when login is successful.
 Creating a Login Page
 Creating a Success Page
Creating a Login Page
1. Right-click the MyStrutsApp project node, choose New > JSP, and name the
new file login. Click Finish. The login.jsp file opens in the Source Editor.
2. In the Source Editor, change the content of both the <title> and <h1> tags
(or <h2> tags, depending on the IDE version you are using) to Login Form.
3. Add the following two taglib directives to the top of the file:
<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html" %>
Many web applications use JSP pages for views in the MVC paradigm, so
Struts provides custom tag libraries which facilitate interaction with HTML
forms. These can be easily applied to a JSP file using the IDE's support for code
completion. When you type in the Source Editor, the IDE provides you with
code completion for Struts tags, as well as the Struts Javadoc. You can also
invoke code completion manually by pressing Ctrl-Space:

65
The bean taglib provides you with numerous tags that are helpful when
associating a form bean (i.e., an ActionForm bean) with the data collected from the
form. The html taglib offers an interface between the view and other components
necessary to a web application. For example, below you replace common
html form tags with Struts' <html:form> tags. One benefit this provides is that it
causes the server to locate or create a bean object that corresponds to the value
provided forhtml:form's action element.
4. Below the <h1> (or <h2>) tags, add the following:
<html:form action="/login">

<html:submit value="Login" />

</html:form>
Whenever you finish typing in the Source Editor, you can tidy up the code by
right-clicking and choosing Format (Alt-Shift-F).
5. In the Palette (Window > Palette) in the right region of the IDE, drag a Table
item from the HTML category to a point just above the <html:submit
value="Login" /> line. The Insert Table dialog box displays. Set the rows to 3,
66
columns to 2, and leave all other settings at 0. Later, you will attach a
stylesheet to affect the table display. 

 
Click OK, then optionally reformat the code (Alt-Shift-F). The form
in login.jsp now looks as follows:
<html:form action="/login">
<table border="0">
<thead>
<tr>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
</tbody>
</table>

<html:submit value="Login" />

67
</html:form>
Note: You can safely delete the <thead> table row.
6. In the first table row, enter the following (changes in bold):
<tr>
<td>Enter your name:</td>
<td><html:text property="name" /></td>
</tr>
7. In the second table row, enter the following (changes in bold):
<tr>
<td>Enter your email:</td>
<td><html:text property="email" /></td>
</tr>
The html:text element enables you to match the input fields from the form with
properties in the form bean that will be created in the next step. So for example,
the value of property must match a field declared in the form bean associated
with this form.
8. Move the <html:submit value="Login" /> element into the second column of
the third table row, so that the third table row appears as follows (changes
in bold):
<tr>
<td></td>
<td><html:submit value="Login" /></td>
</tr>
At this stage, your login form should look as follows:
<html:form action="/login">
<table border="0">
<tbody>
<tr>
<td>Enter your name:</td>
<td><html:text property="name" /></td>
</tr>
<tr>
<td>Enter your email:</td>
<td><html:text property="email" /></td>
</tr>
<tr>
<td></td>
<td><html:submit value="Login" /></td>
</tr>
</tbody>
</table>
</html:form>
Creating a Success Page

68
1. Right-click the MyStrutsApp project node, choose New > JSP, and name the
new file success. In the Folder field, click the adjacent Browse button and
selectWEB-INF from the dialog that displays. Click Select Folder to enter
WEB-INF in the Folder field. Any files contained in the WEB-INF folder are
not directly accessible to client requests. In order for success.jsp to be properly
displayed, it must contain processed data. Click Finish.
2. In the Source Editor, change the content of the newly created page to the
following:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Login Success</title>
</head>
<body>
<h1>Congratulations!</h1>

<p>You have successfully logged in.</p>

<p>Your name is: .</p>

<p>Your email address is: .</p>


</body>
3. Add a bean taglib directive to the top of the file:
<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>
4. Add the following <bean:write> tags (changes in bold):
<p>Your name is: <bean:write name="LoginForm"
property="name" />.</p>

<p>Your email address is: <bean:write name="LoginForm"


property="email" />.</p>
By employing the <bean:write> tags, you make use of the bean taglib to locate
the ActionForm bean you are about to create, and display the user data saved
for name and email.
Creating an ActionForm Bean
A Struts ActionForm bean is used to persist data between requests. For example, if a
user submits a form, the data is temporarily stored in the form bean so that it can
either be redisplayed in the form page (if the data is in an invalid format or if login
fails) or displayed in a login success page (if data passes validation).
1. Right-click the MyStrutsApp project node and choose New > Other. Under
Categories choose Struts, then under File Types choose Struts ActionForm
Bean. Click Next.
2. Type in LoginForm for the Class Name. Then select com.myapp.struts in the
Package drop-down list and click Finish.
The IDE creates the LoginForm bean and opens it in the Source Editor. By
default, the IDE provides it with a String called name and an int called number.
Both fields have accessor methods defined for them. Also, the IDE adds a bean
69
declaration to the struts-config.xml file. If you open the struts-config.xml file in
the Source Editor, you can see the following declaration, which was added by
the wizard:
<form-beans>
<form-bean name="LoginForm"
type="com.myapp.struts.LoginForm" />
</form-beans>
The IDE provides navigation support in the struts-config.xml file. Hold down
the Ctrl key and hover your mouse over the LoginForm bean's fully qualified
class name. The name becomes a link, enabling you to navigate directly to the
class in the Source Editor:

3. In the LoginForm bean in the Source Editor, create fields and accompanying


accessor methods that correspond to the name and email text input fields that
you created in login.jsp. Because name has already been created in
the LoginForm skeleton, you only need to implement email.
Add the following declaration beneath name (changes in bold):
private String name;
private String email;
To create accessor methods, place your cursor on email and press Alt-Insert.

Select Getter and Setter, then in the dialog that displays, select email :
String and click Generate. Accessor methods are generated for the email field.
Note: You can delete the declaration and accessor methods for number.

70
Creating an Action Class
The Action class contains the business logic in the application. When form data
is received, it is the execute method of an Action object that processes the data and
determines which view to forward the processed data to. Because the Action class is
integral to the Struts framework, NetBeans IDE provides you with a wizard.
1. In the Projects window, right-click the MyStrutsApp project node and choose
New > Other. From the Struts category choose Struts Action and click Next.
2. In the Name and Location panel, change the name to LoginAction.
3. Select com.myapp.struts in the Package drop-down list.
4. Type /login in Action Path. This value must match the value you set for
the action attribute of the <html:form> tags in login.jsp. Make sure settings
appear as in the screenshot below, then click Next. 

5. In the third step of the wizard, you are given the opportunity to associate
the Action class with a form bean. Notice that the LoginForm bean you
previously created is listed as an option for ActionForm Bean Name. Make the
following adjustments to the panel:
 Delete the forward slash for the Input Resource field
 Set Scope to Request (Session is the default scope setting in Struts.)
 Deselect the Validate ActionForm Bean option
Click Finish. The LoginAction class is generated, and the file opens in the Source
Editor. Also note that the following action entry is added to the struts-
config.xml file:
<action-mappings>
<action name="LoginForm" path="/login" scope="request"
type="com.myapp.struts.LoginAction" validate="false"/>

71
<action path="/Welcome" forward="/welcomeStruts.jsp"/>
</action-mappings>

The name and scope attributes apply to the form bean that is associated with the


action. Specifically, when an incoming request matches /login, the Struts framework
automatically instantiates a LoginForm object and populates it with the form data sent
in the request. The default value of validate is set to true. This tells the framework to
call the validate method of the form bean. You deselected this option in the wizard
however because you will hand-code simple validation in the next step, which does
not require the validate method.
Implementing Validation
In the Source Editor, browse through the LoginAction class and look at
the execute method:
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {

return mapping.findForward(SUCCESS);
}

Notice the definition of SUCCESS, listed beneath the LoginAction class


declaration:
private final static String SUCCESS = "success";

Currently, the mapping.findForward method is set to unconditionally forward


any request to an output view called success. This is not really desirable; you want to
first perform some sort of validation on the incoming data to determine whether to
send the success view, or any different view.
 Accessing Bean Data and Preparing a Forwarding Condition
 Setting Up an Error Message
Accessing Bean Data and Preparing a Forwarding Condition
1. Type in the following code within the body of the execute method:
// extract user data
LoginForm formBean = (LoginForm)form;
String name = formBean.getName();
String email = formBean.getEmail();
In order to use the incoming form data, you need to
take execute's ActionForm argument and cast it as LoginForm, then apply the
getter methods that you created earlier.
2. Type in the following conditional clause to perform validation on the incoming
data:
// perform validation
if ((name == null) || // name parameter does not exist
email == null || // email parameter does not exist
name.equals("") || // name parameter is empty
72
email.indexOf("@") == -1) { // email lacks '@'

return mapping.findForward(FAILURE);
}
At this stage, the execute method should look as follows:
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {

// extract user data


LoginForm formBean = (LoginForm) form;
String name = formBean.getName();
String email = formBean.getEmail();

// perform validation
if ((name == null) || // name parameter does not exist
email == null || // email parameter does not exist
name.equals("") || // name parameter is empty
email.indexOf("@") == -1) { // email lacks '@'

return mapping.findForward(FAILURE);
}

return mapping.findForward(SUCCESS);
}
3. Add a declaration for FAILURE to the LoginAction class (changes in bold):
private final static String SUCCESS = "success";
private final static String FAILURE = "failure";

Using the above logic, the execute method forwards the request to


the success view if the user provides an entry for both name and email fields, and the
email entered contains an '@' sign. Otherwise, the failure view is forwarded. As will
be demonstrated below in Adding forward Entries to struts-config.xml, you can set
thefailure view to point back to the form page, so that the user has another chance to
enter data in the correct format.

Setting Up an Error Message

If the login form is returned, it would be good to inform the user that validation
failed. You can accomplish this by adding an error field in the form bean, and an
appropriate<bean:write> tag to the form in login.jsp. Finally, in the Action object, set
the error message to be displayed in the event that the failure view is chosen.
1. Open LoginForm and add an error field to the class:
// error message
private String error;
73
2. Add a getter method and a setter method for error, as demonstrated above.
3. Modify the setter method so that it appears as follows:
public void setError() {
this.error =
"<span style='color:red'>Please provide valid entries for both
fields</span>";
}
4. Open login.jsp and make the following changes:
<html:form action="/login">
<table border="0">
<tbody>
<tr>
<td colspan="2">
<bean:write name="LoginForm" property="error"
filter="false"/>
&nbsp;</td>
</tr>
<tr>
<td>Enter your name:</td>
<td><html:text property="name" /></td>
</tr>
5. In LoginAction, within the if conditional clause, add a statement to set the error
message before forwarding the failure condition (changes in bold):
if ((name == null) || // name parameter does not exist
email == null || // email parameter does not exist
name.equals("") || // name parameter is empty
email.indexOf("@") == -1) { // email lacks '@'

formBean.setError();
return mapping.findForward(FAILURE);
}
Your completed LoginAction class should now appear as follows:

public class LoginAction extends org.apache.struts.action.Action {

private final static String SUCCESS = "success";


private final static String FAILURE = "failure";

public ActionForward execute(ActionMapping mapping, ActionForm form,


HttpServletRequest request, HttpServletResponse response)
throws Exception {

// extract user data


LoginForm formBean = (LoginForm)form;
String name = formBean.getName();
74
String email = formBean.getEmail();

// perform validation
if ((name == null) || // name parameter does not exist
email == null || // email parameter does not exist
name.equals("") || // name parameter is empty
email.indexOf("@") == -1) { // email lacks '@'

formBean.setError();
return mapping.findForward(FAILURE);
}

return mapping.findForward(SUCCESS);

}
}
Adding forward Entries to struts-config.xml
In order for the application to match JSP pages with forwarding conditions
returned by LoginAction's execute method, you need to add forward entries to
the struts-config.xml file.

1. Open struts-config.xml in the Source Editor, right-click anywhere in


the action entry for LoginForm, and choose Struts > Add Forward. 

2. In the Add Forward dialog box, type success in Forward Name. Enter the path
to success.jsp in the Resource File field (i.e., /WEB-INF/success.jsp). The
dialog box should now look as follows: 

75
 
Click Add. Note that the following forward entry was added to struts-
config.xml (changes in bold):
<action name="LoginForm" path="/login" scope="request"
type="com.myapp.struts.LoginAction" validate="false">
<forward name="success" path="/WEB-INF/success.jsp"/>
</action>
3. Perform the same action to add a forward entry for failure. Set the Resource
File path to /login.jsp. The following forward entry is added to struts-
config.xml (changes in bold):
<forward name="success" path="/WEB-INF/success.jsp"/>
<forward name="failure" path="/login.jsp"/>
Configuring and Running the Application
The IDE uses an Ant build script to build and run your web application. The
IDE generated the build script when you created the project, basing it on the options
you entered in the New Project wizard. Before you build and run the application, you
need to set the application's default entry point to login.jsp. Optionally, you can also
add a simple stylesheet to the project.
 Setting the Welcome Page
 Attaching a Stylesheet
 Running the Application
Setting the Welcome Page
1. In the Projects window, double-click the web.xml deployment descriptor. The
tabs listed along the top of the Source Editor provide you with an interface to
the web.xmlfile. Click on the Pages tab. In the Welcome Files field,
enter login.jsp. 

76
 
Now click on the Source tab to view the file. Note that login.jsp is now listed in
the welcome-file entry:
2. <welcome-file>login.jsp</welcome-file>
Attaching a Stylesheet
1. Add a simple stylesheet to the project. One easy way to do this is by saving this
sample stylesheet to your computer. Copy the file (Ctrl-C), then in the IDE,
select the Web Pages node in the Projects window and press Ctrl-V). The file is
added to your project.
2. Link the stylesheet to your JSP pages by adding a reference between
the <head> tags of both login.jsp and success.jsp:
3. <link rel="stylesheet" type="text/css" href="stylesheet.css">

Running the Application


1. In the Projects window, right-click the project node and choose Run. The IDE
builds the web application and deploys it, using the server you specified when
creating the project. The browser opens and displays the login.jsp page. Type in
some data that should fail validation, i.e., either leave either field blank, or enter
an email address with a missing '@' sign: 

When you click Login, the login form page redisplays, containing an error
77
message: 

2. Try entering data that should pass validation. Upon clicking Login, you are
presented with the success page: 

Result:
Thus the simple MVC application that displays a login page and returns a
success page upon submitting data that passes validation executed successfully.

78
3.1.2. Web Application Using Hibernate

Aim:
To Implement a simple program using Hibernate.

Procedure:
 Creating the Database
 Creating the Web Application Project
 Modifying the Hibernate Configuration File
 Creating the HibernateUtil.java Helper File
 Generating Hibernate Mapping Files and Java Classes
 Creating the FilmHelper.java Helper Class
 Creating the JSF Managed Bean
 Creating the Web Pages
 Running the Project

Program:

79
80
81
82
83
84
85
Result:
Thus the implementation of Web Application Using Hibernate executed
successfully.

86
3.1.3. Web Application Using Spring

Aim:

To Implement a simple program using Spring.

Procedure:
 Overview of the Application
 Setting up a New Project with Spring Web MVC Support
 Creating a Spring Web MVC Skeleton Project
 Running the Skeleton Project
 Implementing a Service
 Implementing the Controller and Model
 Implementing the Views

Setting up a New Project with Spring Web MVC Support


 Creating a Spring Web MVC Skeleton Project
 Running the Skeleton Project
Creating a Spring Web MVC Skeleton Project
Start by creating a new project for a web application using the Spring Framework.

87
1. Choose New Project (Ctrl-Shift-N; ⌘-Shift-N on Mac) from the IDE's File
menu. Select the Java Web category, then under Projects select Web
Application. Click Next.
2. In Project Name, type in HelloSpring. Click Next.
3. In Step 3: Server and Settings, deselect the Enable Contexts and Dependency
Injection option, as you are not working with the JSR-299 specification in this
tutorial.
4. Confirm that the GlassFish server is selected in the Server drop-down list. Click
Next.
The Java EE version depends upon the version of the server that is selected. The
default Java EE version is Java EE 7 Web when the selected server is GlassFish
Server 4.0.
5. In Step 4, the Frameworks panel, select Spring Web MVC.
6. Select Spring Framework 3.x in the Spring Library drop-down list. 

88
7. Click the Configuration tab and note that the wizard enables you to specify the
name and mapping of the Spring Dispatcher servlet. 

8. Click Finish.
9. In the Projects window, expand the new project's Libraries node and note that
the Spring JARs are included in the project's classpath. 

Running the Skeleton Project


89
Before making any changes to project files, try running the new project in the IDE:
1. Click the Run Project (   ) in the IDE's main toolbar. The IDE automatically
starts the GlassFish server if it is not already running, compiles the project, then
deploys it to the server. Note any output displayed in the IDE's Output window
(Ctrl-4; ⌘-4 on Mac). The generated output completes with a BUILD
SUCCESSFUL message. 

The IDE's default browser starts up, and you see content from the welcome
page view (/WEB-INF/jsp/index.jsp). 
2.

When you run your project in the IDE, the project is compiled and deployed to
the server, and then opens in your default browser. Furthermore, the IDE provides a
Deploy on Save feature, which is activated by default for web projects. When you
save files in the editor, your project is automatically recompiled and deployed to the
server. To view changes, you can simply refresh pages in your browser.

90
In order to understand what just took place, start by examining the project's
deployment descriptor (web.xml). To open this file in the Source Editor, right-click
the WEB-INF> web.xml node in the Projects window and choose Edit. The default
entry point for the application is redirect.jsp:
<welcome-file-list>
<welcome-file>redirect.jsp</welcome-file>
</welcome-file-list>
Within redirect.jsp, there is a redirect statement that points all requests to index.htm:
<% response.sendRedirect("index.htm"); %>
In the deployment descriptor, note that all requests for URL patterns that
match *.htm are mapped to Spring's DispatcherServlet.
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>

The fully qualified name of the dispatcher servlet, as shown above,


is org.springframework.web.servlet.DispatcherServlet. This class is contained in the
Spring library, which was added to the project classpath when the project was created.
You can verify this in the Projects window by drilling down from the Libraries node.

Locate the spring-webmvc-3.1.1.RELEASE.jar, then expand it to


find org.springframework.web.servlet >DispatcherServlet.

The DispatcherServlet handles incoming requests based on configuration


settings found in dispatcher-servlet.xml. Open dispatcher-servlet.xmlby clicking on its
tab in the editor. Note the following code.
<bean id="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/index.htm">indexController</prop>
</props>
</property>
</bean>

<bean id="viewResolver"
91
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/"
p:suffix=".jsp" />

<bean name="indexController"
class="org.springframework.web.servlet.mvc.ParameterizableViewController"
p:viewName="index" />
Three beans are defined in this file: indexController, viewResolver,
and urlMapping. When the DispatcherServlet receives a request that
matches*.htm such as index.htm, it looks for a controller within urlMapping that can
accommodate the request. Above, you see that there is a mappings property that
links/index.htm to indexController.
The runtime environment then searches for the definition of a bean
named indexController, which is conveniently provided by the skeleton project. Note
thatindexController extends ParameterizableViewController. This is another class
provided by Spring, which simply returns a view. Above, note
thatp:viewName="index" specifies the logical view name, which is resolved using
the viewResolver by prepending /WEB-INF/jsp/ and appending .jsp to it. This allows
the runtime to locate the file within the application directory, and respond with the
welcome page view (/WEB-INF/jsp/index.jsp).
Implementing a Service
Now that you are sure your environment is set up properly, you can begin
extending the skeleton project according to your needs. Start by creating
the HelloService class.
1. Click the New File (   ) button in the IDE's toolbar. (Alternatively, press Ctrl-
N; ⌘-N on Mac.)
2. Select the Java category, then select Java Class and click Next.
3. In the New Java Class wizard that displays, type in HelloService for Class
Name, and enter service for Package Name to create a new package for the
class.
4. Click Finish. The IDE creates the new class and opens it in the editor.
The HelloService class performs a very simple service. It takes a name as a
parameter, and prepares and returns a String that includes the name. In the editor,
create the following sayHello() method for the class (changes in bold).
public class HelloService {

public static String sayHello(String name) {


return "Hello " + name + "!";
}
}
Implementing the Controller and Model

92
You can use a SimpleFormController to handle user data and determine which view to
return.
Note: SimpleFormController is deprecated in Spring 3.x. It is used in this tutorial for
demonstration purposes. However, annotated controllers should be used instead of
XML files.
1. Open the New File wizard by pressing Ctrl-N (⌘-N on Mac). Under Categories
select Spring Framework; under File Types select Simple Form Controller. 

 
NetBeans IDE provides templates for various Spring artifacts, including the
Spring XML Configuration File, the AbstractController, and
theSimpleFormController.
2. Click Next.
3. Name the class HelloController and create a new package for it by
typing controller in the Package text field. Click Finish. The IDE creates the
new class and opens it in the editor.
4. Specify controller properties by uncommenting the setter methods that display
by default in the class template. To uncomment the code snippet, highlight the
code as in the image below, then press Ctrl-/ (⌘-/ on Mac). 

93
 
Pressing Ctrl-/ (⌘-/ on Mac) toggles comments in the editor.
5. Make changes as follows (shown in bold).
public HelloController() {
setCommandClass(Name.class);
setCommandName("name");
setSuccessView("helloView");
setFormView("nameView");
}

You now need to create the Name class as a simple bean to hold information for
each request.
6. In the Projects window, right-click on the project node and choose New > Java
Class. The New Java Class wizard displays.
7. Enter Name for the Class Name, and for Package select controller from the
drop-down list.
8. Click Finish. The Name class is created and opens in the editor.
9. For the Name class, create a field named value, then create accessor methods
(i.e., getter and setter methods) for this field. Start by declaring the value field:
public class Name {

private String value;

The IDE can create accessor methods for you. In the editor, right-click
on value and choose Insert Code (or press Alt-Insert; Ctrl-I on Mac). In the popup
menu, choose Getter and Setter. 

94
10.In the dialog that displays, select the value : String option, then click OK.
The getValue() and setValue() methods are added to the Name class:
public String getValue() {
return value;
}

public void setValue(String value) {


this.value = value;
}
11.Press Ctrl-Tab and choose HelloController to switch back to
the HelloController class. Note that the previous error badge has disappeared
since the Nameclass now exists.
12. Delete the doSubmitAction() method and uncomment the onSubmit() method.
The onSubmit() method enables you to create your own ModelAndView, which
is what is required here. Make the following changes:
@Override
protected ModelAndView onSubmit(
HttpServletRequest request,
HttpServletResponse response,
Object command,
BindException errors) throws Exception {

Name name = (Name) command;


ModelAndView mv = new ModelAndView(getSuccessView());
mv.addObject("helloMessage", helloService.sayHello(name.getValue()));
return mv;
}

95
13.Fix import errors by right-clicking in the editor and choosing Fix Imports (Ctrl-
Shift-I; ⌘-Shift-I on Mac). 

Note. Confirm
that org.springframework.validation.BindException and org.springframew
ork.web.servlet.ModelAndView are selected in the Fix All Imports dialog
box.
14.Click OK. The following import statement is added to the top of the file:
import org.springframework.web.servlet.ModelAndView;
Within HelloController, declare a private field named HelloService:
private HelloService helloService;
Then create a public setter method for the field:
public void setHelloService(HelloService helloService) {
this.helloService = helloService;
}
Finally, right-click in the editor and choose Fix Imports (Ctrl-Shift-I; ⌘-Shift-I
on Mac). The following statement is added to the top of the file:
import service.HelloService;
All errors should now be fixed.
15.Register HelloService in applicationContext.xml.
Open applicationContext.xml in the editor and enter the following bean
declaration:
<bean name="helloService" class="service.HelloService" />
Spring support in the IDE includes code completion within XML configuration
files for Java classes as well as bean references. To invoke code completion,

96
press Ctrl-Space when working in the editor: 

16.Register HelloController in dispatcher-servlet.xml. Open dispatcher-
servlet.xml in the editor and enter the following bean declaration:
<bean class="controller.HelloController" p:helloService-ref="helloService"/>
Implementing the Views
To implement the view for this project, you need to create two JSP pages. The
first, which you will call nameView.jsp, serves as the welcome page and allows users
to input a name. The other page, helloView.jsp, displays a greeting message that
includes the input name. Begin by creating helloView.jsp.
1. In the Projects window, right-click the WEB-INF > jsp node and choose New >
JSP. The New JSP File wizard opens. Name the file helloView.
2. Click Finish. The new JSP page is created in the jsp folder and opens in the
editor.
3. In the editor, change the file's title to Hello, and change the output message to
retrieve the helloMessage of the ModelandView object that is created
inHelloController.
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Hello</title>
</head>
<body>
<h1>${helloMessage}</h1>
</body>
Create another JSP page in the same manner as above, but name it nameView.
4. In the editor, add the following Spring tag library declaration to nameView.jsp.
<%@taglib uri="http://www.springframework.org/tags" prefix="spring" %>
This imports the Spring tag library, which contains tags useful when
implementing views as JSP pages.
5. Change the contents of the <title> and <h1> tags to read: Enter Your Name.
97
6. Enter the following code beneath the <h1> tags:
<spring:nestedPath path="name">
<form action="" method="post">
Name:
<spring:bind path="value">
<input type="text" name="${status.expression}" value="${status.value}">
</spring:bind>
<input type="submit" value="OK">
</form>
</spring:nestedPath>
spring:bind allows you to bind a bean property. The bind tag provides a
bind status and value, which you use as the name and value of the input field.
This way, when the form is submitted, Spring will know how to extract the
submitted value. Here, our command class (controller.Name) has
a value property, therefore you set thepath to value. 

spring:nestedPath enables you to prepend a specified path to a bean. So,


when used with spring:bind as shown above, the path to the bean
becomes:name.value. As you recall, the command name
of HelloController is name. Therefore, this path refers to the value property of a
bean named name in the page scope.
7. Change the relative entry point for the application. Currently, the project entry
point is still index.htm which, as described in Running the Skeleton
Project above, redirects to WEB-INF/jsp/index.jsp. You can specify an entry
point for the project when it is deployed and run. In the Projects window, right-
click the project node and choose Properties. The Project Properties dialog
displays. Under Categories select Run. In the Relative URL field, type
in /hello.htm, then click OK. 

At this moment you may wonder where the mapping


of hello.htm to HelloController is located. You have not added a mapping to
the urlMapping bean, as is the case for index.htm, the skeleton project's
welcome page. This is possible with a bit of Spring magic provided by the
following bean definition in dispatcher-servlet.xml:
<bean
class="org.springframework.web.servlet.mvc.support.ControllerClassNameHan
dlerMapping"/>
This bean is responsible for automatically creating an URL mapping for
all controllers registered in the file. It takes the fully-qualified class name of the
controller (in our case, controller.HelloController) and strips the package name
and Controller suffix, then uses the result as a URL mapping. Therefore,
forHelloController it creates a hello.htm mapping. This magic however does not
work for controllers that are included in the Spring Framework, such
asParameterizableViewController. They require an explicit mapping.
98
In the Projects window right-click the project node and choose Run. This compiles, deploys
and runs the project. Your default browser opens, displaying hello.htm as the
project's nameView: 

Output: 

Result:

Thus a simple web MVC application using the Spring Framework has been


executed successfully.

99
3.2.1 SEARCHING IN REAL TIME WITH LIVE SEARCHES AND GETTING
THE ANSWER WITH AUTO COMPLETE

Aim:
To write AJAX program for Searching in Real Time with Live Searches and
getting the answer with auto complete.

Procedure:
 Enter a term to search for.
 Ajax contacts Google behind the scenes, looks up words that might match in a
dictionary on the server and displays them.
 See a drop-down menu that displays common search terms from Google that
might match what you’re typing.
 To select one of those terms, just click it in the menu. That’s all there is to it.
 Ajax application that connects to Google in this way behind the scenes.

Program:
Index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>jQuery Ajax Live Search - DEMO</title>
<!-- Bootstrap core CSS -->
<link rel="stylesheet"
href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<!-- Custom styles for this template -->
<link href="starter-template.css" rel="stylesheet">
<!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries
-->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
100
<body>
<div class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-
target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Brand</a>
</div>
<div class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li class="active"><a href="#">Link 1</a></li>
<li><a href="#">Link 2</a></li>
</ul>
</div><!--/.nav-collapse -->
</div>
</div>
<div class="container">
<div class="starter-template">
<div class="page-header">
<h1>jQuery Ajax Live Search <small>DEMO</small></h1>
</div>
<form role="form" method="post">
<div class="form-group">
<input type="text" class="form-control" id="keyword"
placeholder="Enter keyword">
</div>
</form>
<ul id="content"></ul>

</div>
</div><!-- /.container -->
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->

<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script
src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<script type="text/javascript">
101
$(document).ready(function() {
$('#keyword').on('input', function() {
var searchKeyword = $(this).val();
if (searchKeyword.length >= 3) {
$.post('search.php', { keywords: searchKeyword },
function(data) {
$('ul#content').empty()
$.each(data, function() {
$('ul#content').append('<li><a
href="example.php?id=' + this.id + '">' + this.title + '</a></li>');
});
}, "json");
}
});
});
</script>
</body>
</html>

Search.php
<?php
define('DB_USER', 'ENTER_USER');
define('DB_PASSWORD', 'ENTER_PASSWORD');
define('DB_SERVER', 'localhost');
define('DB_NAME', 'ENTER_DBNAME');

if (!$db = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME)) {


die($db->connect_errno.' - '.$db->connect_error);
}

$arr = array();

if (!empty($_POST['keywords'])) {
$keywords = $db->real_escape_string($_POST['keywords']);
$sql = "SELECT ID, post_title FROM wp_posts WHERE post_content LIKE
'%".$keywords."%' AND post_status = 'publish'";
$result = $db->query($sql) or die($mysqli->error);
if ($result->num_rows > 0) {
while ($obj = $result->fetch_object()) {
$arr[] = array('id' => $obj->ID, 'title' => $obj->post_title);
}
}
}

102
echo json_encode($arr);

starter-template.css
body { padding-top: 10px; }

.starter-template { max-width:640px;margin:0 auto;padding: 25px 15px; }

Output:

Result:
Thus the AJAX program for Searching in Real Time with Live Searches and
getting the answer with auto complete has been executed successfully.

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:

103
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);
}
}
}
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);
104
}
}

Output:

Result:
Thus the Ajax Program for Getting instant login feedback has been executed
successfully.

105
3.2.3 AJAX PROGRAM FOR MODIFYING WEB PAGES ON THE FLY

Aim:
To write Ajax Program for Modifying Web Pages On the Fly

Procedure:
 Updating Web pages on the fly without page refreshes
Program:
<html>
<head>
<title>
JavaScript Event Example
</title>
</head>
<body onmousedown=”document.bgcolor=’pink’”>
<h1>
Click this page to turn it pink!
</h1>
</body>
</html>

Output:

Result:
Thus the Ajax Program for Modifying Web Pages On the Fly has been executed
successfully.

106
3.3 WRITE A WEB SERVICES FOR FINDING WHAT PEOPLE THINK BY
ASKING 500 PEOPLE’S OPINION FOR ANY CONSUMER PRODUCT

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

Procedure:
 Open the home page.
 Enter the login ID and type the comments then submit.
 Retrieve comments with post id
 Display the comments.

Program:
Index.php
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>jQuery Ajax Comment System - Demo</title>
<link rel="stylesheet" href="css/style.css">
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="js/script.js"></script>
</head>
<body>
<div class="wrap">
<h1> Maggy Noodles Comment System</h1>
<?php
// retrive post
include('config.php');
include ('function.php');
dbConnect();

107
$query = mysql_query(
'SELECT *
FROM post
WHERE post_id = 1');
$row = mysql_fetch_array($query);
?>
<div class="post">
<h2><?php echo $row['post_title']?></h2>
<p><?php echo $row['post_body']?></p>
</div>

<?php
// retrive comments with post id
$comment_query = mysql_query(
"SELECT *
FROM comment
WHERE post_id = {$row['post_id']}
ORDER BY comment_id DESC
LIMIT 15");
?>

<h2>Comments.....</h2>
<div class="comment-block">
<?php while($comment = mysql_fetch_array($comment_query)): ?>
<div class="comment-item">
<div class="comment-avatar">
<img src="<?php echo avatar($comment['mail']) ?>"
alt="avatar">
</div>
<div class="comment-post">
<h3><?php echo $comment['name'] ?>
<span>said....</span></h3>
<p><?php echo $comment['comment']?></p>
</div>
</div>
<?php endwhile?>
</div>

108
<h2>Submit new comment</h2>
<!--comment form -->
<form id="form" method="post">
<!-- need to supply post id with hidden fild -->
<input type="hidden" name="postid" value="<?php echo
$row['post_id']?>">
<label>
<span>Name *</span>
<input type="text" name="name" id="comment-name"
placeholder="Your name here...." required>
</label>
<label>
<span>Email *</span>
<input type="email" name="mail" id="comment-mail"
placeholder="Your mail here...." required>
</label>
<label>
<span>Your comment *</span>
<textarea name="comment" id="comment" cols="30"
rows="10" placeholder="Type your comment here...." required></textarea>
</label>
<input type="submit" id="submit" value="Submit Comment">
</form>
</div>
</body>
</html>

Ajax_Comment.php
<?php
if (isset( $_SERVER['HTTP_X_REQUESTED_WITH'] )):
include('config.php');
include('function.php');
dbConnect();

if (!empty($_POST['name']) AND !empty($_POST['mail']) AND !


empty($_POST['comment']) AND !empty($_POST['postid'])) {
$name = mysql_real_escape_string($_POST['name']);
$mail = mysql_real_escape_string($_POST['mail']);
$comment = mysql_real_escape_string($_POST['comment']);

109
$postId = mysql_real_escape_string($_POST['postid']);

mysql_query("
INSERT INTO comment
(name, mail, comment, post_id)
VALUES('{$name}', '{$mail}', '{$comment}', '{$postId}')");

}
?>

<div class="comment-item">
<div class="comment-avatar">
<img src="<?php echo avatar($mail) ?>" alt="avatar">
</div>
<div class="comment-post">
<h3><?php echo $name ?> <span>said....</span></h3>
<p><?php echo $comment?></p>
</div>
</div>

<?php
dbConnect(0);
endif?>

Config.php
<?php
# db configuration
define('DB_HOST', 'localhost');
define('DB_USER', 'root');
define('DB_PASS', 'root');
define('DB_NAME', 'dbname');
?>

Function.php
<?php
/**
* Connect to mysql server
* @param bool
* @use true to connect false to close

110
*/
function dbConnect($close=true){

if (!$close) {
mysql_close($link);
return true;
}

$link = mysql_connect(DB_HOST, DB_USER, DB_PASS) or die('Could not


connect to MySQL DB ') . mysql_error();
if (!mysql_select_db(DB_NAME, $link))
return false;
}

/**
* gravatar Image
* @see http://en.gravatar.com/site/implement/images/
*/
function avatar($mail, $size = 60){
$url = "http://www.gravatar.com/avatar/";
$url .= md5( strtolower( trim( $mail ) ) );
// $url .= "?d=" . urlencode( $default );
$url .= "&s=" . $size;
return $url;
}
?>

Style.CSS
/* general styling */
*{
margin: 0;
padding: 0;
box-sizing: border-box;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
-webkit-font-smoothing: antialiased;
-moz-font-smoothing: antialiased;
-o-font-smoothing: antialiased;
font-smoothing: antialiased;
111
text-rendering: optimizeLegibility;
}
body{
font: 12px Arial,Tahoma,Helvetica,FreeSans,sans-serif;
text-transform: inherit;
color: #333;
background: #e7edee;
width: 100%;
text-shadow: 0 1px 1px rgba(0, 0, 0, 0.2)
}
.wrap{
width: 720px;
margin: 15px auto;
padding: 15px 20px;
background: white;
border: 2px solid #DBDBDB;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
overflow: hidden;
}

a{ text-decoration: none; color: #333}


h1{
font-family: Georgia, "Times New Roman", Times, serif;
font-size: 2.8em;
text-align: center;
margin: 25px 0;
}
h2{font-size: 1.5em; margin: 8px 0}
h3{
font-size: 1.2em;
margin: 5px 0;
}
h3 span{
font-weight: normal;
font-size: 1em;
}
.item{
112
clear: both;
margin:0;
padding: 10px;
overflow: hidden;
border-top: 1px solid #DBDBDB;
}
.item:last-child{border-bottom:1px solid #DBDBDB}
.item:hover{background: #f9f9f9}
.post{
padding: 10px 0;
border-bottom: 1px solid #E6E6E6;
}
.comment-block{
margin: 20px 0 20px 20px;
}
.comment-item{
overflow: hidden;
width: 500px;
clear: both;
padding: 10px;
border: 1px solid #E6E6E6;
border-radius: 5px;
margin: 5px;
}
.comment-avatar{
width: 60px;
float: left;
}
.comment-avatar img{
width: 60px;
height: 60px;
border-radius: 5px;
}
.comment-post{
width: 400px;
float: left;
padding: 0 5px 0 10px;
}
#form{
113
clear: both;
margin: 10px;
width: 500px;
}

/* form styling */
input[type="text"],
input[type="email"],
input[type="tel"],
input[type="url"],
textarea {
width:100%;
background: #fff;
border: 1px solid #ddd;
font-size: 13px;
line-height: 20px;
margin: 0;
padding: 7px 10px;
box-shadow: inset 0 1px 2px #eee;
border:1px solid #CCC;
margin:0 0 5px;
border-radius:5px;
}

textarea {
height:100px;
max-width:100%;
}
input[type="submit"] {
cursor:pointer;
width:100%;
border:none;
background:#991D57;
background-image:linear-gradient(bottom, #8C1C50 0%, #991D57 52%);
background-image:-moz-linear-gradient(bottom, #8C1C50 0%, #991D57 52%);
background-image:-webkit-linear-gradient(bottom, #8C1C50 0%, #991D57
52%);
color:#FFF;
margin:0 0 5px;
114
padding:10px;
border-radius:5px;
}
input[type="submit"]:hover {
background-image:linear-gradient(bottom, #9C215A 0%, #A82767 52%);
background-image:-moz-linear-gradient(bottom, #9C215A 0%, #A82767 52%);
background-image:-webkit-linear-gradient(bottom, #9C215A 0%, #A82767
52%);
-webkit-transition:background 0.3s ease-in-out;
-moz-transition:background 0.3s ease-in-out;
transition:background-color 0.3s ease-in-out;
}
input[type="submit"]:active {
box-shadow:inset 0 1px 3px rgba(0,0,0,0.5);
}
input:focus,
textarea:focus {
outline:0;
border:1px solid #999;
}
label{
display: block;
margin: 5px 0;
font-weight: 900;
cursor: pointer;
}

.alert{
display: none;
padding: 8px 35px 8px 14px;
margin: 20px 0;
text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5);
color: #468847;
background-color: #dff0d8;
border-color: #d6e9c6;
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
border-radius: 4px;
}
115
Script.js
$(document).ready(function(){
var form = $('form');
var submit = $('#submit');

form.on('submit', function(e) {
// prevent default action
e.preventDefault();
// send ajax request
$.ajax({
url: 'ajax_comment.php',
type: 'POST',
cache: false,
data: form.serialize(), //form serizlize data
beforeSend: function(){
// change submit button value text and disabled it
submit.val('Submitting...').attr('disabled', 'disabled');
},
success: function(data){
// Append with fadeIn see
http://stackoverflow.com/a/978731
var item = $(data).hide().fadeIn(800);
$('.comment-block').append(item);

// reset form and button


form.trigger('reset');
submit.val('Submit Comment').removeAttr('disabled');
},
error: function(e){
alert(e);
}
});
});
});

Output:

116
Result:
Thus a web services for finding what people think by asking 500 people’s
opinion for any consumer product has been executed successfully.

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:
117
 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>

// 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');
},
118
// 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
119
</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>
120
<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) {

121
$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;
}

122
$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:

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

123

You might also like