WT Lab Manual
WT Lab Manual
following:
1 Title of the book
2 Author name
3 Publisher Name
4 Editions
5 Price
Write a Document Type Definition (DTD) to validate the above XML file.
PROGRAM:
Ex1.xml
<?xml version="1.0" encoding="UTF-8"?>
<?DOCTYPE catalogue SYSTEM "book.dtd"?>
<catalogue>
<book>
<title>c</title>
<author>Balaguruswamy</author>
<isbn>1234</isbn>
<publisher>pearson</publisher>
<edition>4</edition>
<price>$50</price>
</book>
<book>
<title>c++</title>
<author>Balaguruswamy</author>
<isbn>123</isbn>
<publisher>pearson</publisher>
<edition>3</edition>
<price>$55</price>
</book>
<book>
<title>java</title>
<author>Brett spell</author>
<isbn>12</isbn>
<publisher>Apress</publisher>
<edition>2</edition>
<price>$45</price>
</book>
</catalogue>
Document Type Definition (DTD) to validate the above XML file
Dtd file: book.dtd
<!ELEMENT catalogue (book)*>
<!ELEMENT book (title,author,isbn,publisher,edition,price)>
<!ELEMENT title (#PCDATA)>
<!ELEMENT author (#PCDATA)>
<!ELEMENT isbn (#PCDATA)>
<!ELEMENT publisher (#PCDATA)>
<!ELEMENT edition (#PCDATA)>
<!ELEMENT price (#PCDATA)>
Output:
2. Write a PHP programs that uses arrays and functions in PHP.
Array in PHP
An array stores multiple values in one single variable
In PHP, there are three kinds of arrays:
o Numeric array
o Associative array
o Multidimensional array
Numeric Array in PHP
Numeric array is an array with a numeric index
Numeric Array Example
<html>
<body>
<?php
$flower_shop = array ("rose", "daisy","orchid");echo "Flowers:
".$flower_shop[0].",".$flower_shop[1].", ".$flower_shop[2]."";
?>
</body>
</html>
OUTPUT:
Flowers: rose, daisy, orchid
Associative array in PHP
Associative array is an array where each ID key is associated with a value
Associative array Example
<html>
<body>
<?php
$flower_shop = array ( "rose" => "5.00", "daisy" => "4.00", "orchid"
=> "2.00" );
// Display the array values
echo "rose costs" .$flower_shop['rose'].",daisy costs
".$flower_shop['daisy'].",and orchild
costs ".$flower_shop['orchild']."";
?>
</body>
</html>
OUTPUT:
rose costs 5.00,daisy costs 4.00,and orchild costs
Loop through an Associative Array
<html>
<body>
<?php
$flower_shop=array("rose"=>"5.00",
"daisy"=>"4.00","orchid"=>"2.00");
foreach($flower_shop as $x=>$x_value) {
echo "Flower=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>
</body>
</html>
OUTPUT:
Flower=rose, Value=5.00
Flower=daisy, Value=4.00
Flower=orchid, Value=2.00
OUTPUT:
4) Write a PHP program for display all students in CSE using mysql student table.
studentinfo.php
<?php
$user = 'root';
$password = 'root';
$database = 'info';
$servername='localhost:3306';
$mysqli = new mysqli($servername, $user,$password, $database);
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '. $mysqli->connect_error);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>CSE Student Details</title>
<style>
table {
margin: 0 auto;
font-size: large;
border: 1px solid black;
}
h1 {
text-align: center;
color: #006600;
font-size: xx-large;
font-family: 'Gill Sans', 'Gill Sans MT',
' Calibri', 'Trebuchet MS', 'sans-serif';
}
td {
background-color: #E4F5D4;
border: 1px solid black;
}
th,
td {
font-weight: bold;
border: 1px solid black;
padding: 10px;
text-align: center;
}
td {
font-weight: lighter;
}
</style>
</head>
<body>
<section>
<h1>CSE Department Student Information</h1>
<table>
<tr>
<th>Reg_No</th>
<th>FirstName</th>
<th>LastName</th>
<th>Gender</th>
<th>Email</th>
<th>Address</th>
<th>Phone_No</th>
</tr>
<!-- PHP CODE TO FETCH DATA FROM ROWS -->
<?php
// SQL query to select data from database
$sql = " SELECT * FROM studnetinfo where dept='CSE' ";
// LOOP TILL END OF DATA
if($result = $mysqli->query($sql)){
while ($rows = $result->fetch_assoc()){
?>
<tr>
<!-- FETCHING DATA FROM EACH ROW OF EVERY COLUMN -->
<td><?php echo $rows['Reg_No'];?></td>
<td><?php echo $rows['FirstName'];?></td>
<td><?php echo $rows['LastName'];?></td>
<td><?php echo $rows['Gender'];?></td>
<td><?php echo $rows['Email'];?></td>
<td><?php echo $rows['Address'];?></td>
<td><?php echo $rows['Phone_No'];?></td>
</tr>
<?php
}
}
?>
</table>
</section>
</body>
</html>
Database Creation:
Table Creation:
CREATE TABLE studentinfo( Reg_No int(12), FirstName varchar(30), LastName varchar(30),
Gender varchar(30), Email varchar(30), Dept varchar(30), Address varchar(50), Phone_No int(12));
Insert Data:
INSERT INTO `studnetinfo`(`Reg_No`, `FirstName`, `LastName`, `Gender`, `Email`, `Dept`, `Address`,
`Phone_No`) VALUES ('102','kiran','selva','[email protected]','Male','CSE','HYB','98623476')
Output:
5) Create a PHP page for login system using session.
Aim: To create a PHP page for login system using session.
<?php
ob_start();
session_start();
?>
<html lang = "en">
<head>
<link rel="stylesheet"
href=https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css >
<style>
body {
padding-top: 40px;
padding-bottom: 40px;
background-color: #ADABAB;
}
.form-signin {
max-width: 330px;
padding: 15px;
margin: 0 auto;
color: #017572;
}
.form-signin .form-signin-heading,
.form-signin .checkbox {
margin-bottom: 10px;
}
.form-signin .checkbox {
font-weight: normal;
}
.form-signin .form-control {
position: relative;
height: auto;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
padding: 10px;
font-size: 16px;
}
.form-signin .form-control:focus {
z-index: 2;
}
.form-signin input[type="email"] {
margin-bottom: -1px;
border-bottom-right-radius: 0;
border-bottom-left-radius: 0;
border-color:#017572;
}
.form-signin input[type="password"] {
margin-bottom: 10px;
border-top-left-radius: 0;
border-top-right-radius: 0;
border-color:#017572;
}
h2{
text-align: center;
color: #017572;
}
</style>
</head>
<body>
<h2>Enter Username and Password</h2>
<div class = "container form-signin">
<?php
$msg = '';
if (isset($_POST['login']) && !empty($_POST['username'])
&& !empty($_POST['password'])) {
if ($_POST['username'] == 'ram' &&
$_POST['password'] == 1234) {
$_SESSION['valid'] = true;
$_SESSION['timeout'] = time();
$_SESSION['username'] = 'ram';
OUTPUT:
7) Write a Node JS program to read and write file system
Aim: To write a Node JS program to read and write file system operation
Filename: Index.js
const fs=require('fs');
var data=readFileSync("data.txt");
console.log(data);
/*data.txt*/
hello node
Output:
<Buffer 68 65 6c 6c 6f 20 6e 6f 64 65>
Filename: Index.js
const fs=require('fs');
var data=readFileSync("data.txt").toString();
console.log(data);
/*data.txt*/
hello node
Output:
hello node
Read File
fs.readFile read any file asynchronously using a callback function as parameter.
Filename: Index.js
const fs=require('fs');
fs.readFile("data.txt",(err,data)=>{
if(err){
console.log("Error : ", err);
}
else{
console.log(data.toString());
}
})
/*data.txt*/
hello node
Output:
hello node
Write File
To write in a file, node js use writeFile / writeFileSync methods.
const fs=require('fs');
fs.writeFileSync('data.txt','Hello Node');
If data.txt file is missing in current directory, node js will create a new directory with same
name and then write. There is no need to create a file first and then write.
writeFileSync
To write in a file synchronously, node js used fs.writeFileSync method. The first parameter
is file name and second is text data.
Filename: Index.js
const fs=require("fs");
fs.writeFileSync('data.txt','Hello Node JS');
writeFile
To write in a file asynchronously, node js used fs.writeFile method. The first parameter is
file name and second is text data and third is callback to handle errors..
Filename: Index.js
const fs=require("fs");
fs.writeFile('data.txt',"hello Node",(err)=>{
if(err){
console.log(err)
}
})
Filename: Index.js
const fs=require('fs');
fs.appendFileSync('src/data.txt',"hello Node 1",'utf8',(err)=>{
if(err){
console.log(err)
}
});
fs.appendFileSync('src/data.txt',"hello Node 2",'utf8',(err)=>{
if(err){
console.log(err)
}
});
Output:
Hello Node 1
Hello Node 2
appendFile
appendFile method of fs append file synchronously.
Filename: Index.js
const fs=require('fs');
fs.appendFile('src/data.txt',"hello Node 1",'utf8',(err)=>{
if(err){
console.log(err)
}
});
fs.appendFile('src/data.txt',"hello Node 2",'utf8',(err)=>{
if(err){
console.log(err)
}
});
Output:
Hello Node 1
Hello Node 2
delete file
To delete files, node js use fs.unlink or fs.unlinkSync methods.
fs.unlinkSync
const fs=require('fs');
fs.unlinkSync('data.txt');
By using fs.unlinkSync without exception handling can create runtime errors. To handle this, use
fs.unlinkSync with exception handling
Filename: Index.js
const fs=require('fs');
try{
fs.unlinkSync('data.txt');
console.log('file deleted successfully');
}
catch(err){
console.log("Error",err);
}
fs.unlink
fs.unlink is a asynchronously method to delete file with two arguments. First is file name and
second is callback function.
Filename: Index.js
const fs=require('fs');
fs.unlink('data.txt',(err)=>{
if(err){
console.log('Error:', err);
}
else{
console.log('file deleted successfully');
}
})
Output:
file deleted successfully
8) Write a Node JS program to connect the MongoDB
Aim:
To perform CRUD Operation in MongoDB
Step 1
Connect your system with the internet and open the command prompt and then run
Command install mongodb --save
Step 2
Create a database in MongoDB using Node.js and VS Code. first, open VS Code and create a
folder where you want to make database program. and then open this folder in VS Code
Step 3
For performing any crud operation in MongoDB, you need a database and a collection. First.
create a database and then create a collection.
Step 4 - Create a database
Create a .js page(createdatabase.js) and now write the code:
createdatabase.js
var mongodb=require('mongodb');
var MongoClient=mongodb.MongoClient;
var url='mongodb://localhost:27017/';
MongoClient.connect(url,function(error, databases){// use for to connect to the datab
ases
if(error){
throw error;
}
var dbobject=databases.db('navigcollection');//use for create database
console.log("databases is created")
databases.close();
})
Compile
node createdb.js
Step 5 - Create collection in database
Create a .js file ("createcollection.js") and write code.
createcollection.js
var mongodb=require('mongodb');
var MongoClient=mongodb.MongoClient;
var url="mongodb://localhost:27017/"
MongoClient.connect(url,function(error,databases){
if(error){
throw error;
}
var dbase=databases.db("navigcollection");
dbase.createCollection("pract",function(error,response){
if(error){
throw error;
}
console.log("collection is created.....")
databases.close();
});
});
Compile
node createcollection.js
Step 6 - Insert record in database
insert.js"
var mongodb = require('mongodb');
var mongoClient = mongodb.MongoClient;
var url = "mongodb://localhost:27017/";
mongoClient.connect(url, function(err, databases) {
if (err)
{
throw err;
}
var nodetestDB = databases.db("navigcollection"); //here
var customersCollection = nodetestDB.collection("pract");
var customer = {_id:111, name:"Santosh Kumar" , address: "B-222, Sector19, NOIDA",
orderdata:"Arrow Shirt"};
customersCollection.insertOne(customer, function(error, response) {
if (error) {
throw error;
}
console.log("1 document inserted");
databases.close();
});
});
Compile
node insert.js
Now insert record into the collection, create again a js file ("insertmanydocu.js") and write
the code:
insertmanydocu.js
var mongodb=require('mongodb');
var MongoClient=mongodb.MongoClient;
var url='mongodb://localhost:27017/';
MongoClient.connect(url,function(error,databases){
if(error){
throw error;
}
var nodtst=databases.db("navigcollection");
var pract=[
{_id:11,name:"Chaman Gautam" , address: "Harvansh nagar Ghaziabad", orderdata:"J
eans"},
{_id:12,name:"Shivani" , address: "Harvansh nagar Ghaziabad", orderdata:"Jeans"},
{_id:13,name:"Menu" , address: "Harvansh nagar Ghaziabad", orderdata:"Top"},
{_id:14,name:"Brajbala" , address: "Harvansh nagar Ghaziabad", orderdata:"Dinig tab
le"},
{_id:15,name:"Ramsaran" , address: "Harvansh nagar Ghaziabad", orderdata:"Washin
g machine"},
{_id:16,name:"Dheeraj" , address: "Harvansh nagar Ghaziabad", orderdata:"Jeans"}
]
nodtst.collection('pract').insertMany(pract , function(error,response){
if(error){
throw error;
}
console.log("Numnber of document is inserted.........");
})
. })
Compile
node insertmanydocu.js
Step 7 - Find record from database
Find 1 record from collection
Now creata a .js page("find1docu.js") create a page and write the code:
var mongodb=require("mongodb");
var MongoClient=mongodb.MongoClient;
var url='mongodb://localhost:27017/';
MongoClient.connect(url, function(error, databases){
if(error){
throw error;
}
var nodtst = databases.db("navigcollection");
nodtst.collection("pract").findOne({name:'Shivani'}, function(err, result) {
if (err) throw err;
console.log("one record is find now....."+result.name + ", " + result.address + ", " +
result.orderdata);
databases.close();
})
})
Compile
node findonedocu.js
deletemany.js
var mongodb=require('mongodb');
var MongoClient=mongodb.MongoClient;
var url='mongodb://localhost:27017/';
MongoClient.connect(url,function(error,databases){
if(error)
{
throw error;
}
var nodtst=databases.db('navigcollection');
var deleteQuery={};
nodtst.collection('pract').deleteMany(deleteQuery,function(error,response){
if(error){
throw error;
}
console.log(response.result.n + "document(s) deleted successfully .....");
databases.close();
})
})
9) Write a servlet program which receives data from HTML forms and respond it. Create one
Servlet to retrieve “ServletContext Initialization Parameters “which you have given in the
web.xml file.
Login.html
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title> Login Page </title>
<style>
Body {
font-family: Calibri, Helvetica, sans-serif;
background-color: pink;
}
button {
background-color: #4CAF50;
width: 100%;
color: orange;
padding: 15px;
margin: 10px 0px;
border: none;
cursor: pointer;
}
form {
width: 25%;
border: 3px solid #f1f1f1;
}
input[type=text], input[type=password] {
width: 100%;
margin: 8px 0;
padding: 12px 20px;
display: inline-block;
border: 2px solid green;
box-sizing: border-box;
}
button:hover {
opacity: 0.7;
}
.cancelbtn {
width: auto;
padding: 10px 18px;
margin: 10px 5px;
}
.container {
padding: 25px;
background-color: lightblue;
}
</style>
</head>
<body>
<center> <h1> Login Form </h1>
<form action="ValidServ" method="post">
<div class="container">
<input type="text" placeholder="Enter Username" name="txtuser" required>
<input type="password" placeholder="Enter Password" name="txtpass" required>
<button type="submit">Login</button>
</div>
</form> </center>
</body>
</html>
ValidServ.java
import java.io.IOException;
import java.util.Enumeration;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public ValidServ() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see Servlet#init(ServletConfig)
*/
public void init(ServletConfig config) throws ServletException {
cfg = config;
}
login.java:
import java.io.*;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
public class login extends HttpServlet
{
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
String n=request.getParameter("uname");
String p=request.getParameter("pass");
PrintWriter out = response.getWriter();
Cookie nam1=new Cookie("user1","user1");
Cookie nam2=new Cookie("user2","user2");
Cookie nam3=new Cookie("user3","user3");
Cookie nam4=new Cookie("user4","user4");
Cookie pas1=new Cookie("pwd1","pwd1");
Cookie pas2=new Cookie("pwd2","pwd2");
Cookie pas3=new Cookie("pwd3","pwd3");
Cookie pas4=new Cookie("pwd4","pwd4");
int flag=0;
String nam[]={nam1.getValue(),nam2.getValue(),nam3.getValue(),nam4.getValue()};
String pas[]={pas1.getValue(),pas2.getValue(),pas3.getValue(),pas4.getValue()};
for(int i=0;i<4;i++)
{
if(nam[i].equals(n)&&pas[i].equals(p))
{
flag=1;
}
}
if(flag==1)
{
out.println("Wecome you "+n.toUpperCase());
}
else
{
out.println("You are not an authenticated user");
}
}
}
Web.xml:
<web-app>
<servlet>
<servlet-name>login</servlet-name>
<servlet-class>login</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/cookies</url-pattern>
</servlet-mapping>
</web-app>
Output:
11) Write a servlet that, on entry of a student roll no, displays the full details of that student
details (Using student table with roll no, Name, Address, date of birth, course fields).
Database Creation
index.html
<!DOCTYPE html>
<html>
<body>
<form action="Search" method="get">
Enter your Roll_No:<input type="text" name="t1"><br/>
<button type="submit">Search</button>
</form>
</body>
</html>
StudentSearch.java
import java.io.*;
import java.sql.*;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.*;
public class StudentSearch extends HttpServlet {
public void init()
{
try
{
Connection cn=DriverManager.getConnection("jdbc:mysql://localhost:3306/crud","root","root");
}
catch(Exception ce)
{
System.out.println("Error"+ce.getMessage());
}
}
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
resp.setContentType("text/html");
PrintWriter pw=resp.getWriter();
try
{
int rno=Integer.parseInt(req.getParameter("t1"));
String qry="select * from student where RollNo="+rno;
Statement st=cn.createStatement();
ResultSet rs=st.executeQuery(qry);
while(rs.next())
{
pw.print("Students Detail");
pw.print("<table border=1>");
pw.print("<tr>");
pw.print("<td>" + rs.getInt(1) + "</td>"); pw.print("<td>" + rs.getString(2) + "</td>");
pw.print("<td>" + rs.getString(3) + "</td>");
pw.print("<td>" + rs.getString(4) + "</td>");
pw.print("<td>" + rs.getString(5) + "</td>");
pw.print("</tr>");
pw.print("</table>");
} }
catch(Exception se){}
pw.close();
}}
web.xmlfile
<web-app>
<servlet>
<servlet-name>Search</servlet-name>
<servlet-class>StudentSearch</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Search</servlet-name>
<url-pattern>/Search</url-pattern>
</servlet-mapping>
</web-app>
Output:
12) Write JSP program to register a student using registration form using student table.
Registration.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>User Data</title>
</head>
<style>
div.ex {
text-align: right;
width: 300px;
padding: 10px;
border: 5px solid grey;
margin: 0px
}
</style>
<body>
<h1>Registration Form</h1>
<div class="ex">
<form action="RegistrationController" method="post">
<table style="with: 50%">
<tr>
<td>Full Name</td>
<td><input type="text" name="fullname"/></td>
</tr>
<tr>
<td>Username</td>
<td><input type="text" name="userName"/></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="pass"/></td>
</tr>
<tr>
<td>Address</td>
<td><input type="text" name="address"/></td>
</tr>
<tr>
<td>Age</td>
<td><input type="text" name="age"/></td>
</tr>
<tr>
<td>Qualification</td>
<td><input type="text" name="qual"/></td>
</tr>
<tr>
<td>Percentage</td>
<td><input type="text" name="percent"/></td>
</tr>
<tr>
<td>Year Passed</td>
<td><input type="text" name="yop"/></td>
</tr>
</table>
<input type="submit" value="register"/>
</form>
<br>
create a student table in test database before registering this form
<br> Syntax : <br>
<i>create table student(name varchar(100), userName varchar(100), pass varchar(100), addr
varchar(100), age int,
qual varchar(100), percent varchar(100), year varchar(100));</i>
</div>
</body>
</html>
RegistrationController.java
package com.candid;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/RegistrationController")
public class RegistrationController extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String name = request.getParameter("fullname");
String userName = request.getParameter("userName");
String pass = request.getParameter("pass");
String addr = request.getParameter("address");
String age = request.getParameter("age");
String qual = request.getParameter("qual");
String percent = request.getParameter("percent");
String year = request.getParameter("yop");
Screenshot 1
Screenshot 2
13) Write JSP program for authenticating user by his password using login form.
Login.html:
<html>
<body>
<table border="1" width="100%" height="100%">
<tr>
<td valign="top" align="center"><br/>
<form action="auth.jsp"><table>
<tr>
<td colspan="2" align="center"><b>Login Page</b></td>
</tr>
<tr>
<td colspan="2" align="center"><b> </td>
</tr>
<tr>
<td>User Name</td>
<td><input type="text" name="user"/></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="pwd"/></td>
</tr>
<tr>
<td> </td> <td> </td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="LogIN"/></td>
</tr>
</table>
</form>
` </td>
</tr>
</table>
</body>
</html>
Auth.jsp:
<%@page import="java.sql.*;"%>
<html> <head>
<title>
This is simple data base example in JSP</title>
</title>
</head>
<body bgcolor="yellow">
<%
String uname=request.getParameter("user");
String pwd=request.getParameter("pwd");
try
{
Connection
con=DriverManager.getConnection("jdbc:mysql://localhosr:3306/demo","root","root");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select name,password from personal where
name='"+uname+"' and password='"+pwd+"'");
if(rs.next())
{
out.println("Authorized person");
}
else
{
out.println("UnAuthorized person");
}
con.close();
}
catch(Exception e){out.println(""+e);}
%>
</body>
</html>
OUTPUT:
14) Create table to store the details of book(book name, price, quantity, amount) and extract
data from table and display all books using JSP and JDBC.
PROGRAM:
Retrieve.java:
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import java.io.*;
import java.util.*;
public class Retrieve extends HttpServlet
{
public void service(HttpServletRequest req,HttpServletResponse res) throws
ServletException,IOException
{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
try{
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/demo","root","root");
Statement s=con.createStatement();
ResultSet r=s.executeQuery("select * from cart");
out.println("<center> <table border=1>");
out.println("<thead> <th> Book name </th> <th> Price </th> <th> Quantity </th> <th> Amount
</th> </thead>");
while(r.next())
{
out.println("<tr> <td> "+r.getString(1)+"</td> ");
out.println("<td> "+r.getString(2)+"</td> ");
out.println("<td> "+r.getInt(3)+"</td> ");
out.println("<td> "+r.getString(4)+"</td> </tr>");
}
out.println("</table></center>");
con.close();
}
catch(SQLException sq)
{
out.println("sql exception"+sq);
}
catch(ClassNotFoundException cl)
{
out.println("class not found"+cl);
}
}
}
web.xml:
<web-app>
<servlet>
<servlet-name>set</servlet-name>
<servlet-class>Cartenter</servlet-class>
</servlet>
<servlet>
<servlet-name>display</servlet-name>
<servlet-class>Retrieve</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>set</servlet-name>
<url-pattern>/enterdata</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>display</servlet-name>
<url-pattern>/display1</url-pattern>
</servlet-mapping>
</web-app>
CREATE THE TABLE AND INSERT VALUES INTO THE TABLE:
OUTPUT: