0% found this document useful (0 votes)
10 views52 pages

Java Programs for Serialization and JDBC

Uploaded by

nallaberozgar09
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views52 pages

Java Programs for Serialization and JDBC

Uploaded by

nallaberozgar09
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Name:- Chhaya Bhandari Course/Semester:-MCA/2 nd Roll_No.

/Sec:-20/A
Rawat

Q12 Write a java program to demonstrate object serialization and


deserialization. Create a file [Link] and save state of an instance.

Code :

import [Link].*;

class Product implements Serializable


{ String name = "Redmi
12C"; int id = 101;
double price = 10000;
}

public class Qes1 {

public static void main(String[] args) throws Exception {

[Link]("Object Serialization");
Product prd = new Product();
FileOutputStream fs = new FileOutputStream("[Link]");
ObjectOutputStream obj = new ObjectOutputStream(fs);
[Link](
prd);

[Link]("Object De-
Serialization"); FileInputStream fis = new
FileInputStream("[Link]");
ObjectInputStream ois = new
ObjectInputStream(fis); Product p =
(Product)[Link]();
[Link]("product name is : "+ [Link] + " product price is :
"+[Link] );

}
}
Name:- Chhaya Bhandari Course/Semester:-MCA/2 nd Roll_No./Sec:-20/A
Rawat

Output :
Name:- Chhaya Bhandari Course/Semester:-MCA/2 nd Roll_No./Sec:-20/A
Rawat

Q13 Assume two files [Link] and [Link] with some content. Write a Java program to merge
the content of these files and write into third file [Link]

Code :
import [Link].*; public class Qes2 { public static void
main(String[] args) throws IOException {
FileReader fr1 = new FileReader("[Link]");
BufferedReader br1 = new BufferedReader(fr1);
FileReader fr2 = new FileReader("[Link]");
BufferedReader br2 = new BufferedReader(fr2);
PrintWriter pr = new
PrintWriter("[Link]"); String line =
[Link](); while (line != null) {
[Link](line); line = [Link]();
[Link]();
}
String line2 =
[Link](); while (line2
!= null) {
[Link](line2); line2 =
[Link]();
[Link]();
}
}
}
Name:- Chhaya Bhandari Course/Semester:-MCA/2 nd Roll_No./Sec:-20/A
Rawat

Output :
Name:- Chhaya Bhandari Course/Semester:-MCA/2 nd Roll_No./Sec:-20/A
Rawat

Q14 Create [Link] file. Write three-digit number starting from111 to 999. Now read
the [Link] file line by line and if the three digit number is palindrome then write that
number in the [Link] file. (Use PrintWriter and BufferedReader class and
create separate method to check whether a number is palindrome or not).

Code :

import [Link].*; public class Qes3 {


static boolean isPalindrome(int n) {
int reverseNum = 0; int
tempNum = n;

while (tempNum > 0) { int lastDigit


= tempNum % 10; reverseNum =
reverseNum * 10 + lastDigit; tempNum =
tempNum / 10;
}

if (n == reverseNum) {
return true;
} else {
return false;
}

}
Name:- Chhaya Bhandari Course/Semester:-MCA/2 nd Roll_No./Sec:-20/A
Rawat

public static void main(String[] args) throws IOException {


PrintWriter pr = new PrintWriter("[Link]");
for (int i = 111; i < 1000;
i++) { [Link](i);
[Link]();
}
FileReader fr = new FileReader("[Link]");
BufferedReader br = new BufferedReader(fr);
PrintWriter pd = new PrintWriter("[Link]");

String line = [Link]();


while (line != null) { int num =
[Link](line); if
(isPalindrome(num)) {
[Link](line);
[Link]();
}
line = [Link]();
}
}
}
Name:- Chhaya Bhandari Course/Semester:-MCA/2 nd Roll_No./Sec:-20/A
Rawat

Output :
Name:- Chhaya Bhandari Course/Semester:-MCA/2 nd Roll_No./Sec:-20/A
Rawat

Q15 Ask a user to enter a product price using Scanner class. If the price is less then 10 then
throw user define exception TooMinAmount and if the price is greater then 20 then throw
TooMaxAmount else print Collect your product.

Code : import
[Link];
class TooMinAmount extends Exception {
public TooMinAmount(String msg) {
super(msg);
}
}
class TooMaxAmount extends Exception {
public TooMaxAmount(String msg) {
super(msg);
}
}

public class Qes4 { public static void


main(String[] args) {
Scanner sc = new Scanner([Link]);

try {
[Link]("Enter the product price: ");
double price = [Link]();
if (price < 10) {
throw new TooMinAmount("Price is too low!");
} else if (price > 20) {
throw new TooMaxAmount("Price is too high!");
} else {
Name:- Chhaya Bhandari Course/Semester:-MCA/2 nd Roll_No./Sec:-20/A
Rawat

[Link]("Collect your product");


}
} catch (TooMinAmount e) {
[Link]([Link]());
} catch (TooMaxAmount e) {
[Link]([Link]());
}
}
}
Name:- Chhaya Bhandari Course/Semester:-MCA/2 nd Roll_No./Sec:-20/A
Rawat

Output:
Name:- Chhaya Bhandari Course/Semester:-MCA/2 nd Roll_No./Sec:-20/A
Rawat

Q16 . Assume Student table having following


fields roll , name ,fee
1. Write a JDBC program to insert record into Student table using Statement
interface 2 2. Write a JDBC program to insert multiple records using
PreparedStatement use Scanner class to enter records. Code :
import [Link].*; import [Link]; public class CreteDatabase {
public static void main(String[] args) throws ClassNotFoundException {
// [Link]("[Link]");
String DB_url = "jdbc:mysql://localhost:3306/product";
String user = "root";
String password = "root";
// statement interface
try{
Connection con = [Link](DB_url , user , password);
String qeury = "insert into student
values(101,'Atul',56750)"; Statement st =
[Link](); int n = [Link](qeury);
if(n != 0){
[Link]("data inserted succesfully");
}else{
[Link]("failed to insert data");
}
} catch (Exception e) {
[Link](); }
// prepared statement
try{
Connection con = [Link](DB_url , user , password);
String qeury = "insert into student values(?,?,?)";
PreparedStatement ps = [Link](qeury);
Name:- Chhaya Bhandari Course/Semester:-MCA/2 nd Roll_No./Sec:-20/A
Rawat

Scanner s = new Scanner([Link]);


Scanner st = new Scanner([Link]);
[Link]("enter number of products ");
int n = [Link]();
for(int i = 0 ; i<n ; i++){
[Link]("Enter student roll , name and fees");
int roll = [Link]();
String name = [Link]();
int fees = [Link]();
[Link](1, roll);
[Link](2, name);
[Link](3, fees);
[Link]();
}
[Link]("data inserted successfully");
} catch (Exception e) {
[Link]();
} }
}
Name:- Chhaya Bhandari Course/Semester:-MCA/2 nd Roll_No./Sec:-20/A
Rawat

Output :
Name:- Chhaya Bhandari Course/Semester:-MCA/2 nd Roll_No./Sec:-20/A
Rawat

Q17. Write a JDBC program to fetch data from Student


table [Link]() [Link]() [Link](); [Link](int
index);

Code :
import [Link]; import
[Link]; import
[Link]; import
[Link]; import
[Link]; public
class Find { public static void
main(String[] args) {
String url = "jdbc:mysql://localhost:3306/product";
String user = "root";
String password = "root";
try{
Connection con = [Link](url , user , password);
String sql = "select * from student";
Statement st = [Link]();
ResultSet rs = [Link](sql);
while ([Link]()) {
[Link]([Link](1) + " " + [Link](2) + " " + [Link](3)); }
}catch(Exception e){
[Link]();
}
}
}
Name:- Chhaya Bhandari Course/Semester:-MCA/2 nd Roll_No./Sec:-20/A
Rawat

Output :
Name:- Chhaya Bhandari Course/Semester:-MCA/2 nd Roll_No./Sec:-20/A
Rawat

Q18 Assume table Product having following fields


Product id
Product Name
Product price
Write a JDBC program to implement following functions
addRecord():- Ask user to enter the data and insert into
Product table fetchRecord():- To fetch asked record
deleteRecord():- To delete the asked record from the product table

Code :
import [Link].*; import [Link]; public class CRUD {
public static void insertData(Connection con) throws SQLException {
Scanner s = new Scanner([Link]);
Scanner st = new Scanner([Link]);
[Link]("Enter number of products to be inserted");
int n = [Link]();
String qeury = "insert into product values(?,?,?)";
PreparedStatement ps = [Link](qeury);
for (int i = 0; i < n; i++) {
[Link]("Enter the id , name , price of product : ");
int id = [Link]();
String name = [Link]();
int price = [Link]();
[Link](1, id);
[Link](2, name);
[Link](3, price);
[Link]();

}
[Link]("data inserted successfully ");
Name:- Chhaya Bhandari Course/Semester:-MCA/2 nd Roll_No./Sec:-20/A
Rawat

}
public static void showData(Connection con) throws SQLException{
String sql = "select * from product";
Statement st = [Link]();
ResultSet rs = [Link](sql);
[Link]("product details :");
while ([Link]()) {
[Link]([Link](1) + " " + [Link](2) +
" " + [Link](3));
}
}

public static void deleteData(Connection con) throws SQLException {


[Link]("Enter the id of product to delete");

Scanner s = new Scanner([Link]);


int id = [Link]();
String sql = "delete from product where id =" +
id; Statement st = [Link](); int
ans = [Link](sql);
if (ans !=0 ) {
[Link]("data deleted successfully");
}
}

public static void main(String[] args)throws SQLException {


String url = "jdbc:mysql://localhost:3306/product";
Name:- Chhaya Bhandari Course/Semester:-MCA/2 nd Roll_No./Sec:-20/A
Rawat

String user = "root";


String password = "root";
Connection con = [Link](url, user, password);
insertData(con);
showData(con);
deleteData(con);
}
}
Name:- Chhaya Bhandari Course/Semester:-MCA/2 nd Roll_No./Sec:-20/A
Rawat

Output :
Name:- Chhaya Bhandari Course/Semester:-MCA/2 nd Roll_No./Sec:-20/A
Rawat

Q19. Assume table Product having following fields


Product id , Product Name , Product price
Write a JDBC program to execute following operation using batch update .
Insert data , Update existing data , Delete data

Code :
import [Link]; import
[Link]; import
[Link]; import
[Link]; import
[Link]; import
[Link];

public class CRUDBATCH {

public static void main(String[] args) {


String url = "jdbc:mysql://localhost:3306/product";
String user = "root";
String password = "root";
String insert_sql = "insert into product values (?, ?, ?)";
String update_sql = "update product set name = ? where id = ?";
String delete_sql = "delete from product where id = ?";
try{
Connection con = [Link](url , user , password);
PreparedStatement insp = [Link](insert_sql);
PreparedStatement updp = [Link](update_sql);
PreparedStatement delp = [Link](delete_sql);
[Link](1,4 );
Name:- Chhaya Bhandari Course/Semester:-MCA/2 nd Roll_No./Sec:-20/A
Rawat

[Link](2,"pasta");
[Link](3,250);
[Link]();
[Link](1,5 );
[Link](2,"glas");
[Link](3, 25);
[Link]();\
[Link](1,2);
[Link](2,"Cat");
[Link]();

[Link](1,5);
[Link]();

[Link]();
// [Link]();
[Link]();

[Link]("batch operation successfull");


}catch(Exception e){
[Link]();
}
}
}
Name:- Chhaya Bhandari Course/Semester:-MCA/2 nd Roll_No./Sec:-20/A
Rawat

Output :
Name:- Chhaya Bhandari Course/Semester:-MCA/2 nd Roll_No./Sec:-20/A
Rawat

Q20. Write a JDBC program to demonstrate CallableStatement using IN and OUT


parameter

Code :

[Link]:

import [Link];
import [Link]; import
[Link]; import
[Link]; import
[Link]; import
[Link]; import
[Link]; import
[Link];
import [Link];

public class Callble {


public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/product";
String user = "root";
String password = "root";

try{
Connection con = [Link](url , user , password);

// Prepare the callable statement


String sql = "{call GetProductName(?, ?)}";
CallableStatement cs = [Link](sql);
[Link](1, 2);
[Link](1, [Link]);
[Link]();
String productName = [Link](1);
[Link]("Product Name: " + productName);

}catch(Exception e){
[Link]();
}
}
}

Database Stored Proceudre


Name:- Chhaya Bhandari Course/Semester:-MCA/2 nd Roll_No./Sec:-20/A
Rawat

DELIMITER //

CREATE PROCEDURE GetProductName(IN prod_id INT, OUT prod_name


VARCHAR(100))
BEGIN
SELECT product_name INTO prod_name
FROM Product
WHERE product_id = prod_id;
END //

DELIMITER ;
Name:- Chhaya Bhandari Course/Semester:-MCA/2 nd Roll_No./Sec:-20/A
Rawat

Output :
Name:- Chhaya Bhandari Course/Semester:-MCA/2 nd Roll_No./Sec:-20/A
Rawat

Q21. Create a dynamic web project to calculate factorial of a number (index,html,


FactServlet)

Code :
[Link]
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action ="fact" method="get" >
<input type="input" placeholder="Enter a number" name="n"/>
<input type="submit" value="find factorial" />
</form>
</body>
</html>

[Link] package [Link]; import


[Link]; import
[Link]; import
[Link]; import
[Link]; import
[Link];

import [Link]; import


[Link];
Name:- Chhaya Bhandari Course/Semester:-MCA/2 nd Roll_No./Sec:-20/A
Rawat

@WebServlet("/FactTest") public class


FactTest extends HttpServlet {

public void service(HttpServletRequest req, HttpServletResponse res) {


int num = [Link]([Link]("n"));
int f = 1;
while(num > 0) {
f = f*num;
num--;
}
PrintWriter out;
try {
out = [Link]();
[Link]("factorial of the number is : "+f);
}catch(IOException io)
{
[Link]();
}
}
}

[Link]
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="[Link]
xmlns="[Link]
xsi:schemaLocation="[Link]
Name:- Chhaya Bhandari Course/Semester:-MCA/2 nd Roll_No./Sec:-20/A
Rawat

[Link] id="WebApp_ID" version="3.1">


<servlet>
<servlet-name>factorial</servlet-name>
<servlet-class>[Link]</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>factorial</servlet-name>
<url-pattern>/fact</url-pattern>
</servlet-mapping>
</web-app>
Name:- Chhaya Bhandari Course/Semester:-MCA/2 nd Roll_No./Sec:-20/A
Rawat

Output :
Name:- Chhaya Bhandari Course/Semester:-MCA/2 nd Roll_No./Sec:-20/A
Rawat

Q22. Create a dynamic web project to add two numbers.

Code :

[Link]
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action ="sum" method="get" >
<input type="input" placeholder="Enter a first Number" name="n1"/>
<input type="input" placeholder="Enter a Second Number" name="n2"/>
<br/>
<input type="submit" value="find Sum" />
</form>
</body>
</html>

[Link] package
[Link]; import
[Link];
import [Link];
import
[Link]
let; import
Name:- Chhaya Bhandari Course/Semester:-MCA/2 nd Roll_No./Sec:-20/A
Rawat

[Link]
letRequest; import
[Link]
letResponse;

public class Sum extends HttpServlet {


public void service (HttpServletRequest req , HttpServletResponse res) {

int n1 = [Link]([Link]("n1"));
int n2 = [Link]([Link]("n2"));

int sum = n1 + n2; PrintWriter out;


try { out =
[Link]();
[Link]("sum of the two numbers are :"+sum);
}catch(IOException io) {
[Link]();
}
}
}

[Link]
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="[Link]
xmlns="[Link]
xsi:schemaLocation="[Link]
[Link] id="WebApp_ID" version="3.1">
<servlet>
<servlet-name>S</servlet-name>
Name:- Chhaya Bhandari Course/Semester:-MCA/2 nd Roll_No./Sec:-20/A
Rawat

<servlet-class>[Link]</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>S</servlet-name>
<url-pattern>/sum</url-pattern>
</servlet-mapping>
</web-app>
Name:- Chhaya Bhandari Course/Semester:-MCA/2 nd Roll_No./Sec:-20/A
Rawat

Output :
Name:- Chhaya Bhandari Course/Semester:-MCA/2 nd Roll_No./Sec:-20/A
Rawat

Q23. Create a dynamic web project to demonstrate RequestDispatcher

Code :

[Link]
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="dispatch" method="get">
<input type="input" name="num" palaceholder ="Enter a number" />
<input type="submit" value="submit" />
</form>
</body>
</html>

[Link]:
package [Link]; import
[Link]; import
[Link]; import
[Link]; import
[Link]; import
[Link];

public class Send extends HttpServlet {


public void service(HttpServletRequest req , HttpServletResponse res) throws IOException {
Name:- Chhaya Bhandari Course/Semester:-MCA/2 nd Roll_No./Sec:-20/A
Rawat

int n = [Link]([Link]("num"));
n++;
HttpSession s = [Link]();
[Link]("ck", n);
// url name not class
[Link]("send2");
}
}

[Link] :
package [Link]; import
[Link]; import
[Link]; import
[Link];

import [Link]; import


[Link]; import
[Link];

public class Send2 extends HttpServlet {

public void service(HttpServletRequest req , HttpServletResponse res) throws IOException {

HttpSession s = [Link]();
int n = (int)[Link]("ck");
n = n*10;
Name:- Chhaya Bhandari Course/Semester:-MCA/2 nd Roll_No./Sec:-20/A
Rawat

PrintWriter out = [Link]();


[Link]("Eg for request dispacter :" +n );
}
}

[Link] :
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="[Link]
xmlns="[Link]
xsi:schemaLocation="[Link]
[Link] id="WebApp_ID" version="3.1">

<servlet>
<servlet-name>dispatch</servlet-name>
<servlet-class>[Link]</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>dispatch</servlet-name>
<url-pattern>/dispatch</url-pattern>
</servlet-mapping>

<servlet>
<servlet-name>dispatch2</servlet-name>
<servlet-class>[Link].Send2</servlet-class>
</servlet>

<servlet-mapping>
Name:- Chhaya Bhandari Course/Semester:-MCA/2 nd Roll_No./Sec:-20/A
Rawat

<servlet-name>dispatch2</servlet-name>
<url-pattern>/send2</url-pattern>
</servlet-mapping>
Name:- Chhaya Bhandari Course/Semester:-MCA/2 nd Roll_No./Sec:-20/A
Rawat

Output :
Name:- Chhaya Bhandari Course/Semester:-MCA/2 nd Roll_No./Sec:-20/A
Rawat

Q24 . Create a dynamic web project to demonstrate Session management using Cookie

Code :

[Link]
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="cookie" method="get">
<input type="input" name="user" palaceholder ="Enter a username" />
<input type="submit" value="submit" />
</form>
</body>
</html>

[Link] : package [Link]; import


[Link]; import
[Link]; import
[Link]; import
[Link]; import
[Link]; import
[Link]; import
[Link]; public class
Cookie1 extends HttpServlet
{
Name:- Chhaya Bhandari Course/Semester:-MCA/2 nd Roll_No./Sec:-20/A
Rawat

public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException


{
int n=[Link]([Link]("n"));
n++;
//HttpSession session=[Link]();
//[Link]("test", n);
Cookie ck=new Cookie("key",n+"");
[Link](ck);

[Link]("next");
}
}

[Link]:
package [Link];

import [Link]; import


[Link]; import
[Link]; import
[Link]; import
[Link]; import
[Link];

import [Link]; public


class Cookie2 extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException
{
//HttpSession ss=[Link]();
Name:- Chhaya Bhandari Course/Semester:-MCA/2 nd Roll_No./Sec:-20/A
Rawat

//int n=(int)[Link]("test"); Cookie[]


ck=[Link]();
int n=0;
for(Cookie c: ck)
{
if([Link]().equals("key"))
{
n=[Link]([Link]());
}
}
n=n*n;
PrintWriter out=[Link]();

[Link]("value of cookies is : " +n);

}
Name:- Chhaya Bhandari Course/Semester:-MCA/2 nd Roll_No./Sec:-20/A
Rawat

Output :
Name:- Chhaya Bhandari Course/Semester:-MCA/2 nd Roll_No./Sec:-20/A
Rawat

Q25. Create a Login application using Servlet

Code :
[Link]:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="submit" method="post">
<input type="text" name="username" placeholder="enter name "><br>
<input type="password" name="password" placeholder= "Enter password"><br>
<button type="submit">Login</button>
</form>
</body>
</html>

[Link] :
package [Link]; import
[Link]; import
[Link]; import
[Link]; import
[Link]; import
[Link]; import
[Link];
Name:- Chhaya Bhandari Course/Semester:-MCA/2 nd Roll_No./Sec:-20/A
Rawat

@WebServlet("/login") public class Login extends HttpServlet {


public void doPost(HttpServletRequest req, HttpServletResponse res)
throws IOException {
String user= "hello";
String pass = "world";
String username = [Link]("username");
String password = [Link]("password"); if
([Link](username) && [Link](password)) {
[Link]().println("Login successfull ");
} else {
[Link]().println("Invalid username or password.");
}
}
}

[Link] :
<servlet>
<servlet-name>log</servlet-name>
<servlet-class>[Link]</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>log</servlet-name>
<url-pattern>/submit</url-pattern>
</servlet-mapping>
Name:- Chhaya Bhandari Course/Semester:-MCA/2 nd Roll_No./Sec:-20/A
Rawat

Output :
Name:- Chhaya Bhandari Course/Semester:-MCA/2 nd Roll_No./Sec:-20/A
Rawat

Q26. Create JSP page to calculate factorial of a number.

Code :
[Link]:
<%@ 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="[Link]" method="post">

<input type="number" id="number" name="number" placeholder="Enter a number" >


<button type="submit">Calculate</button>
</form>
</body>
</html>

[Link] :
<%@ page import="[Link].*,[Link].*" %>
<!DOCTYPE html>
<html>
<head>
<title>Factorial Result</title>
</head>
Name:- Chhaya Bhandari Course/Semester:-MCA/2 nd Roll_No./Sec:-20/A
Rawat

<body>
<h2>Factorial Result</h2>
<%
// Retrieve the number from the request String
numberStr = [Link]("number"); int
number = [Link](numberStr);
int factorial = 1; for(int i
= 1; i <= number; i++) {
factorial *= i;
}
%>
<p>The factorial of <%= number %> is <%= factorial %>.</p>
</body>
</html>

Output :
Name:- Chhaya Bhandari Course/Semester:-MCA/2 nd Roll_No./Sec:-20/A
Rawat
Name:- Chhaya Bhandari Course/Semester:-MCA/2 nd Roll_No./Sec:-20/A
Rawat

Q27. Create Dynamic Web project to demonstrate the use of Java Bean class using useBean
and setProperty tag in JSP pages.
Code :

[Link]
<%@ 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="[Link]" method="post">
<input type="number" name="number1" >
<input type="number" name="number2" >
<br>
<button type="submit">Add</button>
</form>
</body>
</html>

[Link]:
<%@ page import="[Link]" %>
<jsp:useBean id="numberBean" class="[Link]" scope="request" />
<jsp:setProperty property="*" name="numberBean" />

<!DOCTYPE html>
Name:- Chhaya Bhandari Course/Semester:-MCA/2 nd Roll_No./Sec:-20/A
Rawat

<html>
<head>
<title>Result</title>
</head>
<body>
<h2>Result</h2>
<%
int sum = [Link]();
%>
<p>The sum of <%= numberBean.getNumber1() %> and <%= numberBean.getNumber2() %>
is <%= sum %>.</p>
</body>
</html>

[Link] : package
[Link]; public class
NumberBean { private
int number1; private int
number2; private int
sum;

public int getNumber1() {


return number1;

public void setNumber1(int number1) {


this.number1 = number1;
}
Name:- Chhaya Bhandari Course/Semester:-MCA/2 nd Roll_No./Sec:-20/A
Rawat

public int getNumber2() {


return number2;
}

public void setNumber2(int number2) {


this.number2 = number2;
}

public int getSum() {


return number1 + number2;
}
}
Name:- Chhaya Bhandari Course/Semester:-MCA/2 nd Roll_No./Sec:-20/A
Rawat

Output :

Common questions

Powered by AI

In the dynamic web project, the `Sum` servlet handles HTTP GET requests where parameters `n1` and `n2` are received from the client's form submission. These parameters are accessed using `request.getParameter` and processed to calculate their sum. Servlets can handle both GET and POST methods, but in this case, processing is tailored for GET requests as indicated by the form method attribute without any differentiation within the service method .

The program uses the method `isPalindrome`, which checks if a number remains the same when reversed. The logic involves reverse computation by extracting digits using modulus (%) and rebuilding the number using division (/). This operation is encapsulated in a static boolean method, `isPalindrome(int n)`, which allows reuse for any numeric input, enhancing the modularity and usability of the code in various applications .

The program demonstrates object serialization and deserialization by creating a `Product` class that implements the `Serializable` interface, allowing its instances to be converted into a stream of bytes. A `Product` object is then serialized and stored in the file `notes.ser` using `ObjectOutputStream` and is later deserialized back into a `Product` object using `ObjectInputStream`. Implementing `Serializable` implies that all fields are serialized by default, except those marked as `transient` or `static` .

The `try-catch` block in the program captures and handles exceptions to provide specific error messages when a user-defined exception is thrown. If the entered price is less than 10 or greater than 20, the program throws `TooMinAmount` or `TooMaxAmount` exceptions, respectively. The `catch` blocks handle these exceptions by displaying a specific error message without terminating the program abruptly, thus ensuring robustness and clarity in user interaction .

BufferedReader is used to efficiently read text from the files `f1.txt` and `f2.txt`, while PrintWriter writes the merged content into `f3.txt`. The program reads each line from both input files using `BufferedReader` and writes it to the output file `f3.txt` using `PrintWriter`, allowing it to handle large files by processing line-by-line rather than loading everything into memory at once .

In JDBC batch operations, transactions ensure that either all operations are executed successfully, or none are, maintaining data integrity. While using batch updates, operations like insert, update, and delete are grouped so they can be executed as a single unit. This reduces number of database calls, minimizes overheads, and ensures atomicity because the database can roll back all changes if any statement fails, preventing partial updates .

The Java Bean in JSP is used to manage state by allowing properties of HTML form inputs to be mapped directly onto attributes or fields in a Java class (`NumberBean`). Using `<jsp:useBean>` and `<jsp:setProperty>` tags, the JSP engine creates an instance of the bean and initializes its properties with the data submitted through the form. This state management is convenient for operations like accessing form values across multiple JSP pages, without reducing the scope of the bean to the request or session scope, which defines its lifecycle .

The `web.xml` file maps URLs to specific servlet classes using `<servlet>` and `<servlet-mapping>` tags. Each servlet is identified by a unique `<servlet-name>`, which links to the `<servlet-class>`. For adding numbers, the form action 'sum' is mapped to the specific servlet class `Sum` using `<url-pattern>/sum</url-pattern>`. This configuration directs the web server to invoke the appropriate servlet when the defined URL pattern is requested, creating a clear routing mechanism for processing client requests in the application .

CallableStatement in JDBC is significant for executing stored procedures which can be more efficient than inline queries especially with complex logic. It allows handling both IN and OUT parameters, which simplifies invoking stored procedures and retrieving results. This capability is crucial for performance optimization and code maintenance, as complex logic encapsulated in stored procedures can be reused and centrally managed within the database itself, reducing application complexity .

Session objects in servlets enable stateful communication by maintaining user data across multiple requests. The program uses `HttpSession` to store attributes in one servlet and retrieve them in another. `RequestDispatcher` or `sendRedirect` is used for forwarding or redirecting requests, allowing data sharing amongst different servlet components within the same session context. This mechanism supports continuity and user session tracking throughout the interaction lifecycle, ensuring coherent state management .

You might also like