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

CS8661-IP - RECORD 2024-2025 VTH SEM

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 60

Reg No: ***

DEPARTMENT OF CSE
EX NO: 1
DATE: Create a Web Page Using Bootstrap

AIM
To create a simple web page using Bootstrap framework. Bootstrap is a popular
front-end framework for developing responsive and mobile-first websites.
ALGORITHM:
1. HTML Structure: The HTML structure is defined with the necessary elements
like <header>, <main>, and <footer>. These sections provide the basic
structure of the web page.
2. Bootstrap Integration: Bootstrap CSS and JavaScript files are imported from
CDN (Content Delivery Network). This allows the usage of Bootstrap classes
and components to style the web page and make it responsive.
Header Section:
3. The <header> contains a navigation bar (<nav>) styled with Bootstrap classes.
4. Inside the navigation bar, there's a link (<a>) with the text "My Web Page",
functioning as the website's title.
Main Section:
5. The <main> section contains a <div> element with the class "container" and
margin top class "mt-5". This class helps in creating a responsive layout and
adding space between elements.
6. Inside the container, there's an <h1> heading with the text "Welcome to My
Web Page" and a <p> paragraph providing some information about the web
page.
Footer Section:
7. The <footer> contains copyright information.
8. It has a dark background color (bg-dark) and light text color (text-light) to
improve visibility.
9. Similar to the main section, it contains a <div> element with the class
"container" to provide padding and center the content.
10. Inside the container, there's a <p> element displaying the copyright text.

P a g e 1 | 60
Reg No: ***
DEPARTMENT OF CSE
11. Bootstrap JavaScript: Bootstrap JavaScript file is imported at the end of the
body section. This enables the use of Bootstrap components that require
JavaScript functionality, such as dropdowns and modals.

PROGRAM1. HTML:

<!DOCTYPE html>
<html>
<head>
<title>Simple Web Page using Bootstrap</title>
<!-- Import Bootstrap CSS -->
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstra
p.min.css">
</head>
<body>
<header>
<nav class="navbarnavbar-expand-lgnavbar-dark bg-dark">
<a class="navbar-brand"
href="file:///C:/Users/2021PECCS189/Desktop/cse189/website.html"
>My Web Page</a>
</nav>
</header>
<main>
<div class="container mt-5">
<h1>Welcome to My Web Page</h1>
<p>This is a simple web page created using Bootstrap.</p>
</div>
</main>
<footer class="bg-dark text-light py-3">
<div class="container">
<p>&copy; 2023 My Web Page. All rights reserved.</p>
</div>
</footer>
<!-- Import Bootstrap JavaScript -->
<script
src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.
min.js"></script>
P a g e 2 | 60
Reg No: ***
DEPARTMENT OF CSE
</body>
</html>

OUTPUT:

P a g e 3 | 60
Reg No: ***
DEPARTMENT OF CSE

EX.NO: 2
DATE: Implement Typescript classes and functions
AIM
To write a TypeScript code is to define a class Rectangle that represents a
rectangle shape, with functions to calculate its area and perimeter.
ALGORITHM
Define the Rectangle Class:
1. Create a TypeScript class named Rectangle.
2. Define private properties width and height to store the dimensions of the
rectangle.
3. Write a constructor that takes width and height as parameters and initializes the
properties.
4. Define public methods getArea() and getPerimeter() to calculate the area and
perimeter of the rectangle, respectively.
Calculate Area and Perimeter Function (calculateAreaAndPerimeter()):
5. Inside the function, create an instance of the Rectangle class with width 5 and
height 10 (as provided in the example).
6. Call the getArea() method of the Rectangle instance to calculate the area and
store it in a variable.
Call the getPerimeter() method of the Rectangle instance to calculate the perimeter
and store it in a variable.
7. Log the calculated area and perimeter to the console using console.log().
8. Call the calculateAreaAndPerimeter() Function:
9. Finally, call the calculateAreaAndPerimeter() function to execute the logic
defined within it.
Output:
10. Upon execution, the console will display the calculated area and perimeter of
the rectangle.

P a g e 4 | 60
Reg No: ***
DEPARTMENT OF CSE
PROG2.HTML

class Rectangle{
private width:number;
private height:number;
constructor(width:number,height:number)
{
this.width=width;
this.height=height;
}
public getArea():number{
return this.width*this.height;
}
public getPerimeter():number{
return 2*(this.width+this.height);
}
}
function calculateAreaAndPerimeter():void{
const rectangle=new Rectangle(5,10);
const area=rectangle.getArea();
const perimeter=rectangle.getPerimeter();
console.log(`Area:${area}`);
console.log(`Perimeter:${perimeter}`);
}
calculateAreaAndPerimeter();
OUTPUT:

P a g e 5 | 60
Reg No: ***
DEPARTMENT OF CSE

EX.NO: 3
DATE: Implement Bootstrap Typography
AIM
To demonstrate a various typographic elements and styles available in Bootstrap
framework.
ALGORITHM
1. Bootstrap Integration:
Bootstrap CSS is imported from the CDN (Content Delivery Network) using the
<link> tag within the <head> section. This enables the usage of Bootstrap classes and
styles.
Bootstrap JavaScript is imported from the CDN using the <script> tag at the end of
the <body> section. This is optional, but some Bootstrap components require
JavaScript functionality.
2. Typography Elements:
Various heading elements <h1> to <h6> are used to display different levels of
headings.
<p> elements with different Bootstrap text classes are used to demonstrate various
text styles such as lead, muted, primary, success, danger, info, and warning.
<blockquote> element with the class blockquote is used to create a blockquote. Inside
it, there is a <p> element for the quote text and a <footer> element with the class
blockquote-footer for the author's name.
<ul> element with the class list-unstyled is used to create an unordered list without
any bullets.
3.Classes and Styles:
Various Bootstrap classes such as container, mt-5, lead, text-muted, text-primary, text-
success, text-danger, text-info, text-warning, blockquote, mb-0, blockquote-footer,
and list-unstyled are applied to elements to achieve desired styles and effects.
4.Output:
The HTML content is rendered in the browser, showcasing different typographic
elements and styles provided by Bootstrap.
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap Typography</title>
<!--Import Bootstrap CSS-->
<link
href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
rel="stylesheet">
</head>
P a g e 6 | 60
Reg No: ***
DEPARTMENT OF CSE
<body>
<div class="container mt-5">
<h1>Heading 1</h1>
<h2>Heading 2</h2>
<h3>Heading 3</h3>
<h4>Heading 4</h4>
<h5>Heading 5</h5>
<h6>Heading 6</h6>
<p class="lead">This is a lead paragraph.</p>
<p>This is a normal paragraph.</p>
<p class="text-muted">This is a muted paragraph.</p>
<p class="text-primary">This is a primary paragraph.</p>
<p class="text-success">This is a success paragraph.</p>
<p class="text-danger">This is a danger paragraph.</p>
<p class="text-info">This is an info paragraph.</p>
<p class="text-warning">This is a warning paragraph.</p>
<blockquote class="blockquote">
<p class="mb-0">This is a blockquote.</p>
<footer class="blockquote-footer">John Doe</footer>
</blockquote>
<ul class="list-unstyled">
<li>List item 1</li>
<li>List item 2</li>
<li>List item 3</li>
</ul>
</div>
<!--Import Bootstrap JavaScript-->
<script
src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></
script>
</body>
</html>

OUTPUT:

P a g e 7 | 60
Reg No: ***
DEPARTMENT OF CSE

EX NO: 4 Validation Using JavaScript


DATE:

AIM:

To validate the registration, user login, user profile and payment by credit card
pages using java script.

ALGORITHM:

STEP 1 : Start program

STEP 2 : Create a registration form using html,javascript and create styles using css.

STEP 3 : Create a user login page using html and validate the form using javascript.

STEP 4 : Design a payment page using html and the same.

STEP 5 : For successful login, direct the login page to ayment


page.

STEP 6 : Get user credentials and validate the account.

STEP 5 : Stop the program.

P a g e 8 | 60
Reg No: ***
DEPARTMENT OF CSE
registration.html

<!DOCTYPE html>
<html>
<head>
<script>
var re_id=/^\w{5,12}$/
var re_pwd=/^\w{8,12}$/
var re_name=/^[a-zA-Z.]+$/
var re_email=/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/
var re_pin=/^\d{6,6}$/

function isChecked(x)
{
var flag=false;
for(var i=0;i<x.length;i++)
if(x[i].checked)
{
flag=true;
break;
}
return flag;
}

function formValidation()
{
if(!re_id.test(document.frm.userid.value))
{
alert("ID can contain alphabet,digit,_ and must be between 5
and 12");
document.frm.userid.focus();
return false;
}
else if(!re_pwd.test(document.frm.passid.value))
{
alert("password must be:\n-between 8 and 12");
document.frm.passid.focus();
return false;
}
else if(!re_name.test(document.frm.username.value))
{
alert("name must contain alphabet and .");
document.frm.username.focus();
return false;
}
else if(!(document.frm.dob.value!=""))

P a g e 9 | 60
Reg No: ***
DEPARTMENT OF CSE
{
alert("dob cannot be empty.");
document.frm.dob.focus();
return false;
}
else if(document.frm.country.value=="default")
{
alert("select any country");
document.frm.country.focus();
return false;
}
else if(!re_pin.test(document.frm.zip.value))
{
alert("pin code must contain 6 digits");
document.frm.zip.focus();
return false;
}

else if(!re_email.test(document.frm.email.value))
{
alert("email is empty or not valid");
document.frm.email.focus();
return false;
}

else if(!isChecked(document.frm.interest))
{
alert("select your area of interest");
document.frm.interest[0].focus();
return false;
}

else
return true;

</script>
</head>
<body>
<pre>
<h1>Registration Form</h1>
<form name='frm' onSubmit="return formValidation()" action="login.html">
User id :<input type="text" name="userid" maxlength=12 required autofocus/>

Password :<input type="password" name="passid" maxlength=12 />


P a g e 10 | 60
Reg No: ***
DEPARTMENT OF CSE

Name :<input type="text" name="username" />

DOB :<input type="date" name="dob"/>

Country :<select name="country">


<option value="default" selected>(Please select a country)</option>
<option value="AF">Australia</option>
<option value="AL">Canada</option>
<option value="DZ">India</option>
<option value="AD">USA</option>
</select>

ZIP Code :<input type="text" maxlength=6 name="zip" />

Email :<input type="text" name="email" size="50"/>

Sex :<input type="radio" name="sex" value="Male" checked />Male <input


type="radio" name="sex" value="Female" />Female

Interested in :<input type="checkbox" name="interest" value="sports"/>sports<input


type="checkbox" name="interest" value="music" />music

<input type="submit"/><input type="reset"/>


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

login.html

<!DocType html>
<html>
<head>
<script>
function authenticate()
{
var name=document.getElementById("log");
var pwd=document.getElementById("pwd");

var users=["ram","radha","guna"];
var passwords=["sita","krishna","secret"];

if(users.indexOf(name.value)==-1)

P a g e 11 | 60
Reg No: ***
DEPARTMENT OF CSE
{
alert("Invalid user name... try again...");
name.select();
return false;
}

else if(passwords[users.indexOf(name.value)]!=pwd.value)
{
alert("Invalid password... try again...");
pwd.select();
return false;
}
else

return true;
}
</script>
</head>
<body style="line-height:12pt;">
<div style="position:absolute;
border:34px ridge red;
left:520px;
top:150px;
padding:20px;
background:gold;">
<center>
<form action="payment.html" onSubmit="return authenticate()">
User Name :<input id="log" type="text" required autofocus/><br/><br/>
Password:<input id="pwd" type="password" required/><br/><br/>
<br/>
<input type="submit"><input type="reset">
</form>
</center>
</div>
</body>
</html>

payment.html

<!doctype html>
<html>
P a g e 12 | 60
Reg No: ***
DEPARTMENT OF CSE
<head>
<script>
var re_card=/^\d{12}$/
var re_cvv=/^\d{3}$/

function validate()
{
var c=document.getElementById("card");
var n=document.getElementById("name");
var e=document.getElementById("exdate");
var cvv=document.getElementById("cvv");
if (!re_card.test(c.value))
{
alert("Card Number should be 12 digit number...");
c.select();
return false;
}
else if(n.value=="")
{
alert("name should not be empty...");
n.focus();
return false;

}
else if(e.value=="")
{
alert("expired name should not be empty...");
e.focus();
return false;

}
else if (!re_cvv.test(cvv.value))
{
alert("Cvv should be 3 digit number...");
cvv.select();
return false;
}

else
{
alert("thank you for purchasing with us...");
window.close();
return true;
P a g e 13 | 60
Reg No: ***
DEPARTMENT OF CSE
}

</script>
</head>
<body style="font:bold italic 32px/12px arial narrow;color:white;">
<form name="myform" onSubmit="return validate()">
<center>
<pre style="position:absolute;
border:34px outset gold;
left:420px;
top:130px;
padding:20px;
background:url('indianrupee.jpg');">

CARD NO <input id="card" type="text" required maxlength=12 autofocus /><br/>

NAME <input id="name" type="text" name="name"/><br/>

EXPIRY DATE <input type="month" id="exdate" /><br/>

CVV <input id="cvv" type="text" maxlength=3/>

<input type="submit"/>
</pre>
</center>
</form>
</body>
</html>

Output :

registration.html login.html

P a g e 14 | 60
Reg No: ***
DEPARTMENT OF CSE

Payment.html

EX NO: 5 INVOKING SERVLET FROM HTML FORM

DATE:

AIM:
To write a HTML program for invoking the Servlet.

ALGORITHM:

Step 1: Start the program.


Step 2: Create the Servlet Program which Stores all values entered in the form.
Step 3: Display all the Information Received from the HTML Form.
Step 4: Declare the HTML structure for the program.
Step 5: Define the Action in the Form which will be invoked when the Form is
submitted.
Step 6: Define the Text Boxes and Text Button for the Form to get the Values.

P a g e 15 | 60
Reg No: ***
DEPARTMENT OF CSE
Step 7: Create the separate directory(base directory)for your application inside
of webapps directory save your html file in it.
Step 8: Create WEB-INF directory and save the web.xml file in it.
Step 9: Declare the necessary servlet mapping elements in web.xml file.
Step 10: Create the classes folder in WEB-INF directory and save servlet class
in it.
Step 11: Start the tomcat server and deploy this application.

PROGRAMS:
sayhello.java

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class sayhello extends GenericServlet{@Override
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException {
// TODO Auto-generated method stub
PrintWriter out=res.getWriter();
String name=req.getParameter("usr-name");
out.println("<h1> Welcome"+name+"</h1>");
}}

web.xml

<?xml version="1.0" encoding="UTF-8"?>


<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID"
version="3.0">
<display-name>simpleserv</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
P a g e 16 | 60
Reg No: ***
DEPARTMENT OF CSE
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>sayhello</servlet-name>
<servlet-class>package-name.sayhello</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>sayhello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>

P a g e 17 | 60
Reg No: ***
DEPARTMENT OF CSE
Invokeserv.html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form name="form1" method="post"
action="http://localhost:8080/package-name/hello">
Name : <input type="text" name="usr-name">
<input type="submit" value="submit">
</form>
</body>
</html>

OUTPUT:

P a g e 18 | 60
Reg No: ***
DEPARTMENT OF CSE

EX NO: 6 SESSION TRACKING USING HIDDEN FORM FIELDS

DATE:

AIM:
To write a java program for session tracking using hidden form field method.

ALGORITHM:

Step 1: Create the two servlet classes (FirstServlet, SecondServlet) for session
management.
Step 2: Create the index.html file to get user detail and to call FirstServlet class.
Step 3: Create response html file using form element and add user name as id
in hidden field of form element.
Step 4: Using second html file call SecondServlet class and identify the user
using name parameter.
Step 5: Create the response html file using SecondServlet and add same name
id as hidden field.
Step 6: Repeat this process for all pages in web applicaion.
Step 7: Create the directory structure and save the files in the required place.
Step 8: Start the tomcat server and deploy the application.

P a g e 19 | 60
Reg No: ***
DEPARTMENT OF CSE
Hide.html
<form action="http://localhost:8080/hiddenfields/s1">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>

Serv1.java
import java.io.PrintWriter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class serv1 extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response)
{
try{

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

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

//creating form that have invisible textfield


out.print("<form action='s2'>");
out.print("<input type='hidden' name='uname' value='"+n+"'>");
out.print("<input type='submit' value='go'>");
out.print("<br> User Name is Tracked From HTML");
out.print("</form>");
out.close();
}catch(Exception e){System.out.println(e);}
}
}

Serv2.java
import java.io.PrintWriter;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class serv2 extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response)
{
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
P a g e 20 | 60
Reg No: ***
DEPARTMENT OF CSE

//Getting the value from the hidden field


String n=request.getParameter("uname");
out.print("<br> <h1>User Name tracked Using Hidden Form Field</h1>");
out.print("<br><h3>Hello "+n+"</h3>");

out.close();
}catch(Exception e){System.out.println(e);}
}
}

