LAB on Internet Programming
LAB on Internet Programming
Greet.php
<?php
if (isset($_GET["fname"]) && isset($_GET["lname"])) {
$fname = htmlspecialchars($_GET["fname"]);
$lname = htmlspecialchars($_GET["lname"]);
// Creating full name by joining first and last name
$fullname = $fname . " " . $lname;
// Displaying a welcome message
echo "Hello, $fullname!
Welcome to our website.";
} else {
echo "Hi there! Welcome to our website.";
}
?>
OUTPUT :
INITIAL PAGE :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Javascript Ajax Post Demo</title>
<script>
function postComment() {
var request = new XMLHttpRequest();
request.open("POST", "conformation.php");
request.onreadystatechange = function () {
if (this.readyState === 4 && this.status === 200) {
document.getElementById("result").innerHTML = this.responseText;
}
};
var myForm = document.getElementById("myForm");
var formData = new FormData(myForm);
request.send(formData);
}
</script>
</head>
<body>
<form id="myForm">
<label>Name:</label>
<div><input type="text" name="name" /></div>
<br />
<label>Comment:</label>
<div><textarea name="comment"></textarea></div>
<p><button type="button" onclick="postComment()">Post Comment</button></p>
</form>
<div id="result">
<p>
Content of the result DIV box will be replaced by the server response
</p>
</div>
</body>
</html>
Confirmation.php
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = htmlspecialchars(trim($_POST["name"]));
$comment = htmlspecialchars(trim($_POST["comment"]));
// Check if form fields values are empty
if (!empty($name) && !empty($comment)) {
echo "<p>Hi, <b>$name</b>. Your comment has been received successfully.<p>";
echo "<p>Here's the comment that you've entered: <b>$comment</b></p>";
} else {
echo "<p>Please fill all the fields in the form!</p>";
}
} else {
echo "<p>Something went wrong. Please try again.</p>";
}
?>
OUTPUT:
Q-3. JSON with JavaScript
<html>
<head>
<title>JSON example</title>
<script language="javascript">
var object1 = { "language" : "Java", "author" : "herbert schildt" };
document.write("<h1>JSON with JavaScript example</h1>");
document.write("<br>");
document.write("<h3>Language = " + object1.language+"</h3>");
document.write("<h3>Author = " + object1.author+"</h3>");
var object2 = { "language" : "C++", "author" : "E-Balagurusamy" };
document.write("<br>");
document.write("<h3>Language = " + object2.language+"</h3>");
document.write("<h3>Author = " + object2.author+"</h3>");
document.write("<hr />");
document.write(object2.language + " programming language can be studied " + "from
book
written by " + object2.author);
document.write("<hr />");
</script>
</head>
<body></body>
</html>
OUTPUT:
Q-4. JSON with PHP
<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));
var_dump(json_decode($json, true));
?>
string schemaJson = @"{ 'description': 'A person', 'type':
'object', 'properties': { 'name': {'type':'string'}, 'hobbies': { 'type':
'array', 'items': {'type':'string'} } } }"; JsonSchema schema =
JsonSchema.Parse(schemaJson); JObject person = JObject.Parse(@"{ 'name':
'James', 'hobbies': ['.NET', 'Blogging', 'Reading', 'Xbox', 'LOLCATS'] }"); bool
valid = person.IsValid(schema); // true JSON with PHP
<?php
$arr = array('a' =>
1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
?>
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
public class JSON_Example7_1 {
public static void main(String[] args) {
String s="{\"name\":\"geeta\",\"salary\":600000.0,\"age\":27}";
Object obj=JSONValue.parse(s);
JSONObject = (JSONObject) obj;
String name = (String) jsonObject.get("name");
double salary = (Double) jsonObject.get("salary");
long age = (Long) jsonObject.get("age");
System.out.println(name+" "+salary+" "+age);
}
}
Q-6. JSON with Ajax
<!DOCTYPE html>
<html>
<head>
<title>AJAX Example</title>
<script>
function getWelcome() {
var ajaxRequest = new XMLHttpRequest();
ajaxRequest.open("GET", "data.json");
ajaxRequest.onreadystatechange = function () {
if (ajaxRequest.readyState == 4) {
//the request is completed, now check its status
if (ajaxRequest.status == 200) {
document.getElementById("welcome").innerHTML =
ajaxRequest.responseText;
} else {
console.log("Status error: " + ajaxRequest.status);
}
} else {
console.log("Ignored readyState: " + ajaxRequest.readyState);
}
};
ajaxRequest.send();
}
</script>
</head>
<body>
<button type="button" onclick="getWelcome()">Okay</button>
<p id="welcome"></p>
</body>
</html>
Q-7. A student will not be allowed to sit in exam if his/her attendance is less
than 75%.Take following input from user
Number of classes held Number of classes attended.
And print percentage of class attended Is student is allowed to sit in exam or
not. Modify the above question to allow student to sit if he/she has medical
cause. Ask user if he/she has medical cause or not ('Y'or 'N' ) and print
accordingly. Write JavaScript code.
<html>
<script>
function checkExamEligibility(
classesHeld,
classesAttended,
hasMedicalCause
){
const attendancePercentage = (classesAttended / classesHeld) * 100;
Q-8. Write JavaScript code that prompts the user to input a positive integer.
It should then print the multiplication table of that number.
<html>
<title>input Positive Number Multiplecation table</title>
<body>
<script type="text/javascript">
var num = parseInt(prompt("Enter an integer: "));
var range = parseInt(prompt("Enter a range: "));
for (let i = 1; i <= range; i++) {
var res = i * num;
document.write(num + " * " + i + " = " + res + "<br /> ");
}
</script>
</body>
</html>
Output:
Q-9. Write a program to Check Whether the Entered Year is Leap Year or not
(Hint: A leap year is one that is divisible by 400. Otherwise, a year that is
divisible by 4 but not by
100 is also a leap years. Other years are not leap years. For example, years
1912, 2000, and 1980 are leaps years, but 1835, 1999, and 1900 are not. )
<html>
<title>Leap Year</title>
<body>
<script type="text/javascript">
var year = parseInt(prompt('Enter an integer: '));
10. Write a JavaScript code using function without parameter and without returning
datatype type. Find the late charges applicable for not returning the book to the library on
time. Take input as fine per day and number of days. Total fine is the multiplication of fine
per day and number of days. Find the percentage of marks for 5 subjects. Take input as
marks for 5subjects and find the percentage.
<html>
<script>
function calculateLateCharges() {
const finePerDay = parseFloat(prompt("Enter the fine per day:"));
const numberOfDays = parseInt(prompt("Enter the number of days late:"));
const totalFine = finePerDay * numberOfDays;
document.write(
`Late charges for not returning the book on time: $${totalFine}`
);
}
function calculatePercentageOfMarks() {
let totalMarks = 0;
Output:
11. Write JavaScript code using function with parameter and with returning datatype to
implement the following operations. Find the total salary deducted. Take input as
number of days worked, number of leaves and pay per day. Find the total salary hike.Take
input as salary and percentage of raise received.
<!DOCTYPE html>
<html>
<head>
<title>Salary Deduction Calculator</title>
</head>
<body>
<p>
Find the total salary deducted. take input as number of days worked,
number of leaves and pay per day.
</p>
<script>
function calculateSalaryDeduction(daysWorked, leavesTaken, payPerDay) {
var totalSalary = daysWorked * payPerDay;
var deduction = leavesTaken * payPerDay;
var totalDeduction = totalSalary - deduction;
return totalDeduction;
}
var daysWorked = parseInt(prompt("Enter the number of days worked:"));
var leavesTaken = parseInt(prompt("Enter the number of leaves taken:"));
var payPerDay = parseFloat(prompt("Enter the pay per day:"));
OUTPUT:-
12. Create a JavaScript form for Student Registration to capture student
name, phone number and email and perform validation using Regular
Expression.
<html>
<head>
<script>
function ValidateCode() {
var name = document.forms["RegForm"]["Name"];
var email = document.forms["RegForm"]["EMail"];
var phone = document.forms["RegForm"]["Telephone"];
var what = document.forms["RegForm"]["Subject"];
var password = document.forms["RegForm"]["Password"];
var address = document.forms["RegForm"]["Address"];
if (name.value == "") {
window.alert("Please enter your name.");
name.focus();
return false;
}
if (address.value == "") {
window.alert("Please enter your address.");
address.focus();
return false;
}
if (email.value == "") {
window.alert("Please enter a valid e-mail address.");
email.focus();
return false;
}
if (email.value.indexOf("@", 0) < 0) {
window.alert("Please enter a valid e-mail address.");
email.focus();
return false;
}
if (email.value.indexOf(".", 0) < 0) {
window.alert("Please enter a valid e-mail address.");
email.focus();
return false;
}
if (phone.value == "") {
window.alert("Please enter your telephone number.");
phone.focus();
return false;
}
if (password.value == "") {
window.alert("Please enter your password");
password.focus();
return false;
}
if (what.selectedIndex < 1) {
alert("Please enter your course.");
what.focus();
return false;
}
return true;
}
</script>
<style>
ValidateCode {
margin-left: 70px;
font-weight: bold;
float: left;
clear: left;
width: 100px;
text-align: left;
margin-right: 10px;
font-family: sans-serif, bold, Arial, Helvetica;
font-size: 14px;
}
div {
box-sizing: border-box;
width: 100%;
border: 100px solid black;
float: left;
align-content: center;
align-items: center;
}
form {
margin: 0 auto;
width: 600px;
}
</style>
</head>
<body>
<h1 style="text-align: center">REGISTRATION FORM</h1>
<form
name="RegForm"
action="/submit.php"
onsubmit="return ValidateCode()"
method="post"
>
<p>Name: <input type="text" size="65" name="Name" /></p>
<br />
<p>Address: <input type="text" size="65" name="Address" /></p>
<br />
<p>E-mail Address: <input type="text" size="65" name="EMail" /></p>
<br />
<p>Password: <input type="text" size="65" name="Password" /></p>
<br />
<p>Telephone: <input type="text" size="65" name="Telephone" /></p>
<br />
<p>
SELECT YOUR COURSE
<select type="text" value="" name="Subject">
<option>BTECH</option>
<option>BBA</option>
<option>BCA</option>
<option>B.COM</option>
<option>ValidateCode</option>
</select>
</p>
<br /><br />
<p>Comments: <textarea cols="55" name="Comment"> </textarea></p>
<p>
<input type="submit" value="send" name="Submit" />
<input type="reset" value="Reset" name="Reset" />
</p>
</form>
</body>
</html>
Output:
importjava.sql.*;
importjava.util.Scanner;
publicclassJDBC_insert {
Scanners=newScanner(System.in);
System.out.println("Enter the book id :");
intbook_id=s.nextInt();
System.out.println("Data inserted.");
}
catch(SQLExceptionse)
{
System.out.println(se.getMessage());
}
finally
{
System.out.println("All resources released");
}
SQL
create table book(
book_id number,
book_name varchar2(30),
book_price number);
Output:
14. Write a Java JDBC Program to Insert the data into the Book table by using
the Prepared Statement Interface.
importjava.sql.*;
importjava.util.Scanner;
publicclassMyPreparedStmt {
Connectioncon=null;
PreparedStatementpstmt=null;
try
{
// load oracle driver
Class.forName("oracle.jdbc.driver.OracleDriver");
// connect using Thin driver
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","manag
er");
System.out.println("Connection established");
Scanners=newScanner(System.in);
System.out.println("Enter the book id : ");
intbook_id=s.nextInt();
System.out.println("Enter the book name : ");
Stringbook_name=s.next();
System.out.println("Enter the book price : ");
intbook_price=s.nextInt();
pstmt.setInt(1, book_id);
pstmt.setString(2, book_name);
pstmt.setInt(3, book_price);
pstmt.executeUpdate();
System.out.println("Data Inserted.");
}
catch(SQLExceptionse)
{
System.out.println(se.getMessage());
}
finally
{
System.out.println("All resources released");
}
}
Output:
15. Write a Java JDBC Program to Delete the data from the Book table by
using the Statement Interface.
importjava.sql.*;
importjava.util.Scanner;
publicclassJDBC_delete {
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","manag
er");
System.out.println("Connection established");
stmt=con.createStatement();
Scanners=newScanner(System.in);
System.out.println("Enter the Book id : ");
intbook_id=s.nextInt();
finally
{
System.out.println("All resources released");
}
}
}
Output:
16. Write a Java JDBC Program to Delete the data from the Book table by
using the Prepared Statement Interface.
importjava.sql.*;
importjava.util.Scanner;
publicclassPrepare_Delete {
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","manag
er");
System.out.println("Connection established");
pstmt=con.prepareStatement(delete);
pstmt.setInt(1, BOOK_id);
pstmt.executeUpdate();
System.out.println("Data Deleted.");
con.close();
pstmt.close();
}
catch(SQLExceptionse)
{
System.out.println(se.getMessage());
}
finally
{
System.out.println("All resources released");
}
Output:
17. Write a Java JDBC Program to Update the data from the Book table by
using the Statement Interface.
importjava.sql.*;
importjava.util.Scanner;
publicclassJDBC_update {
try
{
// load oracle driver
Class.forName("oracle.jdbc.driver.OracleDriver");
// connect using Thin driver
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","manag
er");
System.out.println("Connection established");
Scanners=newScanner(System.in);
System.out.println("Enter the Book Id: ");
intbook_id=s.nextInt();
con.close();
stmt.close();
}
catch(SQLExceptionse)
{
System.out.println(se.getMessage());
}
finally
{
System.out.println("All resources released");
}
}
Output:
18. Write a Java JDBC Program to Update the data from the Book table by
using the Prepared Statement Interface.
importjava.sql.*;
importjava.util.Scanner;
publicclassPrepareUpdate {
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","manag
er");
System.out.println("Connection established");
pstmt.setString(1,book_name);
pstmt.setInt(2, book_price);
pstmt.setInt(3, book_id);
pstmt.executeUpdate();
System.out.println("Data Updated.");
}
catch(SQLExceptionse)
{
System.out.println(se.getMessage());
}
finally
{
System.out.println("All resources released");
}
Output:
19. Write a Menu Driven program to perform Insert, Update and Delete by
using the Statement Interface.
1. Insert
2. Delete
3. Update
4. Exit
import java.sql.*;
import java.util.Scanner;
Class.forName("oracle.jdbc.driver.OracleDriver");
// connect using Thin driver
con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","manager");
System.out.println("Connection established");
}
catch(SQLException se)
{
System.out.println(se.getMessage());
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
switch(choice)
{
case 1:
try
{
System.out.println("Data inserted.");
}
catch(SQLException se)
{
System.out.println(se.getMessage());
}
break;
case 2 :
try
{
stmt = con.createStatement();
System.out.println("Enter the Book id : ");
int book_id = s.nextInt();
break;
case 3 :
try
{
System.out.println("Enter the Book Id of which you
want to update data");
int book_id = s.nextInt();
}
catch(SQLException se)
{
System.out.println(se.getMessage());
}
break ;
case 4: System.exit(0);
}
ja.closeConnection();
}
}
Output:
20. Write a Menu Driven program to perform Insert, Update and Delete by
using the Prepared Statement Interface.
1. Insert
2. Delete
3. Update
4. Exit
import java.sql.DriverManager;
import java.sql.* ;
import java.util.Scanner ;
public class JDBC_ALL {
int bid,bprice;
String bname;
switch(choice)
{
case 1:
try
{
// load oracle driver
Class.forName("oracle.jdbc.driver.OracleDriver");
// connect using Thin driver
con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","manager");
System.out.println("Connection established");
pstmt.setInt(1, book_id);
pstmt.setString(2, book_name);
pstmt.setInt(3, book_price);
pstmt.executeUpdate();
System.out.println("Data Inserted.");
}
catch(SQLException se)
{
System.out.println(se.getMessage());
}
break;
case 2:
try {
// load oracle driver
Class.forName("oracle.jdbc.driver.OracleDriver");
// connect using Thin driver
con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","manager");
System.out.println("Connection established");
String delete ="delete from BOOK where book_id=?";
pstmt = con.prepareStatement(delete);
pstmt.setInt(1, BOOK_id);
pstmt.executeUpdate();
System.out.println("Data Deleted.");
con.close();
pstmt.close();
}
catch (SQLException se) {
System.out.println(se.getMessage());
}
break;
case 3 :
try
{
// load oracle driver
Class.forName("oracle.jdbc.driver.OracleDriver");
// connect using Thin driver
con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","manager");
System.out.println("Connection established");
pstmt.setString(1,book_name);
pstmt.setInt(2, book_price);
pstmt.setInt(3, book_id);
pstmt.executeUpdate();
System.out.println("Data Updated.");
}
catch(SQLException se)
{
System.out.println(se.getMessage());
}
break;
case 4 :
try
{
String select = "Select * from BOOK";
pstmt = con.prepareStatement(select);
rs = pstmt.executeQuery(select);
while(rs.next())
{
System.out.println("Book Id :"+rs.getInt("bid"));
System.out.println("Book
Name :"+rs.getString("bname"));
System.out.println("Book Pages :"+rs.getInt("bpages"));
}
rs.close();
}
catch(SQLException se)
{
System.out.println(se.getMessage());
}
break;
case 5:
System.exit(0);
break;
}
ja.closeConnection();
}
}
Output:
21. Design an application using JSP and Servlet to insert the data in the Book
table.
JSP FILE :
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="InsertServelet" method="post">
Book ID :<input type="text" name="bid"><br/><br/>
Book Name :<input type="text" name="bname"><br/><br/>
Book Price :<input type="text" name="bprice"><br/><br/>
<input type="submit" value="Submit">
</form>
</body>
</html>
SERVELET CODE:
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;
import java.util.Scanner;
/**
* Servlet implementation class InsertServelet
*/
public class InsertServelet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public InsertServelet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
//response.getWriter().append("Served at:
").append(request.getContextPath());
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","manager");
System.out.println("Connection established");
pstmt.setInt(1, bid);
pstmt.setString(2, bname);
pstmt.setInt(3, bprice);
pstmt.executeUpdate();
System.out.println("Data Inserted.");
}
catch(SQLException se)
{
System.out.println(se.getMessage());
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}
Output:
22. Design an application using JSP and Servlet to delete the data
from the Book table.
JSP CODE:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="Delete" method="post">
<h1><b>ENTER THE ID OF THE BOOK WHICH YOU WANT TO DELETE</b></h1>
Book ID :<input type="text" name="bid"><br/><br/>
<input type="submit" value="DELETE">
</form>
</body>
</html>
SERVELET CODE:
import java.sql.*;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* Servlet implementation class Delete
*/
public class Delete extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public Delete() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
//response.getWriter().append("Served at:
").append(request.getContextPath());
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
pstmt = con.prepareStatement(delete);
pstmt.setInt(1, bid);
pstmt.executeUpdate();
System.out.println("Data Deleted.");
response.getWriter().append("Data Deleted Successfully");
con.close();
pstmt.close();
}
catch(SQLException se)
{
System.out.println(se.getMessage());
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
Output:
23. Design an application using JSP and Servlet to update the data from the
Book table.
JSP CODE :
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="Update" method="post">
<h1><b>ENTER THE ID OF THE BOOK WHICH YOU WANT TO UPDATE THE
DETAILS</b></h1><br/><br/>
Book ID :<input type="text" name="bid"><br/><br/>
New Book Name :<input type="text" name="bname"><br/><br/>
New Book Price :<input type="text" name="bprice"><br/><br/>
<input type="submit" value="Submit">
</form>
</body>
</html>
SERVELET CODE :
import java.sql.*;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* Servlet implementation class Update
*/
public class Update extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public Update() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at:
").append(request.getContextPath());
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
pstmt.setString(1,bname);
pstmt.setInt(2, bprice);
pstmt.setInt(3, bid);
pstmt.executeUpdate();
System.out.println("Data Updated.");
}
catch(SQLException se)
{
System.out.println(se.getMessage());
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}
Output:
24. Design an application using JSP and Servlet to display the data from the
Book table.
try {
// Establish database connection
Connection con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system",
"manager");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM BOOK");
while (rs.next()) {
%>
<tr>
<td><%= rs.getInt("BOOK_ID") %></td>
<td><%= rs.getString("BOOK_NAME") %></td>
<td><%= rs.getInt("BOOK_PRICE") %></td>
</tr>
<%
}
// Close the resources
rs.close();
stmt.close();
con.close();
} catch (SQLException e) {
out.println("Error: " + e.getMessage());
}
%>
</table>
</body>
</html>
Servlet.java
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
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("/DisplayBooksServlet")
public class DisplayBooksServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
rs.close();
stmt.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
request.getRequestDispatcher("displayBooks.jsp").forward(request, response);
}
}
Output:
25. Design an application using JSP and Servlet to insert, update, delete and
display the data from the Book table.
Prepare a file with the Title Page and Index Page
Title Page should contain your name, PRN Number, Division etc.
Servlet.java
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* Servlet implementation class BookServlet
*/
public class BookServlet2 extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public BookServlet2() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
// TODO Auto-generated method stub
//response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
// TODO Auto-generated method stub
//doGet(request, response);
pstmt.setInt(1, bid1);
pstmt.setString(2, bname);
pstmt.setInt(3, bpages1);
pstmt.executeUpdate();
String update = "update book1 set bname = ? , bpages = ? where bid =?";
pstmt = con.prepareStatement(update);
pstmt.setString(1, bname);
pstmt.setInt(2, bpages1);
pstmt.setInt(3, bid1);
pstmt.executeUpdate();
PrintWriter out = response.getWriter();
out.print("Updated the data");
} else if (action1.equals("Delete")) {
String bid = request.getParameter("bid");
int bid1 = Integer.parseInt(bid);
pstmt = con.prepareStatement(delete);
pstmt.setInt(1, bid1);
pstmt.executeUpdate();
out.print("<td>");
out.print(res.getInt("bpages"));
out.print("</td>");
out.print("</tr>");
}
out.print("</table>");
out.print("</body>");
out.print("</html>");
}
} catch (SQLException se) {
System.out.println(se.getMessage());
} catch (Exception se) {
System.out.println(se.getMessage());
}
}
}
Output:
-------------------------------------------------------------------------------------------------------------