0% found this document useful (0 votes)
267 views

CS8661 IP Lab Record

The document describes how to invoke servlets from HTML forms. It involves creating an HTML form with fields and a submit button that sends the form data to a servlet. The servlet class extends HttpServlet and uses the service() method to get parameter names and values from the request. It then sends a response back to the client using a PrintWriter. The HTML, servlet class, and web.xml configuration are provided as an example.

Uploaded by

Vjay Narain
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
267 views

CS8661 IP Lab Record

The document describes how to invoke servlets from HTML forms. It involves creating an HTML form with fields and a submit button that sends the form data to a servlet. The servlet class extends HttpServlet and uses the service() method to get parameter names and values from the request. It then sends a response back to the client using a PrintWriter. The HTML, servlet class, and web.xml configuration are provided as an example.

Uploaded by

Vjay Narain
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 78

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

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
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="mystyle.css">
</head>
<body>

<h1>This is a heading</h1>
<p>This is a paragraph.</p>

</body>
</html>
mystyle.css
body {
  background-color: lightblue;
}

h1 {
  color: navy;
  margin-left: 20px;
}
Output:

This is a heading

This is a paragraph.

Internal CSS
An internal style sheet may be used if one single HTML page has a unique style.
The internal style is defined inside the <style> element, inside the head section.
Internal styles are defined within the <style> element, inside the <head> section of an

HTML page:
<!DOCTYPE html>
<html>
<head>
<style>
body {
  background-color: linen;
}

h1 {
  color: maroon;
  margin-left: 40px;
}
</style>
</head>
<body>

<h1>This is a heading</h1>
<p>This is a paragraph.</p>

</body>
</html>
Output:
This is a heading

This is a paragraph.

Inline CSS
An inline style may be used to apply a unique style for a single element.
To use inline styles, add the style attribute to the relevant element. The style attribute can contain any
CSS property.
Inline styles are defined within the "style" attribute of the relevant element:

<!DOCTYPE html>
<html>
<body>
<h1 style="color:blue;text-align:center;">This is a heading</h1>
<p style="color:red;">This is a paragraph.</p>
</body>
</html>

Output:
This is a heading

This is a paragraph.

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

Aim:
To create a web page that validate the Registration, user login, user profile and payment by
credit card pages using JavaScript.

Procedure:
 Create a web page which consist of details like User registration
 Create a Text box for User name , Password
 Create a link for creating User profile
 Create a link which navigates to payment gateway
 Create a validation method using Javascript.
Program:
<html>
<head>
<title>Form Validation</title>
<script type="text/javascript"> function
validate()
{
if (document.myForm.Name.value == "" )
{
alert( "Please provide your name!" );
document.myForm.Name.focus(); return false;
}
if (document.myForm.EMail.value == "" )
{
alert( "Please provide your Email!" );
document.myForm.EMail.focus() ; return
false;
}
if (document.myForm.Address.value == "" )
{
alert( "Please provide your Address!" );
document.myForm.Address.focus() ; return false;
}
if (document.myForm.Country.value == "-1" )
{
alert( "Please provide your country!" ); return
false;
}
if (document.myForm.Mobile.value == "" ||
isNaN( document.myForm.Mobile.value )
||document.myForm.Mobile.value.length != 10 )
{
alert ("Provide Your valid Mobile Number");
document.myForm.Mobile.focus() ;
return false;
}
alert("Registration Successful..Thank you!"); return
true;
}
</script>
</head>
<body>
<h1>Welcome Guest...Register With US!!</h1><br><br>
<form action="FormValidation.html" name="myForm"
onsubmit="return validate()">
<table border="0">
<tr>
<td>Name</td>
<td><input type="text" name="Name" size="30" /></td>
</tr>
<tr>
<td>E-Mail</td>
<td><input type="text" name="EMail" size="30"/></td>
</tr>
<tr>
<td>Address</td>
<td> <textarea rows="4" cols="50"
name="Address"></textarea> </td>
</tr>
<tr>
<td>Country</td>
<td>
<select name="Country">
<option value="-1" selected>Select</option>
<option value="1">USA</option>
<option value="2">UK</option>
<option value="3">INDIA</option>
</select>
</td>
</tr>
<tr>
<td>Mobile Number</td>
<td><input type="text" name="Mobile" Size="30"/></td>
</tr>
<tr>
<td>gender</td>
<td>
<input type="radio" name="group1" value="Male" checked
/>Male
<input type="radio" name="group1”
value="Female">Female
</td>
</tr>
<tr>
<td align="right"></td>
<td><input type="submit" value="Register" /></td>
</tr>
</table>
</form>
</body>
</html>

OUTPUT - FORM DESIGN

OUTPUT WITH JS VALIDATION

Result:

Thus the creation of a web page that validates the Registration, user login, user profile and payment
by credit card pages using JavaScript was successfully executed and verified.

4.1. INVOKING SERVLETS FROM HTML FORM


Aim:
To write a java program to invoke servlets from HTML form.

Procedure:
client.html:
(1) Create a web page using HTML form that contains the fields such as label,text and one submit
button.
(2) Set the URL of the server as the value of form’s action attribute.
(3) Run the HTML program.
(4) Submit the form data to the server.

server.java:
(1) Define the class server that extends the property of the class GenericServlet.
(2) Handle the request from the client by using the method service() of GenericServlet class.
(3) Get the parameter names from the HTML form by using the method getParameterNames().
(4) Get the parameter values from the HTML forms by using the method getParameter().
(5) Send the response to the client by using the method of PrintWriter class.

Program:
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServletHtmlDemo extends HttpServlet
{
public void service(HttpServletRequest req,HttpServletResponse res) throws
ServletException,IOException
{
PrintWriter out = res.getWriter();
Enumeration en = req.getParameterNames();
while(en.hasMoreElements())
{
String name=(String)en.nextElement();
out.print(name+"=");
String value=req.getParameter(name);
out.println(value);
out.println(" ");
}
}
}

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>
<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:
Result:
Thus the java program to invoke servlets from HTML form has been executed successfully.

4.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();
}
}
}

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();
}
}
}

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

4.3. 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();

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

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

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


return ~servercode;
}
}

class KeyGenerationException extends Exception {

public KeyGenerationException() {
super();
}

public KeyGenerationException(String msg) {


super(msg);
}
}
<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>
<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>

OUTPUT:
http://localhost:8084/KeyedServerUnlock/?host=localhost&port=8084
Result:
Thus the Java Program for lock and Unlock servlet itself to a particular server IP address and
port number.
4.4. SESSION TRACKING USING HIDDEN FORM FIELDS

Aim:
To perform session tracking using hidden form fields.

Procedure:
1. Create a html file which contains user information.
2. The first servlet will receive these values.
3. First servlet stores them in the hidden form fields.
4. The second servlet will display the user information with greeting message.

Program:
HTML CODE
<html>
<head>
<title>Session Tracking Using Hidden Form Field</title>
</head>
<body>
<form action="Servlet1">
Enter Name:<input type="text" name="username"/><br/>
Enter city:<input type="text" name="usercity"/><br/>
<input type="submit" value="submit"/>
</form>
</body>
</html>

SERVLET1
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Servlet1 extends HttpServlet
{
public void doGet(HttpServletRequest request,HttpServletResponse response)
{
try
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("username");
String c=request.getParameter("usercity");
out.print("<form action=\"Servlet2\">");
out.print("<input type='hidden' name='uname' value="+n+"'>");
out.print("<input type='submit' value='Just click here'>");
out.print("</form>");
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


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

Result:
Thus the Java Program for Session Tracking Using Hidden Form Fields has been executed
successfully.
4.5. SESSION TRACKING A HIT COUNT

Aim:
To write a Java Program for Session tracking a hit count. This servlet uses session tracking to
count the number of times a client has accessed it.

Procedure:
1. Servlet program to keep track of user visiting the page.
2. The count is incremented by one when user visits.
3. The output displays the greeting message.
4. The number of previous access is also displayed.

Program:
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SessionServletDemo extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse res) throws
ServletException,IOException
{
res.setContentType("text/html");
HttpSession session = req.getSession();
String heading;
Integer cnt=(Integer)session.getAttribute("cnt");
if(cnt==null)
{
cnt=new Integer(0);
heading="Welcome you are accessing the page for the first time";
}
else
{
heading="Welcome once again";
cnt=new Integer(cnt.intValue()+1);
}
session.setAttribute("cnt",cnt);
PrintWriter out = res.getWriter();
out.println("<html>");
out.println("<head>");
out.println("</head>");
out.println("<body>");
out.println("<center>");
out.println("<h1>"+heading);
out.println("<h2>The number of previous access="+cnt);
out.println("</center>");
out.println("</body>");
out.println("</html>");
}
}
Output:

Result:
Thus the Java program for Session tracking a hit count has been executed successfully.
5. THREE-TIER APPLICATIONS USING SERVLETS
Aim:
To write java servlet programs to conduct online examination and to display student mark list
available in a database

Procedure:
Client:
 In index.html on the client side declare the contents that you like to transfer to the server
using html form and input type tags.
 Create a submit button and close all the included tags.
Server:
 Import all necessary packages
 Define a class that extends servlet
 In the doPost() method, do the following:
i) Set the content type of the response to "text/html"
ii) Create a writer to the response
iii) Get a paratmeter from the request
iv) If its value is equal to right answer then add 5 to mark variable
v) Similarly repeat step
vi) for all parameters
vii) Display the result in an html format using the writer
Student Mark List Database:
 Import necessary to java packages and javax packages and classes
 Create a class that extends HttpServlet and implements ServletException
 and IOException
 In the doGet() method, do the following:
i) Create a PrintWriter object
ii) Open a connection with the data source name
iii) Write a sql query and execute to get the resultset
iv) Display the resultset information in html form

Program:
SERVLET CODE:
import java.io.*; import java.sql.*; import javax.servlet.*;
import javax.servlet.http.*;
public class StudentServlet3 extends HttpServlet
{
String message,Seat_no,Name,ans1,ans2,ans3,ans4,ans5; int Total=0;
Connection connect; Statement stmt=null; ResultSet rs=null;
public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletExcep-
tion,IOException
{
try
{
String url="jdbc:odbc:NEO"; Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
connect=DriverManager.getConnection(url," "," "); message="Thank you for participating in online
Exam";
}
catch(ClassNotFoundException cnfex){ cnfex.printStackTrace();
}
catch(SQLException sqlex){ sqlex.printStackTrace();
}
catch(Exception excp){ excp.printStackTrace();
}
Seat_no=request.getParameter("Seat_no"); Name=request.getParameter("Name");
ans1=request.getParameter("group1"); ans2=request.getParameter("group2");
ans3=request.getParameter("group3"); ans4=request.getParameter("group4");
ans5=request.getParameter("group5"); if(ans1.equals("True"))
Total+=2;
if(ans2.equals("False"))
Total+=2;
if(ans3.equals("True"))
Total+=2;
if(ans4.equals("False"))
Total+=2;
if(ans5.equals("False"))
Total+=2; try
{
Statement stmt=connect.createStatement();
String query="INSERT INTO student("+"Seat_no,Name,Total"+") VAL-
UES('"+Seat_no+"','"+Name+"','"+Total+"')";
int result=stmt.executeUpdate(query); stmt.close();
}catch(SQLException ex){
}
response.setContentType("text/html"); PrintWriter out=response.getWriter(); out.println("<html>");
out.println("<head>"); out.println("</head>"); out.println("<body bgcolor=cyan>");
out.println("<center>"); out.println("<h1>"+message+"</h1>\n");

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>");
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>
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.
6.CONVERTING STATIC WEB PAGES TO DYNAMIC WEB PAGES
Aim:
To convert the static web pages into dynamic web pages using servlets (or JSP) and cookies.

Procedure:
step1: we will create ahtml form for entering the user name,password and card ID.
Step2:From the above HTML form, the servlet program is invoked in which the validity of
the user name,password and card id is checked.if it is a valid user then the welcome message will be
displayed otherwise the “invalid user” message will be displayed. In this servlet we set the cookies in
which the current user name is stored.
Step3: compile the above servlet Login servlet.java and copy its class file in tomcats folder at
c:\tomcatdirectory\webapps\examples\WEB-INF\classes.
Then edit the web.xml in WEB-INF folder.We must store he user information such as user
name,password and card id in the web.xml using init-param.
Step4: On successful login , the information from the cookie is checked and shopping cart
page for corressponding user can be displayed.
Step5:Compile the above servlet LoginSuccess.java and copy its class file in the tomcat's
folder at c:\tomcatdirectory\webapps\examples\WEB-INF\classes.
Then edit the web.xml in WEB-INF folder.
Step6:Start tomcat web server.Open the web browser and display the login form created in
step1.

Index.jsp
<html>
<head>
<body>
<form action="http://localhost:8084/ddd/LoginServlet" method="post">
Enter username:
<input type="text" value""name="user">
<br>
Enter Password:
<input type="password" value""name="password">
<br>
Enter Card ID:
<input type="text" value""name="cardID">
<br>
<br> <br> <br>
<input type="submit" value="login">
</form>
</body>

Loginservlet.html
import java.io.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {

String usr=request.getParameter("user");
String pwd=request.getParameter("password");
String card=request.getParameter("cardID");
boolean flag=true;

String[] userID=getInitParameter("usernames").split(",");
String[] password=getInitParameter("passwords").split(",");
String[] cardids=getInitParameter("cardIDs").split(",");

int i;
for(i=0;i<userID.length;i++)
{
if(userID[i].equals(usr)&&password[i].equals(pwd)&&cardids[i].equals(card))
{
flag=false;
Cookie MyCookie=new Cookie("CurrentUser", usr);
MyCookie.setMaxAge(60*60);
response.addCookie(MyCookie);
response.sendRedirect("http://localhost:8084/ddd/LoginSuccess");
}
}
if(flag==true)
{
out.print("Error");
out.println("<h4>Invalid user,please try again by clicking following link</h4>");
out.println("<a href='http://localhost:8084/ddd/'>"+"LoginForm.html");
}
}
finally {
out.close();
}
}

LoginSuccess.java
import java.io.*;
import java.net.*;

import javax.servlet.*;
import javax.servlet.http.*;
public class LoginSuccess extends HttpServlet {protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
Cookie[] my_cookies=request.getCookies();
response.setContentType("text/html");
PrintWriter out=response.getWriter();
out.print("Login Success");
out.println("<b>");
String userName=null;
if(my_cookies!=null)
{
for(Cookie cookie:my_cookies)
{
if(cookie.getName().equals("currentUser"))
userName=cookie.getValue();
}
}
out.print("<h3>Login Success!!!Welcome</h3>");
out.print("<h2>This is a Shopping cart for"+userName+"</h2>");
out.close();

}
}

Web.xml
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>LoginServlet</servlet-class>
<init-param>
<param-name>usernames</param-name>
<param-value>user1,user2,user3</param-value>
</init-param>
<init-param>
<param-name>passwords</param-name>
<param-value>pwd1,pwd2,pwd3</param-value>
</init-param>
<init-param>
<param-name>cardIDs</param-name>
<param-value>111,222,333</param-value>
</init-param>
</servlet>
<servlet>
<servlet-name>LoginSuccess</servlet-name>
<servlet-class>LoginSuccess</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>LoginSuccess</servlet-name>
<url-pattern>/LoginSuccess</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
Output:
Result:

Thus the conversion of the static web pages into dynamic web pages using servlets cookies has
been executed successfully.
Ex.NO 7
DYNAMIC WEBPAGES USING JSP

AIM:

Redo the previous task using JSP by converting the static web pages of
assignments 2 into dynamic web pages. Create a database with user information and books
information and books information. The books catalogue should be dynamically loaded from
the database. Follow the MVC architecture while doing the website.
PROCEDURE:
1) Create your own directory under tomcat/webapps (e.g. tr1)
2) Copy the html files in tr1
3) Copy the jsp files also into tr1
4) Start tomcat give the following command
Catalina.bat run
At install-dir/bin
5) at I.E give url as http://localhost:8081/tr1/main.html

Home page:
Main.html:

<html>
<body>
<br><br><br><br><br><br>
<h1 align="center"><u>ONLINE BOOK
STORAGE</u></h1><br><br><br>
<h2 align="center"><PRE>
<b> Welcome to online book storage. Press
LOGIN if you are having id Otherwise press
REGISTRATION
</b></PRE></h2>
<br><br><pre>
<div align="center"><a href="login.html">LOGIN</a>
<a href="reg.html">REGISTRATION</a></div></pre>
</body></html>
Login page:
Login.html:

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

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

<html>
<body><br /><br /><br />
<form name="myform" method="post" action="profile.jsp">
<div align="center"><pre>
LOGIN ID :<input type="text" name="id" /><br />
</pre><br /><br />
</div>
<br /><br />
<div align="center">
<input type="submit" value="ok" onclick="validate()" />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="reset" value="clear"
/>
</div>
</form>
</body>
</html>
Books catalog page:
Catalog.html:

<html>
<body><br /><br /><br />
<form method="post" action="catalog.jsp">
<div align="center"><pre>
BOOK TITLE :<input type="text" name="title" /><br />
</pre><br /><br />
</div>
<br /><br />
<div align="center">
<input type="submit" value="ok"
name="button1"/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<input type="reset" value="clear" name="button2"/>
</div>
</form>
</body> </html>
Shopping cart, Payment by credit card, Order
Conformation page:

Order.html:

<html>
<body><br /><br />
<form method="post" action="order.jsp">
<div align="center"><pre> ID
:<input type="text" name="id" /><br />
PASSWORD
:<input type="password" name="pwd" /><br/> TITLE
:<input type="text" name="title" /><br /> NO. OF BOOKS :<input type="text"
name="no" /><br />
DATE
:<input type="text" name="date" /><br />
CREDIT CARD NUMBER :<input type="password" name="cno" /><br
/></pre><br /><br />
</div>
<br /><br />
<div align="center">
<input type="submit" value="ok" name="button1"/>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="reset" value="clear" name="button2"/>
</div>
</form>
</body>
</html>
Login JSP:
Login.jsp:

<%@page import="java.sql.*"%>
<%@page import="java.io.*"%>
<% out.println("<html><body>"); String
id=request.getParameter("id");
String pwd=request.getParameter("pwd");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:orcl","scott","tiger");
Statement
stmt=con.createStatement();
String sqlstmt="select id,pwd from login"; ResultSet
rs=stmt.executeQuery(sqlstmt); int flag=0;
while(rs.next())
{
if(id.equals(rs.getString(1))&&pwd.equals(rs.getString(2)))
{
flag=1;
}
}
if(flag==0)
{
out.println("<br><br>SORRY INVALID ID TRY AGAIN
ID<br><br>");
out.println("<a href=\"login.html\">press LOGIN to
RETRY</a>");
}
else
{
out.println("<br><br>VALID LOGIN ID<br><br>");
out.println("<h3><ul>");
out.println("<li><a
href=\"profile.html\"><fontcolor=\"black\">USER
PROFILE</font>
</a></li><br><br>");
out.println("<li><a
href=\"catalog.html\"><fontcolor=\"black\">BOOKS
CATALOG</font></a></li><br><br>"); out.println("<li><a
href=\"order.html\"><fontcolor=\"black\">ORDER
CONFIRMATION</font>
</a></li></ul><br><br>");
}
out.println("</body></html>");
con.close();
%>
Registration JSP:
Reg.jsp :

<%@page import="java.sql.*"%>
<%@page import="java.io.*"%>
<% response.setContentType("text/html");
out.println("<html><body>");
String name=request.getParameter("name"); String
addr=request.getParameter("addr"); String
phno=request.getParameter("phno");
String id1=request.getParameter("id"); String
pwd1=request.getParameter("pwd"); int
no=Integer.parseInt(phno);
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:orcl","scott","tiger");
Statement
stmt=con.createStatement();
String sqlstmt="select id,pwd from login"; ResultSet
rs=stmt.executeQuery(sqlstmt); int flag=0;
while(rs.next())
{ if(id1.equals(rs.getString(1))&&pwd1.equals(rs.getString(2)))
{
flag=1;
}
}
if(flag==1)
{ out.println("<br><br>SORRY INVALID ID ALREADY EXITS
TRY AGAIN WITH NEW ID<br><br>");
out.println("<a href=\"reg.html\">press REGISTER to
RETRY</a>");
}
else
{ Statement stmt1=con.createStatement(); stmt1.executeUpdate("insert into login
values('"+name+"','"+addr+"',"+no+",'"+id1+"','"+pwd1+"');");
out.println("<br><br>YOUR DETAILS
ARE
ENTERED<br><br>");
out.println("<a href=\"login.html\">press LOGIN to login</a>");
}
out.println("</body></html>");
con.close();
%>
Profile JSP:
Profile.jsp:

<%@page import="java.sql.*"%>
<%@page import="java.io.*"%>
<% out.println("<html><body>"); String
id=request.getParameter("id");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection
con=DriverManager.getConnection("jdbc:odbc:orcl","scott","tiger");
Statement
stmt=con.createStatement();
String sqlstmt="select * from login where id="+id+""; ResultSet
rs=stmt.executeQuery(sqlstmt);
int flag=0;
out.println("<br><br><br>");
while(rs.next())
{
out.println("<div align=\"center\">");
out.println("NAME :"+rs.getString(1)+"<br>");
out.println("ADDRESS
:"+rs.getString(2)+"<br>");
out.println("PHONE NO
:"+rs.getString(3)+"<br>");
out.println("</div>"); flag=1;
}
if(flag==0)
{
out.println("<br><br>SORRY INVALID ID TRY AGAIN
ID<br><br>");
out.println("<a href=\"profile.html\">press HERE to
RETRY</a>");
}
out.println("</body></html>");
con.close(); %>
Catalog JSP:
Catalog.jsp:

<%@page import="java.sql.*"%>
<%@page import="java.io.*"%>
<% out.println("<html><body>");
String title=request.getParameter("title");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:orcl","scott","tiger");
Statement
stmt=con.createStatement();
String sqlstmt="select * from book where title=\'"+title+"\'"; ResultSet
rs=stmt.executeQuery(sqlstmt);
int flag=0;
while(rs.next())
{
out.println("<div align=\"center\">");
out.println("TITLE
:"+rs.getString(1)+"<br>");
out.println("AUTHOR :"+rs.getString(2)+"<br>"); out.println("VERSION
:"+rs.getString(3)+"<br>");
out.println("PUBLISHER :"+rs.getString(4)+"<br>"); out.println("COST
:"+rs.getString(5)+"<br>");
out.println("</div>"); flag=1;
}
if(flag==0)
{
out.println("<br><br>SORRY INVALID TITLE TRY
AGAIN <br><br>");
out.println("<a href=\"catalog.html\">press HERE to
RETRY</a>");
}
out.println("</body></html>");
con.close();
%>
Order servlet:
Order.java:

<%@page import="java.sql.*"%>
<%@page import="java.io.*"%>
<% int count;
out.println("<html><body>");
String id=request.getParameter("id"); String
pwd=request.getParameter("pwd"); String
title=request.getParameter("title"); String
count1=request.getParameter("no"); String
date=request.getParameter("date"); String
cno=request.getParameter("cno");
count=Integer.parseInt(count1);
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:orcl","scott","tiger");
Statement
stmt=con.createStatement();
String sqlstmt="select id,pwd from login"; ResultSet
rs=stmt.executeQuery(sqlstmt); int flag=0,amount,x;
while(rs.next())
{
if(id.equals(rs.getString(1))&&pwd.equals(rs.getString(2)))
{
flag=1;
}
}
if(flag==0)
{
out.println("<br><br>SORRY INVALID ID TRY AGAIN
ID<br><br>");
out.println("<a href= \"order.html \" >press HERE to RETRY</a>");
}
else
{
Statement stmt2=con.createStatement();
String s="select cost from book where title=\'"+title+"\'"; ResultSet
rs1=stmt2.executeQuery(s);
int flag1=0;
while(rs1.next())
{
flag1=1; x=Integer.parseInt(rs1.getString(1));
amount=count*x;
out.println("<br><br>AMOUNT
:"+amount+"<br><br><br><br>"); Statement
stmt1=con.createStatement();
stmt1.executeUpdate("insert into details
values('"+id+"','"+title+"',"+amount+",'"+cno+"');");
out.println("<br>YOUR ORDER has taken<br>");
}
if(flag1==0)
{
out.println("<br><br><br>SORRY INVALID ID TRY
AGAIN ID<br><br>");
out.println("<a href=\"order.html\">press HERE to
RETRY</a>");
}
}
out.println("</body></html>");
con.close();
%>

RESULT:

Thus the conversion of the static web pages into dynamic web pages using JSP has been executed
successfully.
Ex.NO 8
XML DOCUMENT TO STORE INFORMATION OF 10 USERS

AIM:

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

PROGRAM:

User.xml

<?xml version=”1.0”?>
<userlist>
<user>

<userid>usr01</userid>
<username>Gouse</username>
<address>DSNR</address>
<phone>8801550101</phone>
<email>[email protected]</email>
</user>
<user>
<userid>usr02</userid>
<username>D Divakar</username>
<address>Ameerpet</address>
<phone>9888888888</phone>
<email>D [email protected]</email>
</user>
<user>
<userid>usr03</userid>
<username>Rajinth</username>
<address>SR Nagar</address>
<phone>9866666666</phone>
<email>[email protected]</email>
</user>
<user>

<userid>usr04</userid>
<username>M Vijaya</username>
<address>DESHMUKHI</address>

<phone>9835994445</phone>
<email>M [email protected]</email>
</user>
<user>
<userid>usr05</userid>
<username>Kusuma</username>
<address>KOTI</address>
<phone>968877555</phone>
<email>[email protected]</email>
</user>

User.xml

<?xml version=”1.0”?>
<userlist>
<user>

<userid>usr01</userid>
<username>Gouse</username>
<address>DSNR</address>
<phone>8801550101</phone>
<email>[email protected]</email>
</user>
<user>
<userid>usr02</userid>
<username>D Divakar</username>
<address>Ameerpet</address>
<phone>9888888888</phone>
<email>D [email protected]</email>
</user>
<user>
<userid>usr03</userid>
<username>Rajinth</username>
<address>SR Nagar</address>
<phone>9866666666</phone>
<email>[email protected]</email>
</user>
<user>

<userid>usr04</userid>
<username>M Vijaya</username>
<address>DESHMUKHI</address>

<phone>9835994445</phone>
<email>M [email protected]</email>
</user>
<user>
<userid>usr05</userid>
<username>Kusuma</username>
<address>KOTI</address>
<phone>968877555</phone>
<email>[email protected]</email>
</user>
<user>
<userid>usr06</userid>
<username>P Kalpana</username>
<address>KOTI</address>
<phone>968875554</phone>
<email>P [email protected]</email>
</user>

<user>
<userid>usr07</userid>
<username>V Anitha</username>

<address>KPHB</address>
<phone>968888554</phone>
<email>V [email protected]</email>
</user>

<user>
<userid>usr08</userid>
<username>M Ramesh</username>
<address>IBP</address>
<phone>968878554</phone>
<email>M [email protected]</email>
</user>

<user>
<userid>usr09</userid>
<username>Raswitha</username>
<address>DSNGR</address>
<phone>968899554</phone>
<email>[email protected]</email>
</user>

<user>
<userid>usr10</userid>
<username>A Prasanna</username>
<address>KPHB</address>
<phone>9088008554</phone>
<email>A [email protected]</email>
</user>

</userlist>
User.html

<html>
<head>
<script language="javascript">
function fncDisplayInfo()
{
var xhttp=null;
var flag=0;
var userid = document.frm.uname.value;
var xmlDoc = new ActiveXObject("microsoft.xmldom"); xmlDoc.load("user.xml");
var noOfUsers = xmlDoc.getElementsByTagName("userlist")[0].childNodes.length; for(var
i=0;i<parseInt(noOfUsers);i++)

{
var uid
=xmlDoc.getElementsByTagName("user")[i].childNodes[0].childNodes[0].nodeValue;
if(uid == userid)
{
document.write("<h1> User Details</h1>");
var userName =
xmlDoc.getElementsByTagName("user")[i].childNodes[1].childNodes[0].nodeValue;
var Address
=xmlDoc.getElementsByTagName("user")[i].childNodes[2].childNodes[0].nodeValue;
var phone =
xmlDoc.getElementsByTagName("user")[i].childNodes[3].childNodes[0].nodeValue;
var email=
xmlDoc.getElementsByTagName("user")[i].childNodes[4].childNodes[0].nodeValue;
document.write("<br><b>User ID :&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp"+uid)
document.write("<br>User Name :&nbsp"+userName);
document.write("<br>Address :&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp "+Address);
document.write("<br>Phone no : &nbsp&nbsp&nbsp&nbsp&nbsp"+phone);

document.write("<br>E - Mail : &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp"+email);


flag =1;
break;
}
}
if(flag==0)
{
alert("InValid User");
}
}
</script>
</head>
<body>
<center>
<h1><b>User Information</h1>
<form name="frm">
User ID : <input type="text" name="uname"><br>
<input type="button" name="btn" value="Submit" onclick="fncDisplayInfo()"> </form>
</center>
</body>
</html>
Output:

RESULT:
Thus the conversion program, which takes user ID as input and returns the user details by taking the
user information from XML Document has been executed successfully.

x.NO 9 .1.FORM VALIDATION USING PHP Regular expression

AIM:
To create a form and validate using PHP regular expression.

PROCEDURE:

HP - Validate Name
The code below shows a simple way to check if the name field only contains letters and whitespace.
If the value of the name field is not valid, then store an error message:
$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
PHP - Validate E-mail
The easiest and safest way to check whether an email address is well-formed is to use PHP's
filter_var() function.

In the code below, if the e-mail address is not well-formed, then store an error message:

$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
PHP - Validate URL
The code below shows a way to check if a URL address syntax is valid (this regular expression also
allows dashes in the URL). If the URL address syntax is not valid, then store an error message:

$website = test_input($_POST["website"]); if
(!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[
-a-z0-9+&@#\/%=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}
PHP - Validate Name, E-mail, and URL
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace if (!preg_match("/^[a-zA-Z ]*$/",
$name)) {
$nameErr = "Only letters and white space allowed";
}
}

if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}

if (empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
// check if URL address syntax is valid (this regular expression also allows dashes in the
URL)
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!
:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}
}

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

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

<!DOCTYPE HTML>  
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>  

<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";

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

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

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

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

<h2>PHP Form Validation Example</h2>


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

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

</body>
</html>
OUTPUT:

PHP Form Validation Example

* required field

Name:   *

E-mail:   *

Website: 

Comment: 

Gender:  Female  Male  Other *

Submit

RESULT:

Thus the form was created using PHP and the validation using regular expression has been executed
successfully.
9.2.PHP Stores a FORM data to database
AIM:
To create a form using PHP and the store the data from the form to database.

PROCEDURE:

The following steps are required to design a registration form (Sign Up Form):


 
Step 1: Firstly, install a virtual server on your computer (eg Xampp, Wamp).
 
Xampp is a free and open-source cross-platform web server solution stack package developed by Apache
Friends, consisting mainly of the Apache HTTP Server, MySQL database, and interpreters for scripts written
in the PHP and Perl programming languages. XAMPP stands for Cross-Platform (X), Apache (A), MySQL
(M), PHP (P), and Perl (P).
 

 
Figure: Xampp Server
 
Step 2: Next we will require an editor where the HTML code has to be written. You can use any editor (such
as Notepad++, Adobe Dreamweaver, NetBeans, etc). Here we will use Notepad ++.
 
Step 3: Install Notepad++. Here are the steps:
 

58
 
Figure: Notepad ++
 
Notepad++ is a source code editor used with Microsoft Windows. It supports editing in tabular form, which
allows us to work with multiple open files in a single window.
 
Notepad++ is distributed as free software.
 
Click on the first link in the browser window. After clicking the first link the following window will appear.
 

 
Figure: Download Notepad ++   
 
Download the software by clicking the download button.

59
 
Step 4: Open the Notepad++ text editor and write the HTML code for designing the HTML Sign Up page.\
 
<html>    
    <head>    
        <title>Registration Form</title>    
    </head>    
    <body>    
        <link href = "registration.css" type = "text/css" rel = "stylesheet" />    
        <h2>Sign Up</h2>    
        <form name = "form1" action="modified.php" method = "post" enctype = "multipart/form-data" >    
            <div class = "container">    
                <div class = "form_group">    
                    <label>First Name:</label>    
                    <input type = "text" name = "fname" value = "" required/>    
                </div>    
                <div class = "form_group">    
                    <label>Middle Name:</label>    
                    <input type = "text" name = "mname" value = "" required />    
                </div>    
                <div class = "form_group">    
                    <label>Last Name:</label>    
                    <input type = "text" name = "lname" value = "" required/>    
                </div>    
                <div class = "form_group">    
                    <label>Password:</label>    
                    <input type = "password" name = "pwd" value = "" required/>    
                </div>    
            </div>    
        </form>    
    </body>    
</html>    
 
CSS stands for Cascading Style Sheets
 
This is used for styling purpose. HTML coding is just a structure and CSS is applied to dictate your website's
look and feel. Font size, font color, font style styling of images, page layout, mouse-over effects and more are
determined by CSS. The CSS applied over the above HTML coding is given below.
.container {  
  max-width: 1350px;  
  width: 100%;  
  margin: 50px;  
  height: auto;  
  display: block;  
}  
  
body {  
  color: #8A2BE2;  
  font-size: 20px;  
  font-family: Verdana, Arial, Helvetica, monospace;  
  background-color: #F0E8A0;  
}  
  
h2 {  
  text-align: center;  
}  
  

60
.form_group {  
  padding: 10px;  
  ;    
display: block;  
}  
  
label {  
  float: left;  
  padding-right: 50px;  
  line-height: 10%;  
  display: block;  
  width: 208px;  
 
Step 5:  Apply CSS on the HTML code. General rules for applying CSS are:
 
We use dot(.) beside any class to apply effects into it and ‘#’ tag before any ID. E.g.
 .container {
   // css attributes will be written here
 
}
 
Here I have taken container as a class. Class is user-defined.
 Note: Save the Sign_Up page in the xampp folder->htdocs->create a new folder( user-defined). Inside
this new folder, you have to keep all the data related to your project. It may be any kind of images used in
webpage, HTML coding, or CSS coding. I mean to say all the things that are used in creating a web page
must be under one roof (i.e under one folder). 
 

 
Figure: Sign_Up
61
 
After writing the HTML code and applying the above CSS, the registration page would look like above.
 
Next, we will insert data into the fields of the sign_up page and store the information in MySQL.
 
For that, we have to start the xampp controller. Start Apache and MYSQL in the XAMPP controller.
 
Now we will go to the next level where we will make use of PHP syntax.
 
PHP
 
PHP is a server-side scripting language designed for web development but also used as a general-purpose
programming language. PHP is an acronym for "PHP: Hypertext Preprocessor".
 

 
Figure: Xammp Start
 
PHP is a widely-used, open-source scripting language. PHP scripts are executed on the server. PHP is free to
download and use. PHP code is executed on the server, and the result is returned to the browser as plain
HTML. PHP files have extension ".php". PHP can collect form data.
 
PHP can add, delete, modify data in your database. It runs on various platforms (Windows, Linux, Unix, Mac
OS X, etc.) and supports a wide range of databases. PHP is easy to learn and runs efficiently on the server-
side.
 
PHP Variables (Rules)
 A variable starts with the $ sign, followed by the name of the variable.
 A variable name must start with a letter or the underscore character.

 A variable name cannot start with a number.

 Variable names are case-sensitive ($age and $AGE are two different variables).

62
Output Variable
 
The PHP ‘echo’ statement is often used to output data to the screen.
 
PHP FORMS
 
Write Html coding for sign_up page and save it as index.php. Again create a PHP page
named connection.php where we will write the code for creating a connection with the database.
<?php  
       $servername = "localhost";  
       $username = "root";  
       $password = "";  
       $conn = mysql_connect ($servername , $username , $password) or die("unable to connect to host");  
       $sql = mysql_select_db ('test',$conn) or die("unable to connect to database"); 
?>   
The PHP script are always written between (<?php (opening) and ?> closing).
 
Here as you are seeing that I have used user-defined variables to assign something. This makes me easy to
write code effectively and in a clean way.
 
Here I have assigned localhost to $servername, ’root’ to $username and password has been left blank. Again
I have written mysql_connect()—this is mainly used to open a connection to MySQL server. Again we have
used mysql_select_db()—this is used to select the database created in localhost/phpmyadmin.
 
Now let us create a database in MySQL. The PHPMyAdmin window will look like the following screenshot:
 

 
Figure:  phpmyadmin
 

63
Here you can create your own database and as many tables inside that.
 
Suppose here I have created a database named ‘test’, inside that I have created a table named ‘registration’. In
this table, we will create fields that are used in our registration form such as fname, mname, lname, pwd, cnf,
mail, number, sex, address, code, city, country, skills, attach_file.
 
Note: Here we can write any name for the concerned fields, just keep in mind the names you have given for
the relative fields.
 
You can create a table manually or by writing queries. Here, I have created it manually.
 

 
Figure: Insert fields
 
Here write data type (most of the time we use varchar), length in numbers. After filling the fields name click
Go to continue.
 
After inserting you can view the inserted fields where the data will be fetched from the form.
 
The structure is as in the following screenshot:
 

64
 
Figure: Structure
 
Now create another php page and name it modified.php.
 
On this page, we will write code to see how we can fetch data from the fields.
 
For this, we will make use of form methods through which we will retrieve the data entered into the fields and
store it into our MySQL database.
 
The method attribute specifies how to send form-data (the form-data is sent to the page specified in the action
attribute). The form-data can be sent as URL variables (with method="get") or as HTTP post transaction
(with method="post").
 
Basically we use any of the following two methods to fetch data from the fields.
 GET Method: The GET method produces a long string that appears in the browser's location. It has a
restriction of sending up to 1024 characters only. We should never use the GET method if we have a
password or other sensitive information to be sent to the server. The PHP
provides $_GET associative array to access all the information sent using the GET method.

 POST Method: In this method, parameters are not saved in browser history. Data is not shown in the
browser's URL. POST is safer than GET. The PHP provides $_POST associative array to access all
the information sent using the POST method.

Here I have included listing.php file because in this PHP file I have written the code for listing all the
inserted data.

65
<?php    
    
include "connection.php";    
    
if(isset($_GET['id'])){    
$sql = "delete from registration where id = '".$_GET['id']."'";    
$result = mysql_query($sql);    
}    
    
$sql = "select * from registration";    
$result = mysql_query($sql);    
?>    
<html>    
    <body>    
        <table width = "100%" border = "1" cellspacing = "1" cellpadding = "1">    
            <tr>    
                <td>Id</td>    
                <td>First Name</td>    
                <td>Middle Name</td>    
                <td>Last Name</td>    
                <td>Password</td>    
                <td>Confirm Password</td>    
                <td>Email</td>    
                <td>Contact No.</td>    
                <td>Gender</td>    
                <td>Address</td>    
                <td>Pincode</td>    
                <td>City</td>    
                <td>Country</td>    
                <td>Skills</td>    
                <td>Files</td>    
                <td colspan = "2">Action</td>    
            </tr>    
        </table>    
    </body>    
</html>    
 
Note: We have to include connection.php file in all the pages because the connection code has been written
in connection.php file only. Until and unless the connection is established, the data can’t be sent to the
database. Here I have written an IF-ELSE condition to check whether any id is coming or not.
 
The isset () function is used to check whether a variable is set or not.
 
Then I have written a query for delete and saved in a local variable named $sql.
 
After that mysql_query() is used to execute the query written above. Again we have written a query to select
all the elements of the table created.
<?php    
    
while($row = mysql_fetch_object($result)){    
    
    
?>  
    <tr>  
        <td>  
            <?php echo $row->id;?>  
        </td>  

66
        <td>  
            <?php echo $row->fname;?>  
        </td>  
        <td>  
            <?php echo $row->mname;?>  
        </td>  
        <td>  
            <?php echo $row->lname;?>  
        </td>  
        <td>  
            <?php echo $row->pwd;?>  
        </td>  
        <td>  
            <?php echo $row->cnf;?>  
        </td>  
        <td>  
            <?php echo $row->mail;?>  
        </td>  
        <td>  
            <?php echo $row->number;?>  
        </td>  
        <td>G  
            <?php echo $row->sex;?>  
        </td>  
        <td>  
            <?php echo $row->address;?>  
        </td>  
        <td>  
            <?php echo $row->code;?>  
        </td>  
        <td>  
            <?php echo $row->city;?>  
        </td>  
        <td>  
            <?php echo $row->country;?>  
        </td>  
        <td>  
            <?php echo $row->skills;?>  
        </td>  
        <td>  
            <?php echo $row->attach_file;?>  
        </td>  
        <td> <a href="listing.php?id =     
            <?php echo $row->id;?>" onclick="return confirm('Are You Sure')">Delete    
        </a> | <a href="index.php?id =     
            <?php echo $row->id;?>" onclick="return confirm('Are You Sure')">Edit    
        </a> </td>  
        <tr>  
            <? php } ?>  
On the same page that is modified.php, now we will write another group of code for displaying the data into
the table created.
 
For that, we will write a while condition where we will fetch the data from the database until and unless the
data is coming.
 
Here I have saved the query mysql_fetch_object() into a local variable ‘$row’.
 

67
Then I have echoed the relative fields data into the corresponding table entry.
 
Now this tutorial of insertion of data into the database and showing it in the form of lists has been
successfully completed.
 
Have a look at the final result.
 

RESULT:
Thus the form was created using PHP and the transfer of data from the form to database has been
executed successfully.
10. WRITE A WEB SERVICES FOR FINDING WHAT PEOPLE THINK BY
ASKING 500 PEOPLE’S OPINION FOR ANY CONSUMER PRODUCT
68
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();

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

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

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

70
</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']);
$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');

71
?>

Function.php
<?php
/**
* Connect to mysql server
* @param bool
* @use true to connect false to close
*/
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;

72
-o-font-smoothing: antialiased;
font-smoothing: antialiased;
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{
clear: both;
margin:0;
padding: 10px;
overflow: hidden;

73
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{
clear: both;
margin: 10px;
width: 500px;
}

/* form styling */
input[type="text"],
input[type="email"],
input[type="tel"],
input[type="url"],

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

75
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;
}
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);

76
}
});
});
});

Output:

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

78

You might also like