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

Chhaya Java

Uploaded by

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

Chhaya Java

Uploaded by

nallaberozgar09
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

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 notes.ser and save state of an instance.

Code :

import java.io.*;

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 {

System.out.println("Object Serialization");
Product prd = new Product();
FileOutputStream fs = new FileOutputStream("notes.ser");
ObjectOutputStream obj = new ObjectOutputStream(fs);
obj.writeObject(
prd);

System.out.println("Object De-
Serialization"); FileInputStream fis = new
FileInputStream("notes.ser");
ObjectInputStream ois = new
ObjectInputStream(fis); Product p =
(Product)ois.readObject();
System.out.println("product name is : "+ p.name + " product price is :
"+p.price );

}
}
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 f1.txt and f2.txt with some content. Write a Java program to merge
the content of these files and write into third file f3.txt

Code :
import java.io.*; public class Qes2 { public static void
main(String[] args) throws IOException {
FileReader fr1 = new FileReader("f1.txt");
BufferedReader br1 = new BufferedReader(fr1);
FileReader fr2 = new FileReader("f2.txt");
BufferedReader br2 = new BufferedReader(fr2);
PrintWriter pr = new
PrintWriter("f3.txt"); String line =
br1.readLine(); while (line != null) {
pr.println(line); line = br1.readLine();
pr.flush();
}
String line2 =
br2.readLine(); while (line2
!= null) {
pr.println(line2); line2 =
br2.readLine();
pr.flush();
}
}
}
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 Number.txt file. Write three-digit number starting from111 to 999. Now read
the Number.txt file line by line and if the three digit number is palindrome then write that
number in the palindromeOnly.txt file. (Use PrintWriter and BufferedReader class and
create separate method to check whether a number is palindrome or not).

Code :

import java.io.*; 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("number.txt");
for (int i = 111; i < 1000;
i++) { pr.println(i);
pr.flush();
}
FileReader fr = new FileReader("number.txt");
BufferedReader br = new BufferedReader(fr);
PrintWriter pd = new PrintWriter("palindrome.txt");

String line = br.readLine();


while (line != null) { int num =
Integer.parseInt(line); if
(isPalindrome(num)) {
pd.println(line);
pd.flush();
}
line = br.readLine();
}
}
}
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
java.util.Scanner;
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(System.in);

try {
System.out.print("Enter the product price: ");
double price = sc.nextDouble();
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

System.out.println("Collect your product");


}
} catch (TooMinAmount e) {
System.out.println(e.getMessage());
} catch (TooMaxAmount e) {
System.out.println(e.getMessage());
}
}
}
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 java.sql.*; import java.util.Scanner; public class CreteDatabase {
public static void main(String[] args) throws ClassNotFoundException {
// Class.forName("com.mysql.cj.jdbcDriver");
String DB_url = "jdbc:mysql://localhost:3306/product";
String user = "root";
String password = "root";
// statement interface
try{
Connection con = DriverManager.getConnection(DB_url , user , password);
String qeury = "insert into student
values(101,'Atul',56750)"; Statement st =
con.createStatement(); int n = st.executeUpdate(qeury);
if(n != 0){
System.out.println("data inserted succesfully");
}else{
System.out.println("failed to insert data");
}
} catch (Exception e) {
e.printStackTrace(); }
// prepared statement
try{
Connection con = DriverManager.getConnection(DB_url , user , password);
String qeury = "insert into student values(?,?,?)";
PreparedStatement ps = con.prepareStatement(qeury);
Name:- Chhaya Bhandari Course/Semester:-MCA/2 nd Roll_No./Sec:-20/A
Rawat

Scanner s = new Scanner(System.in);


Scanner st = new Scanner(System.in);
System.out.println("enter number of products ");
int n = s.nextInt();
for(int i = 0 ; i<n ; i++){
System.out.println("Enter student roll , name and fees");
int roll = s.nextInt();
String name = st.nextLine();
int fees = s.nextInt();
ps.setInt(1, roll);
ps.setString(2, name);
ps.setInt(3, fees);
ps.executeUpdate();
}
System.out.println("data inserted successfully");
} catch (Exception e) {
e.printStackTrace();
} }
}
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 rs.next() rs.first() rs.last(); rs.absolute(int
index);

Code :
import java.sql.Connection; import
java.sql.DriverManager; import
java.sql.ResultSet; import
java.sql.Statement; import
com.mysql.cj.jdbc.Driver; 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 = DriverManager.getConnection(url , user , password);
String sql = "select * from student";
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(sql);
while (rs.next()) {
System.out.println(rs.getInt(1) + " " + rs.getString(2) + " " + rs.getInt(3)); }
}catch(Exception e){
e.printStackTrace();
}
}
}
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 java.sql.*; import java.util.Scanner; public class CRUD {
public static void insertData(Connection con) throws SQLException {
Scanner s = new Scanner(System.in);
Scanner st = new Scanner(System.in);
System.out.println("Enter number of products to be inserted");
int n = s.nextInt();
String qeury = "insert into product values(?,?,?)";
PreparedStatement ps = con.prepareStatement(qeury);
for (int i = 0; i < n; i++) {
System.out.println("Enter the id , name , price of product : ");
int id = s.nextInt();
String name = st.nextLine();
int price = s.nextInt();
ps.setInt(1, id);
ps.setString(2, name);
ps.setInt(3, price);
ps.executeUpdate();

}
System.out.println("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 = con.createStatement();
ResultSet rs = st.executeQuery(sql);
System.err.println("product details :");
while (rs.next()) {
System.out.println(rs.getInt(1) + " " + rs.getString(2) +
" " + rs.getInt(3));
}
}

public static void deleteData(Connection con) throws SQLException {


System.out.println("Enter the id of product to delete");

Scanner s = new Scanner(System.in);


int id = s.nextInt();
String sql = "delete from product where id =" +
id; Statement st = con.createStatement(); int
ans = st.executeUpdate(sql);
if (ans !=0 ) {
System.out.println("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 = DriverManager.getConnection(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 java.sql.Connection; import
java.sql.DriverManager; import
java.sql.PreparedStatement; import
java.sql.ResultSet; import
java.sql.Statement; import
com.mysql.cj.jdbc.Driver;

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 = DriverManager.getConnection(url , user , password);
PreparedStatement insp = con.prepareStatement(insert_sql);
PreparedStatement updp = con.prepareStatement(update_sql);
PreparedStatement delp = con.prepareStatement(delete_sql);
insp.setInt(1,4 );
Name:- Chhaya Bhandari Course/Semester:-MCA/2 nd Roll_No./Sec:-20/A
Rawat

insp.setString(2,"pasta");
insp.setInt(3,250);
insp.addBatch();
insp.setInt(1,5 );
insp.setString(2,"glas");
insp.setInt(3, 25);
insp.addBatch();\
updp.setInt(1,2);
updp.setString(2,"Cat");
updp.addBatch();

delp.setInt(1,5);
delp.addBatch();

insp.executeUpdate();
// updp.executeUpdate();
delp.executeUpdate();

System.out.println("batch operation successfull");


}catch(Exception e){
e.printStackTrace();
}
}
}
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 :

Callable.java:

import java.sql.CallableStatement;
import java.sql.Connection; import
java.sql.DriverManager; import
java.sql.PreparedStatement; import
java.sql.ResultSet; import
java.sql.Statement; import
java.sql.Types; import
java.util.Scanner;
import com.mysql.cj.jdbc.Driver;

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 = DriverManager.getConnection(url , user , password);

// Prepare the callable statement


String sql = "{call GetProductName(?, ?)}";
CallableStatement cs = con.prepareCall(sql);
cs.setInt(1, 2);
cs.registerOutParameter(1, Types.INTEGER);
cs.execute();
String productName = cs.getString(1);
System.out.println("Product Name: " + productName);

}catch(Exception e){
e.printStackTrace();
}
}
}

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 :
Index.html
<!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>

Fact.java package com.amit.fact; import


java.io.IOException; import
java.io.PrintWriter; import
javax.servlet.ServletException; import
javax.servlet.annotation.WebServlet; import
javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest; import


javax.servlet.http.HttpServletResponse;
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 = Integer.parseInt(req.getParameter("n"));
int f = 1;
while(num > 0) {
f = f*num;
num--;
}
PrintWriter out;
try {
out = res.getWriter();
out.println("factorial of the number is : "+f);
}catch(IOException io)
{
io.printStackTrace();
}
}
}

Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
Name:- Chhaya Bhandari Course/Semester:-MCA/2 nd Roll_No./Sec:-20/A
Rawat

http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">


<servlet>
<servlet-name>factorial</servlet-name>
<servlet-class>com.amit.fact.FactTest</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 :

Sum.html
<!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>

Sum.java package
com.amit.fact; import
java.io.IOException;
import java.io.PrintWriter;
import
javax.servlet.http.HttpServ
let; import
Name:- Chhaya Bhandari Course/Semester:-MCA/2 nd Roll_No./Sec:-20/A
Rawat

javax.servlet.http.HttpServ
letRequest; import
javax.servlet.http.HttpServ
letResponse;

public class Sum extends HttpServlet {


public void service (HttpServletRequest req , HttpServletResponse res) {

int n1 = Integer.parseInt(req.getParameter("n1"));
int n2 = Integer.parseInt(req.getParameter("n2"));

int sum = n1 + n2; PrintWriter out;


try { out =
res.getWriter();
out.print("sum of the two numbers are :"+sum);
}catch(IOException io) {
io.printStackTrace();
}
}
}

Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" 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>com.amit.fact.Sum</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 :

Dispatch.html
<!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>

Send.java:
package com.amit.fact; import
java.io.IOException; import
javax.servlet.http.HttpServlet; import
javax.servlet.http.HttpServletRequest; import
javax.servlet.http.HttpServletResponse; import
javax.servlet.http.HttpSession;

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 = Integer.parseInt(req.getParameter("num"));
n++;
HttpSession s = req.getSession();
s.setAttribute("ck", n);
// url name not class
res.sendRedirect("send2");
}
}

Send2.java :
package com.amit.fact; import
java.io.IOException; import
java.io.PrintWriter; import
javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest; import


javax.servlet.http.HttpServletResponse; import
javax.servlet.http.HttpSession;

public class Send2 extends HttpServlet {

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

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

PrintWriter out = res.getWriter();


out.print("Eg for request dispacter :" +n );
}
}

Web.xml :
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">

<servlet>
<servlet-name>dispatch</servlet-name>
<servlet-class>com.amit.fact.Send</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>com.amit.fact.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 :

Index.html
<!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>

Cookie1.java : package com.amit.fact; import


java.io.IOException; import
javax.servlet.annotation.WebServlet; import
javax.servlet.http.Cookie; import
javax.servlet.http.HttpServlet; import
javax.servlet.http.HttpServletRequest; import
javax.servlet.http.HttpServletResponse; import
javax.servlet.http.HttpSession; 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=Integer.parseInt(req.getParameter("n"));
n++;
//HttpSession session=req.getSession();
//session.setAttribute("test", n);
Cookie ck=new Cookie("key",n+"");
res.addCookie(ck);

res.sendRedirect("next");
}
}

Cookie2.java:
package com.amit.fact;

import java.io.IOException; import


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

import javax.servlet.http.Cookie; public


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

//int n=(int)ss.getAttribute("test"); Cookie[]


ck=req.getCookies();
int n=0;
for(Cookie c: ck)
{
if(c.getName().equals("key"))
{
n=Integer.parseInt(c.getValue());
}
}
n=n*n;
PrintWriter out=res.getWriter();

out.println("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 :
Index.html:
<!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>

Login.java :
package com.amit.fact; import
java.io.IOException; import
javax.servlet.ServletException; import
javax.servlet.annotation.WebServlet; import
javax.servlet.http.HttpServlet; import
javax.servlet.http.HttpServletRequest; import
javax.servlet.http.HttpServletResponse;
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 = req.getParameter("username");
String password = req.getParameter("password"); if
(user.equals(username) && pass.equals(password)) {
res.getWriter().println("Login successfull ");
} else {
res.getWriter().println("Invalid username or password.");
}
}
}

Web.xml :
<servlet>
<servlet-name>log</servlet-name>
<servlet-class>com.amit.fact.Login</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 :
Index.jsp:
<%@ 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="factorial.jsp" method="post">

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


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

Factorial.jsp :
<%@ page import="java.io.*,java.util.*" %>
<!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 = request.getParameter("number"); int
number = Integer.parseInt(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 :

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

Add.jsp:
<%@ page import="com.mca.jsp.NumberBean" %>
<jsp:useBean id="numberBean" class="com.mca.jsp.NumberBean" 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 = numberBean.getSum();
%>
<p>The sum of <%= numberBean.getNumber1() %> and <%= numberBean.getNumber2() %>
is <%= sum %>.</p>
</body>
</html>

Numberjean.java : package
com.mca.jsp; 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 :

You might also like