Web.xml

<servlet>
<servlet-name>servlet1</servlet-name>
<servlet-class>hiddenfields.serv1</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>servlet1</servlet-name>
<url-pattern>/s1</url-pattern>
</servlet-mapping>

<servlet>
<servlet-name>servlet2</servlet-name>
<servlet-class>hiddenfields.serv2</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>servlet2</servlet-name>
<url-pattern>/s2</url-pattern>
</servlet-mapping>

OUTPUT:

P a g e 21 | 60
Reg No: ***
DEPARTMENT OF CSE

P a g e 22 | 60
Reg No: ***
DEPARTMENT OF CSE
EX NO: 7 SESSION TRACKING FOR HIT COUNT
DATE

AIM:
To create the java program to find out webpage hit counts using session
tracking.

ALGORITHM:

Step 1: Create the hits class extending HttpServlet class.


Step 2: Create the session object by calling getSession() method on request
object.
Step 3: Set the access count attribute value to 0 for first request.
Step 4: Increase the accesscount value for each client request separately.
Step 5: Display the pagecount to user by creating reponse HTML file in servlet
program.
Step 6: Start the Tomcat server and deploy the application.

P a g e 23 | 60
Reg No: ***
DEPARTMENT OF CSE
hits.java :
package hitcount;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class hits extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException
{
HttpSession session = request.getSession(true);
Date createTime = new Date(session.getCreationTime());
Date lastAccessTime =
new Date(session.getLastAccessedTime());
String title = "Session tracking. Hit count Example";
Integer visitCount = new Integer(0);
String visitCountKey = new String("visitCount");
String userIDKey = new String("userID");
String userID = new String("ABCD");
if (session.isNew()){
//title = "Welcome to my website";
session.setAttribute(userIDKey, userID);
} else {
visitCount = (Integer)session.getAttribute(visitCountKey);
visitCount = visitCount + 1;
userID = (String)session.getAttribute(userIDKey); }
session.setAttribute(visitCountKey, visitCount);
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\n";
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor=\"#f0f0f0\">\n" +
"<h1 align=\"center\">" + title + "</h1>\n" +
"<h2 align=\"center\">Session Infomation</h2>\n" +
"<table border=\"1\" align=\"center\">\n" +
"<tr bgcolor=\"#949494\">\n" +
" <th>Session info</th><th>value</th></tr>\n" +
"<tr>\n" +
P a g e 24 | 60
Reg No: ***
DEPARTMENT OF CSE
" <td>id</td>\n" +
" <td>" + session.getId() + "</td></tr>\n" +
"<tr>\n" +
" <td>Creation Time</td>\n" +
" <td>" + createTime +
" </td></tr>\n" +
"<tr>\n" +
" <td>Time of Last Access</td>\n" +
" <td>" + lastAccessTime +
" </td></tr>\n" +
"<tr>\n" +
" <td>User ID</td>\n" +
" <td>" + userID +
" </td></tr>\n" +
"<tr>\n" +
" <td>Number of visits</td>\n" +
" <td>" + visitCount + "</td></tr>\n" +
"</table>\n" +
"</body></html>");} }
web.xml
<servlet>
<servlet-name>tracks</servlet-name>
<servlet-class>hitcount.hits</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>tracks</servlet-name>
<url-pattern>/count</url-pattern>
</servlet-mapping>

OUTPUT:

P a g e 25 | 60
Reg No: ***
DEPARTMENT OF CSE
EX NO: 8 ONLINE EXAMINATION USING THREE-TIER APPLICATION

DATE:

AIM:
To write a Java Program to Create a Three Tire application for Online
Examination Using Java Servlets and Database.

ALGORITHM:

Step 1: Start the Program.


Step 2: Declare the HTML structure for the program.
Step 3: Create a DataBase in mysql to Store the Values entered in Form.
Step 4: Create DSN connection for the DataBase.
Step 4: Get the Values from the Form.
Step 5: Store the Values in the DataBase.
Step 6: Retrieve and Display the Values.
Step 7: Stop the program.

P a g e 26 | 60
Reg No: ***
DEPARTMENT OF CSE

/ * Steps to Compile & Execute the Servlet Program.


Exercise: Write programs in Java to create three-tier applications using servlets for
conducting on-line examination for displaying student mark list. Assume that student
information is available in a database which has been stored in a database server.

1. Create database in MYSql


 Open MySql
 Password: tiger
 Step1: Create database Students;
 Step2:Use Students;
 Step3: Create table student(sid int(11),Name1 varchar(25),Total int(11));

2. Type the HTML program(online.html) and servlet


program(StudentServlet.java).

3. open command prompt - set java path.

4. set classpath=F:/JSDK2.0/src;%classpath%;

5. Compile the program.

6. copy the StudentServlet.classfile of the source program into


F:\Apache Software Foundation\Tomcat 7.0\webapps\examples\WEB-INF\
classes

6. open web.xml [open with notepad] from F:\Apache Software Foundation\


Tomcat7.0\webapps\examples\WEB-INF

7. type the following statements near to the <servlet> tag which are already
available in web.xml.

<servlet>
<servlet-name>StudentServlet</servlet-name>
<servlet-class>StudentServlet</servlet-class>
</servlet>

8. type the following statements near to the <servlet - mapping> tag which are
already available in web.xml.

<servlet-mapping>
<servlet-name>StudentServlet</servlet-name>
<url-pattern>/servlets/servlet/StudentServlet</url-pattern>
</servlet-mapping>

9. start - tomcat server which is available from F:\Apache Software Foundation\


Tomcat 7.0\bin\Tomcat7
P a g e 27 | 60
Reg No: ***
DEPARTMENT OF CSE

10. open your HTML file in Firefox.


Online.html

<html>
<head>
<title>Database Test</title></head>
<body><center>
<h1>Online Examination</h1>
</center>
<form action="http://localhost:8080/examples/servlets/servlet/StudentServlet3"
method="POST">
<div align="left"><br></div>
<b>Student Number:</b><input type="text" name="sid">
<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 todestination</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>

StudentServlet3.java

import java.io.*;
P a g e 28 | 60
Reg No: ***
DEPARTMENT OF CSE
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class StudentServlet3 extends HttpServlet
{
String message, sid, 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 ServletException,IOException
{
try
{
Class.forName("com.mysql.jdbc.Driver");
connect=DriverManager.getConnection("jdbc:mysql://localhost:3306/
students","root","pani");
message="Thank you for participating in online Exam";
}
catch(ClassNotFoundException cnfex)
{ cnfex.printStackTrace(); }

catch(SQLException sqlex)
{ sqlex.printStackTrace(); }

catch(Exception excp)
{ excp.printStackTrace(); }
sid=request.getParameter("sid");
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 VALUES("+sid +",'" +Name+"',"+Total
+")";
int result=stmt.executeUpdate(query);
stmt.close();
}
P a g e 29 | 60
Reg No: ***
DEPARTMENT OF CSE
catch(SQLException ex)
{}
response.setContentType("text/html");
PrintWriter out=response.getWriter();
out.println("<html>");
out.println("<body bgcolor=cyan>");
out.println("<center>");
out.println("<h1>"+message+"</h1>\n");
out.println("<h3>Yours results stored in ourdatabase</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>"+"sid"+"</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;
P a g e 30 | 60
Reg No: ***
DEPARTMENT OF CSE
}

OUTPUT:

P a g e 31 | 60
Reg No: ***
DEPARTMENT OF CSE

EX NO: 9 Shopping Cart Using Servlet and Cookies


DATE:

AIM:
To validate the user login, user profile and payment by credit card using html
and java servlets.

ALGORITHM:
Step 1: Start the designing of the program with an HTML and then proceed
to design of a java servlets.
Step 2: Start html tag first. In the head tag the function profile (f1, f2) declare
that describes the status of those users logged in successfully.
Step 3: In the body tag, describe the background colors to be used by using
bgcolor.
Step 4: Three forms are used in developing the Web page.
Step 5: The first form will receive the username and password, on submit these
data i.e., username & password are send to servlet for processing the information. If
these values are valid then the program displays logged in successful. This form is
preceded by marquee that scroll to either to left or right as specified.
Step 6: Second form contains one text field, one password field and one text
area. This form gives the details of the user that will be displayed in text field.
Step 7: Third form contains the 2 text-field and one password field. This is
useful to pay by credit card.
Step 8: To design a servlet import java packages, like servlet etc.
Step 9: Create a class UserInfo that extend properties of HttpServlet. The
doPost method present in this class takes HttpServletRequest and
HttpServletResponse as parameters.
Step 10: Set the MIME type to text/html. For any servlet the default MIME
type is text/plain.
Step 11: An instance out for PrintWriter is created, which is initialized by using
getWriter method.

P a g e 32 | 60
Reg No: ***
DEPARTMENT OF CSE
Step 12: Strings user and password are created, which takes values sent by the
user.
Step 13: Strings ua,pa,ub,pb contains the information of five users which is
stored under the xml document.
Step 14: Values present in user password are verified with either ua, pa or ub,
pb. If these are correct then display login successful message else login invalid
message.
Step 15: To successfully execute this application an xml file is also to be
created that should contain user details. User details are mentioned with in init-param
tags.
Step 16: Place the class file and xml file under the WEB-INF directory then
deploy under Tomcat.
Step 1: Create Servlet Program
 Open eclipse IDE tool. Then select “FILENEW Web Dynamic Project”
 Type project name: shopping. Then click next button followed by next button.
 Then in the third screen select “generate web.xml deployment descriptor”
checkbox then click “Finish” button
 In the project explorer shown left side, right click on project named “shopping”
and select newclass. Then type name: LoginServlet and click Finish button
 Type the following code in LoginServlet.java

P a g e 33 | 60
Reg No: ***
DEPARTMENT OF CSE
LoginServlet.java
package shopping;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class LoginServlet extends HttpServlet
{
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws
ServletException,IOException
{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
String usr=req.getParameter("User");
String pwd=req.getParameter("password");
String card=req.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 cookie1=new Cookie("CurrentUser",usr);
Cookie cookie2=new Cookie("CreditCard",card);
res.addCookie(cookie1);
res.addCookie(cookie2);
out.println("<h2>Welcome "+usr+"</h2><hr>");
out.println("<h2>Select the book you would like to purchase<h2><hr>");
out.println("<form action='LoginSuccess'>");
out.println("<input type=radio name='book' checked
value='Let us C'/>Let us C<br>");
out.println("<input type=radio name='book'
value='Exploring C'/>Exploring C<br>");
out.println("<input type=radio name='book'
value='Mastering C'/>Mastering C<br>");
out.println("<input type=submit value='purchase'><hr>");

}
}
if(flag==true)
{
out.println("<h4>Invalid user name or password or card number
,please try again by clicking following link</h4>");
P a g e 34 | 60
Reg No: ***
DEPARTMENT OF CSE
out.println("<a href='loginform.html'>"+"LoginForm.html");
}
}
}

 In the project explorer shown left side, right click on project named “shopping”
and select newclass. Then type name: LoginSuccess and click Finish button
 Type the following code in LoginSuccess.java

LoginSuccess.java
package shopping;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class LoginSuccess extends HttpServlet
{
protected void doGet(HttpServletRequest req,HttpServletResponse res) throws
ServletException,IOException
{
Cookie[] mycookie=req.getCookies();
res.setContentType("text/html");
PrintWriter out=res.getWriter();
String book=req.getParameter("book");
out.print("<h2>welcome "+mycookie[0].getValue()+"</h2><hr>");
out.print("<h3>Thank you for purchasing book:"+book+"</h3><hr>");
out.print("<h3>Rs.250 debited from credit card: "+mycookie[1].getValue());
out.close();
}
}

 right click on WebContent of project named “shopping” and select newhtml


file. Then type name: loginform.html and click Finish button
 Type the following code in loginform.html

Loginform.html
<!DOCTYPE html>
<html>
<head>
<body>
<pre>
<form action="http://localhost:8088/shopping/LoginServlet" method="post">
Enter username:
<input type="text" value="" name="User">

enter password:
<input type="password" value="" name="password">
P a g e 35 | 60
Reg No: ***
DEPARTMENT OF CSE

enter card ID:


<input type="text" value="" name="CardID">

<input type="submit" value="login">


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

 Copy servlet-api.jar from F:\apache-tomcat-7.0.70\lib


 In project explorer, expand WebContentWEB-INF, right click on lib and
select paste from popup menu
 In project explorer, right click on WebContentWEB-INFweb.xml and
select open withtext editor
 Then add the following code before </web-app> tag in the web.xml file:

<servlet>
<init-param>
<param-name>usernames</param-name>
<param-value>panimalar,arun,bala</param-value>
</init-param>
<init-param>
<param-name>passwords</param-name>
<param-value>panimalar,arun,bala</param-value>
</init-param>
<init-param>
<param-name>cardIDs</param-name>
<param-value>111111,222222,333333</param-value>
</init-param>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>shopping.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>

<servlet>
<servlet-name>LoginSuccess</servlet-name>
<servlet-class>shopping.LoginSuccess</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginSuccess</servlet-name>
<url-pattern>/LoginSuccess</url-pattern>
</servlet-mapping>

P a g e 36 | 60
Reg No: ***
DEPARTMENT OF CSE
 Right click on LoginServlet.java select run asrun on server and follow the step

OUTPUT:
 Open browser and type the following URL address:
http://localhost:8081/Shopping/Loginform.html

P a g e 37 | 60
Reg No: ***
DEPARTMENT OF CSE
EX NO: 10 Book Catalogue Using JSP and MYSQL
DATE:

AIM:
To validate the user login, user profile and payment by credit card by using
HTML and JSP.

ALGORITHM:
Step 1: Start the Eclipse IDE.
Step 2: Create a Database using mysql named bookdetail.
Step 3: Create 2 JSP files namely borrowbook.jsp and storebook.jsp.
Step 4: In borrowbook.jsp create a connection to database and get the
input values from the user.
Step 5: In another JSP file named storebook.jsp, it stores the information
gathered from the user into database.
Step 6: Retreive and Display the values in database.
Step 7: Stop the program.

P a g e 38 | 60
Reg No: ***
DEPARTMENT OF CSE
Step 1. Create database in MYSql
 To Open MySql client select the following:
o Click start”All Programs”MySQL “MySQL Server 5.0”
“MySQL Command Line Client”
o This will open MySQL client screen, in that type
Password: tiger
 In the MySQL client, execute the following commands:

Step 2: Create JSP Program


 Open eclipse IDE tool. Then select “FILENEW Web Dynamic Project”
 Type project name: library. Then click next button followed by next button.
 Then in the third screen select “generate web.xml deployment descriptor”
checkbox then click “Finish” button
 In the project explorer shown left side, right click on WebContent under project
“library” and select newjsp file. Then type name:borrowbook.jsp and click
Finish button
 Type the following code in borrowbook.jsp

SOURCE CODE:

Borrowbook.jsp
<%@ page language="java" %>
<%@ page import="java.sql.*" %>
<%@ page import="java.io.*" %>
<%@ page import="javax.servlet.*" %>
<%@ page import="javax.servlet.http.*" %>

<!DOCTYPE html>
<html>
<body>
<form action="storeborrow.jsp" method="post">
<pre>
student number :<input type="text" name="sno" />
Student name :<input type="text" name="sname" />

P a g e 39 | 60
Reg No: ***
DEPARTMENT OF CSE
book id :<select name="bookid">

<% try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/students","root","tiger");

Statement stmt=con.createStatement();
String query="select * from bookdetail";
ResultSet rs=stmt.executeQuery(query);
while(rs.next()){
%>
<option value="<%=rs.getString(1)%>">
<%=rs.getString(2)%>
</option>
<%}%>
</select>
<%
rs.close();
stmt.close();
con.close();

}catch(Exception e)
{
out.println(e.toString());
}
%>
<input type="submit" value="borrow book"/></pre>
</form>
</body>
</html>

 In the project explorer shown left side, right click on WebContent under project
“library” and select newjsp file. Then type name:storeborrow.jsp and click
Finish button
 Type the following code in storeborrow.jsp

SOURCE CODE:

storeborrow.jsp
<%@ page language="java" %>
<%@ page import="java.sql.*" %>
<%@ page import="java.io.*" %>

<!DOCTYPE html>
<html>
P a g e 40 | 60
Reg No: ***
DEPARTMENT OF CSE
<body>
<% try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/students","root","tiger");

Statement stmt=con.createStatement();
String sno=request.getParameter("sno");
String sname=request.getParameter("sname");
String bookid=request.getParameter("bookid");
String query="insert into borrowbook
values("+sno+",'"+sname+"',"+bookid+")";
int result =stmt.executeUpdate(query);
if(result==1){
%>
<hr/>
<h1> the following query executed successfully</h1>
<hr/>
<%=query%>
<hr/>
<a href="borrowbook.jsp">go back to borrow book screen</a>
<%
}
else
{
%>
<hr/>
<h1> Insertion failed</h1>
<hr/>
<%
}
stmt.close();
con.close();

}catch(Exception e)
{
out.println(e.toString());
}
%>
</body>
</html>
 Copy servlet-api.jar from F:\apache-tomcat-7.0.70\lib
 In project explorer, expand WebContentWEB-INF, right click on lib and
select paste from popup menu
 Similarly copy “mysql-connector-java-5.1.34.jar”, then right click on lib and
select paste from popup menu
P a g e 41 | 60
Reg No: ***
DEPARTMENT OF CSE
 Right click on storeborrow.jsp select run asrun on server and follow the step
and copy the URL address

OUTPUT:
 Open browser and type the following URL address:
http://localhost:8088/library/borrowbook.jsp

AFTER CLICKING borrow book button, the output:

P a g e 42 | 60
Reg No: ***
DEPARTMENT OF CSE
EX NO: 11 Retrieving Information from XML Document
DATE:

AIM:
To write a javascript program to parse the given XML document and retrieve
data.

ALGORITHM:
Step 1: Start the program.
Step 2: Store the required information of each employee in an XML
document.
Step 3: Create a HTML file that accepts an employee ID as input from a text
field from the user.
Step 4: Write javascript code to read all the data in the XML file using the
XMLHttpRequest object.
Step 5: Find the information related to given input employee number.
Step 6: Display the result on the web browser if the inforamtion was found.
Step 7: Stop the program.

P a g e 43 | 60
Reg No: ***
DEPARTMENT OF CSE
XML Document:
emp.xml
<?xml version="1.0" encoding="UTF-8"?>
<EMPLOYEES>
<EMPLOYEE>
<ID>1000 </ID>
<NAME>ABC</NAME>
<DESIG>MANAGER</DESIG>
</EMPLOYEE>

<EMPLOYEE>
<ID>1001</ID>
<NAME>DEF</NAME>
<DESIG>ASST MANAGER</DESIG>
</EMPLOYEE>

<EMPLOYEE>
<ID>1002</ID>
<NAME>GHI </NAME>
<DESIG> GENERAL MANAGER</DESIG>
</EMPLOYEE>

<EMPLOYEE>
<ID>1003</ID>
<NAME>JKL</NAME>
<DESIG>MANAGER</DESIG>
</EMPLOYEE>
</EMPLOYEES>

Web Server:

prg3.html
<html>
<head>
<style>
table, th, td {
border: 1px solid black;
border-collapse:collapse;
}
th, td {
padding: 5px;
}
</style>
</head>
<body>

P a g e 44 | 60
Reg No: ***
DEPARTMENT OF CSE
<h3> Retreiving information from XML Database</h3>
User ID : <input type="text" id="uid"> </input>
<button onclick="test()"> Submit </button>
<script>
function test()
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","emp.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;

var tmp1;
tmp1= parseInt(document.getElementById('uid').value);
document.writeln(tmp1+"<table>");

document.write("<tr><th>Id</th><th>Name</th><th>Designation</th></
tr>");
var x=xmlDoc.getElementsByTagName("EMPLOYEE");
for (i=0;i<x.length;i++)
{
var tmp=parseInt(x[i].getElementsByTagName("ID")[0]
.childNodes[0].nodeValue);
if(tmp==tmp1)
{
document.write("<tr><td>");
document.write(x[i].getElementsByTagName("ID")[0]
.childNodes[0].nodeValue);
document.write("</td><td>");
document.write(x[i].getElementsByTagName("NAME")[0]
.childNodes[0].nodeValue);
document.write("</td><td>");
document.write(x[i].getElementsByTagName("DESIG")[0]
.childNodes[0].nodeValue);
document.write("</td></tr>");
}//if
}//for
document.write("</table>");
}
</script>
</body>
P a g e 45 | 60
Reg No: ***
DEPARTMENT OF CSE
</html>

OUTPUT:

Retreiving information from XML Database

User ID : Submit

1001
Id Name Designation
1001 KARTHICK MANAGER

P a g e 46 | 60
Reg No: ***
DEPARTMENT OF CSE
EX NO: 12 Form Validation and storing data in database Using PHP
DATE:

AIM:
To validate the form using PHP regular expression and stores a data into
database.
ALGORITHM:
Step 1: Start the program.
Step 2: Create a database named student.
Step 3: Start both Apache and MySql Service and click Admin button of
MYSQL.
Step 4: Create Server Side Program using PHP.
Step 5: The PHP program will validate based on the given regular
expression.
Step 6: Values are stored in the database.
Step 7: Stop the program.

P a g e 47 | 60
Reg No: ***
DEPARTMENT OF CSE
SOURCE CODE:

Step 1. Create database in MYSql


 Click start  all programs  XAMPPXAMPP Control Panel you will get
following screen

 In that Start both Apache and MySql Service and click Admin button of MySQL,
which will bring the following screen:

 In that click New to create new database and type name = student and click
create button
 Select student database on left pane and click SQL tab and type the following
code as shown in the following screen:

P a g e 48 | 60
Reg No: ***
DEPARTMENT OF CSE

Table creation syntax:


CREATE TABLE student(
id INT(6) AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
regno VARCHAR(50) NOT NULL,
email VARCHAR(50) NOT NULL
)
 Then click Go to create table named Student

Step2: Create Server Side Program using PHP


 Create folder called demo in the following path:
“C:\xampp\htdocs”
 In that create the following PHP file:

SOURCE CODE:

RegisterStudent.php

<!DocType html>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<h2>Student Registration</h2>

<?php

$nameErr = $emailErr = $regnoErr = "";


$name = $email = $regno = "";

P a g e 49 | 60
Reg No: ***
DEPARTMENT OF CSE
$error = 0;

if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$name = $_POST["name"];
$email = $_POST["email"];
$regno = $_POST["regno"];

if (empty(trim($name)))
{
$nameErr = "Name field should not be empty";
$error = 1;
}
elseif(!preg_match("/^([a-zA-Z' ]+)$/",$name))
{
$nameErr = "Name contain invalid characters";
$error = 1;
}
if (!preg_match("/^[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+\.[a-zA-Z.]{2,5}$/",
$email))
{
$emailErr = "Invalid Email";
$error = 1;
}
if (!preg_match("/^[0-9]{12}$/", $regno))
{
$regnoErr = "Reg No must contain 12 digits";
$error = 1;
}
if($error==0)
{
$servername = "localhost:3306"; //specify the port no. for mysql
$database = "student";
$username = "root";
$password = "";
$conn = mysqli_connect($servername, $username, $password,
$database);
if (!$conn)
die("Connection failed: " . mysqli_connect_error());
$sql = "INSERT INTO Student (name, regno, email) VALUES
('$name', '$regno','$email')";
if (mysqli_query($conn, $sql))
echo "New record created successfully";
else
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
mysqli_close($conn);
}
P a g e 50 | 60
Reg No: ***
DEPARTMENT OF CSE
}
?>
<pre>
<form method = "post">
Name:
<input type = "text" name = "name">
<span class = "error">* <?php echo $nameErr;?></span>
E-mail:
<input type = "text" name = "email" size=40>
<span class = "error">* <?php echo $emailErr;?></span>
Register Number(12 digits):
<input type = "text" name = "regno">
<span class = "error">* <?php echo $regnoErr;?></span>
<input type = "submit">
</form>
</body>
</html>

OUTPUT:
 Open browser and type the following URL address:
http://localhost/demo/RegisterStudent.php

Screen shot after filling form:

Screen shot after submitting the form:

P a g e 51 | 60
Reg No: ***
DEPARTMENT OF CSE

Record stored in the in the database after submitting form:

Note - If Apache runs on any port other than 80, for eg if it runs on port 81, then
URL will be
http://localhost:81/demo/RegisterStudent.php
http://localhost:81/phpmyadmin

P a g e 52 | 60
Reg No: ***
DEPARTMENT OF CSE
EX.NO: 13 Web Services for User opinion and Analysis
DATE:

AIM:
To implement the program for the web services for getting user opinion and
analysis.

ALGORITHM:

Step1: Start the Eclipse IDE


Step 2: Create a File named as Index.jsp
Step 3: Create another file named as Survey.jsp
Step 4: Write the code for the selection of various Products,
such as product1, product2, product 3 in the form of radio buttons.
Step 5: Create a file as web.xml which declares which urls are existing.
Step 6: Create 2 java files named ProductAnalysisService.java
ProductSalesPrediction.java .
Step 7: It is used for getting the user opinion and analysis about various products
Step 8: Now the product opinion is got and feedback gets submitted.
Step 9: Stop.

P a g e 53 | 60
Reg No: ***
DEPARTMENT OF CSE
Index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Product Sales Analysis</title>
</head>
<body bgcolor="#AABBCC" >
<form method="post" action="/ProductSales/Survey.jsp">
<div align="center" >
<hr>
<br><center><b> Welcome to Product Sales Analytics</b></center><br>
<hr>
<br><center>Login</center>
<table border="0">
<tr><td>
<center>UserName <input size="20" maxlength="20" name="password"
type="text" value="" style="width: 166px; height: 33px; "> </center>
</td></tr>
<tr><td>
<center>Password <input size="20" maxlength="20" name="password"
type="password" value="" style="width: 166px; height: 33px; "></center>
</td></tr>
<tr><td>
<center> <input type="submit" value= "Sign In" style="cue: "/> </center>
</td></tr>
</table>
<br>
</div>
</form>
</body>
</html>

Survey.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Product Survey</title>
P a g e 54 | 60
Reg No: ***
DEPARTMENT OF CSE
</head>
<body bgcolor="#AABBCC" >
<form method="post" action="/ProductSales/rest/prediction">
<div> <hr> <br> <center>
<b> Welcome to Product Survey</b>
</center>
<br>
<hr>
<table border="0" cellspacing="100%" align="left" style="width: 1282px;
height: 176px; ">
<tr> <td>Product Name ? <br>
<input type="radio" name="product" value="Product1" checked>
Product1<br>
<input type="radio" name="product" value="Product2"> Product2<br>
<input type="radio" name="product" value="Product3"> Product3<br>
</td> </tr> <tr >
<td>How often you use this product ? <br>
<input type="radio" name="use" value="1" checked> Strongly Dislike the
product<br>
<input type="radio" name="use" value="2"> Dislike the product.<br>
<input type="radio" name="use" value="3"> May Use the product.<br>
<input type="radio" name="use" value="4"> Like using the product.<br>
<input type="radio" name="use" value="5"> Use it every day. <br>
</td> </tr> <tr>
<td width="t">Will you buy this product ?
<br> <input type="radio" name="buy" value="1" checked> Will never
buy<br>
<input type="radio" name="buy" value="2"> May not Buy<br>
<input type="radio" name="buy" value="3"> May Buy
Occasionally <br> <input type="radio" name="buy"
value="4">
Will Buy.<br> <input type="radio" name="buy" value="5"> Strongly Buy the
product <br> </td> </tr> <tr> <td> <center>
<input type="submit" value="Submit Feedback" style="cue:" />
</center> </td> </tr> </table> <br>
</div> </form> </body> </html>

web.xml

<web-app id="WebApp_ID" version="2.4"


xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>productsales</display-name>
<servlet>
<servlet-name>jersey-serlvet</servlet-name>
P a g e 55 | 60
Reg No: ***
DEPARTMENT OF CSE
<servlet-class>
com.sun.jersey.spi.container.servlet.ServletContainer
</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>demo.product.analysis</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>jersey-serlvet</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>

ProductAnalysisService.java

package demo.product.analysis;
import java.util.*;
import javax.ws.rs.*;
import javax.ws.rs.core.Response;
@Path("/analysis")
public class ProductAnalysisService {
@GET
public Response getProductAnalysis() {
String productFeedback = "";
for (Entry<String, ArrayList<Integer>> mapEntry :
ProductSalesPrediction.getOpinionMap().entrySet()) {
int productValue = 0;
ArrayList<Integer> currentList = mapEntry.getValue();
for(Integer score : currentList) productValue += score.intValue();
int customerScore = 0;
if(currentList.size() != 0) customerScore = (productValue / currentList.size());
productFeedback += "Customer rating for product " + mapEntry.getKey() + "
is "+ customerScore +"% \n<br>";
}
return Response.status(200).entity(productFeedback).build();
}
}

ProductSalesPrediction.java

import java.io.IOException;
import java.util.*;
import javax.servlet.ServletException;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
P a g e 56 | 60
Reg No: ***
DEPARTMENT OF CSE

@Path("/prediction")
public class ProductSalesPrediction {

private static ProductSalesPrediction prodInstance = null;

private static ArrayList<Integer> opinionList = new ArrayList<Integer>();


private static Map<String, ArrayList<Integer>> opinionMap = new
HashMap<String, ArrayList<Integer>>();

public static ArrayList<Integer> getOpinionList() {


return opinionList;
}

public static Map<String, ArrayList<Integer>> getOpinionMap() {


return opinionMap;
}

@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public void getMsg(@FormParam("product") String product,
@FormParam("buy") String buy, @FormParam("use") String use) throws
ServletException, IOException
{
String productName = product;
int useValue = Integer.parseInt(use);
int buyValue = Integer.parseInt(buy);
int opinionValue = (useValue+buyValue)/2 * 10;
ArrayList<Integer> opinionList1 = null;
if(opinionMap.containsKey(productName)) {
if(opinionMap.get(productName) == null) opinionList1 = new
ArrayList<Integer>();
else opinionList1 = opinionMap.get(productName);
} else {
opinionList1 = new ArrayList<Integer>();
opinionMap.put(productName, opinionList1);
}
opinionList1.add(opinionValue);
}

public static ProductSalesPrediction getSalesPrediction() {


if(prodInstance == null) prodInstance = new ProductSalesPrediction();
return prodInstance; }}
OUTPUT:

P a g e 57 | 60
Reg No: ***
DEPARTMENT OF CSE

Welcome to Product Survey

Product Name ?
Product1
Product2
Product3
How often you use this product ?
Strongly Dislike the product
Dislike the product.
May Use the product.
Like using the product.
Use it every day.
Will you buy this product ?
Will never buy
May not Buy
May Buy Occasionally
Will Buy.
Strongly Buy the product

http://localhost:8080/ProductSales/rest/analysis
Customer rating for product Product1 is 10%
Customer rating for product Product2 is 30%
Customer rating for product Product3 is 50%

P a g e 58 | 60
Reg No: ***
DEPARTMENT OF CSE
EX.NO: 14 Auto Complete Using AJAX
DATE:

AIM:
To implement autocomplete using AJAX in the provided code, you'll need to modify
the JavaScript part to interact with an endpoint that provides autocomplete suggestions
based on user input.

HTML Structure: Keep the HTML structure as it is. You have a button to trigger the
AJAX request and a div to display the dynamic content.

JavaScript Function: Modify the getContent() function to send a request to the server
to fetch autocomplete suggestions based on user input.

ALGORITHM:

1. When the user types something in an input field, you'll send an AJAX request
to the server with the typed text.
2. The server processes the request, performs a search based on the typed text,
and returns matching suggestions.
3. The client-side JavaScript receives these suggestions and displays them in a
dropdown below the input field.
4. When the user clicks on one of the suggestions, you update the input field with
the selected suggestion.

CODE:
<!DOCTYPE html>
<html>
<head>
<title>AJAX Program by Coders Forum</title>
<script>
let num = 1;

function getContent()
{
// Url for the request
let url = 'https://jsonplaceholder.typicode.com/todos/' + num;
num++;
if(num > 99) {
num = 1;
}
// Making our request
fetch(url, { method: 'GET' })
.then(Result => Result.json())
.then(string => {
// Printing our response
console.log(string);
// Printing our field of our response
console.log(`Title of our response : ${string.title}`);
P a g e 59 | 60
Reg No: ***
DEPARTMENT OF CSE

document.getElementById('dynamicContent').innerHTML =
string.title;
})
.catch(errorMsg => { console.log(errorMsg); });
}
</script>
</head>
<body>
<h1>V2.0</h1>
<button onclick="getContent()">Update</button>
<div id="dynamicContent">
<i>Default Content</i>
</div>
</body>
</html>

OUTPUT:

P a g e 60 | 60

You might also like