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

Final Advanced Java Pra

The document outlines practical assignments for an MCAII student named Ajinkya Milind Jagtap, focusing on advanced Java programming. It includes implementations for a TCP server for file transfer, cookie management using Java Server Pages, a shopping cart system utilizing sessions, and a student registration form with database interactions. Each practical consists of code snippets and aims to demonstrate specific programming concepts and functionalities.

Uploaded by

ajinkya jagtap
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 views36 pages

Final Advanced Java Pra

The document outlines practical assignments for an MCAII student named Ajinkya Milind Jagtap, focusing on advanced Java programming. It includes implementations for a TCP server for file transfer, cookie management using Java Server Pages, a shopping cart system utilizing sessions, and a student registration form with database interactions. Each practical consists of code snippets and aims to demonstrate specific programming concepts and functionalities.

Uploaded by

ajinkya jagtap
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
You are on page 1/ 36

Name: Ajinkya Milind Jagtap Class: MCAII

Roll No: 19 Date:


Subject: Advance Java Proramming

Practical No:- 1

Aim: Implement TCP Server for transferring files using Socket and

Server Socket.

Code:

Server Code:
import java.io.*;
import java.net.*;

public class Server {


public static void main(String args[]) throws Exception {
ServerSocket ss = new ServerSocket(7777);
System.out.println("Server is running, waiting for client...");

Socket s = ss.accept();
System.out.println("Client connected.");

FileInputStream fin = new FileInputStream("Send.txt");


DataOutputStream dout = new DataOutputStream(s.getOutputStream());

int r;
while ((r = fin.read()) != -1) {
dout.write(r);
}

System.out.println("\nFile transfer Completed");

fin.close();
dout.close();
s.close();
ss.close();
}
}

1
Client Code:
import java.io.*;
import java.net.*;

public class Client {


public static void main(String[] args) throws Exception {
Socket s = new Socket("127.0.0.1", 7777);

if (s.isConnected()) {
System.out.println("Connected to server");
}

FileOutputStream fout = new FileOutputStream("received.txt");


DataInputStream din = new DataInputStream(s.getInputStream());

int r;
while ((r = din.read()) != -1) {
fout.write(r);
}

System.out.println("File received successfully!");

fout.close();
din.close();
s.close();
}
}

Output:

2
Name: Ajinkya Milind Jagtap Class: MCAII
Roll No: 19 Date:
Subject: Advance Java Proramming

Practical No: - 2
Aim: Implement cookies to store firstname and lastname using Java serverpages.

Code:

Mains.jsp file
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" import="javax.servlet.http.Cookie"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Setting Cookies</title>
</head>
<body>
<%
// Get first name and last name from request
String firstNameParam = request.getParameter("first_name");
String lastNameParam = request.getParameter("last_name");

// Create cookies
Cookie firstName = new Cookie("first_name", firstNameParam);
Cookie lastName = new Cookie("last_name", lastNameParam);
// Set expiry for 1 hour (optional)
firstName.setMaxAge(60*60);
lastName.setMaxAge(60*60);
// Add cookies to response
response.addCookie(firstName);
response.addCookie(lastName);
%>
<center>
<h1>Cookies are set successfully!</h1>
</center>
<ul>
<li><p><b>First Name:</b> <%= firstNameParam %> </p></li>
<li><p><b>Last Name:</b> <%= lastNameParam %> </p></li>
</ul>
<br>
<a href="hello.jsp">Go Back</a>
</body>
</html>

3
hello.jsp file

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


pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Hello Page</title>
</head>
<body>
<form action="Mains.jsp" method="GET">
First Name: <input type="text" name="first_name">
<br />
Last Name: <input type="text" name="last_name" />
<br />
<input type="submit" value="Submit" />
</form>
</body>
</html>

Output:

4
Name: Ajinkya Milind Jagtap Class: MCAII
Roll No: 19 Date:
Subject: Advance Java Proramming

Practical No: - 3

Aim: Implement the shopping cart for users for the online shopping. Apply the

concept of session.
Code:

CartItemBean:

package in.techfreaks.shoppingcart.beans;
public class CartItemBean { private String strPartNumber;
private String strModelDescription;
private double dblUnitCost;
private int iQuantity;
private double dblTotalCost;
public String getPartNumber()
{ return strPartNumber;
}
public void setPartNumber(String strPartNumber)
{ this.strPartNumber = strPartNumber;
}
public String getModelDescription()
{ return strModelDescription;
}
public void setModelDescription(String strModelDescription)
{ this.strModelDescription =strModelDescription;
}
public double getUnitCost() { return dblUnitCost;
}
public void setUnitCost(double dblUnitCost)
{ this.dblUnitCost = dblUnitCost;
}
public int getQuantity() {
return iQuantity;
}
public void setQuantity(int quantity)
{ iQuantity = quantity;
}

5
public double getTotalCost() { return dblTotalCost;
}
public void setTotalCost(double dblTotalCost) { this.dblTotalCost = dblTotalCost;
}
}

CartBean:

package in.techfreaks.shoppingcart.beans; import java.util.ArrayList;


public class CartBean {
private ArrayList alCartItems = new ArrayList(); private
double dblOrderTotal ;
public int getLineItemCount() { return alCartItems.size();
}
public void deleteCartItem(String strItemIndex) { int
iItemIndex = 0;
try {
iItemIndex = Integer.parseInt(strItemIndex);
alCartItems.remove(iItemIndex - 1);
calculateOrderTotal();
} catch(NumberFormatException nfe) {
System.out.println("Error while deleting cart item: "+nfe.getMessage()); nfe.printStackTrace();
}
}
public void updateCartItem(String strItemIndex, String strQuantity)
{ double dblTotalCost = 0.0;
double dblUnitCost = 0.0; int
iQuantity = 0;
int iItemIndex = 0;
CartItemBean cartItem = null;
try {
iItemIndex = Integer.parseInt(strItemIndex);
iQuantity = Integer.parseInt(strQuantity);
if(iQuantity>0) {
cartItem = (CartItemBean)alCartItems.get(iItemIndex-1); dblUnitCost
= cartItem.getUnitCost();
dblTotalCost = dblUnitCost*iQuantity;
cartItem.setQuantity(iQuantity);
cartItem.setTotalCost(dblTotalCost);
calculateOrderTotal();
}
} catch (NumberFormatException nfe) {
System.out.println("Error while updating cart: "+nfe.getMessage()); nfe.printStackTrace();
}
}
public void addCartItem(String strModelNo, String strDescription, String strUnitCost,String
strQuantity) {
double dblTotalCost = 0.0;
double dblUnitCost = 0.0; int
iQuantity = 0;
CartItemBean cartItem = new CartItemBean(); try
6
{

dblUnitCost = Double.parseDouble(strUnitCost);
iQuantity = Integer.parseInt(strQuantity);
if(iQuantity>0) {
dblTotalCost = dblUnitCost*iQuantity;
cartItem.setPartNumber(strModelNo);
cartItem.setModelDescription(strDescription);
cartItem.setUnitCost(dblUnitCost);
cartItem.setQuantity(iQuantity);
cartItem.setTotalCost(dblTotalCost);
alCartItems.add(cartItem); calculateOrderTotal();
}
} catch (NumberFormatException nfe) {
System.out.println("Error while parsing from String to primitive types:"+nfe.getMessage()); nfe.printStackTrace();
}
}
public void addCartItem(CartItemBean cartItem) {
alCartItems.add(cartItem);
}
public CartItemBean getCartItem(int iItemIndex) { CartItemBean
cartItem = null;if(alCartItems.size()>iItemIndex) { cartItem =
(CartItemBean) alCartItems.get(iItemIndex);
}
return cartItem;
}
{ this.alCartItems = alCartItems;
}
public double getOrderTotal()
{ return dblOrderTotal;
}
public void setOrderTotal(double dblOrderTotal) { this.dblOrderTotal
= dblOrderTotal;
}
protected void calculateOrderTotal() { double dblTotal = 0; for(int
counter=0;
counter<alCartItems.size();
counter++)
{
CartItemBean cartItem = (CartItemBean) alCartItems.get(counter);
dblTotal+=cartItem.getTotalCost();
}
setOrderTotal(dblTotal);
}
}

7
CartController:

package in.techfreaks.shoppingcart.servlet;
import in.techfreaks.shoppingcart.beans.CartBean;
import java.io.IOException;
import javax.servlet.ServletException; import
javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class CartController extends HttpServlet {
//public static final String addToCart
public void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
String strAction = request.getParameter("action");

if(strAction!=null&& !strAction.equals(""))

{ if(strAction.equals("add")) {

addToCart(request);

} else if (strAction.equals("Update"))

{ updateCart(request);
} else if (strAction.equals("Delete"))
{ deleteCart(request);
}
}
response.sendRedirect("../ShoppingCart.jsp");
}
protected void deleteCart(HttpServletRequest request) { HttpSession session =request.getSession();
String strItemIndex = request.getParameter("itemIndex");
CartBean cartBean = null;
Object objCartBean = session.getAttribute("cart"); if(objCartBean!=null) {
cartBean = (CartBean) objCartBean ;
}
else {
cartBean = new CartBean();
}
cartBean.deleteCartItem(strItemIndex);
}
protected void updateCart(HttpServletRequest request) {
HttpSession session =request.getSession();
String strQuantity = request.getParameter("quantity");
String strItemIndex = request.getParameter("itemIndex");
CartBean cartBean = null;
Object objCartBean = session.getAttribute("cart"); if(objCartBean!=null) {
cartBean = (CartBean) objCartBean ;
}
else {
cartBean = new CartBean();
8
}
cartBean.updateCartItem(strItemIndex, strQuantity);
}
protected void addToCart(HttpServletRequest request) { HttpSession
session = request.getSession();
String strModelNo = request.getParameter("modelNo"); String
strDescription = request.getParameter("description"); String
strPrice = request.getParameter("price");
String strQuantity = request.getParameter("quantity"); CartBean
cartBean = null;
Object objCartBean = session.getAttribute("cart");
if(objCartBean!=null) {
cartBean = (CartBean) objCartBean ;
} else {
cartBean = new CartBean();
session.setAttribute("cart", cartBean);
}
cartBean.addCartItem(strModelNo, strDescription, strPrice, strQuantity);
}
}

ShoppingCart.jsp

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">


<html>
<head>
<title>www.tech-freaks.in - Shopping Cart</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body>
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
<p><font face="Verdana, Arial, Helvetica, sans-serif"><strong>Shopping
Cart</strong></font></p>
<p><a href="/ModelList.jsp" mce_href="ModelList.jsp">Model List</a> </p>
<table width="75%" border="1">
<tr bgcolor="#CCCCCC">
<td><strong><font size="2" face="Verdana, Arial, Helvetica, sans-serif">Model Description</font></strong></td>
<td><strong><font size="2" face="Verdana, Arial, Helvetica, sans-
serif">Quantity</font></strong></td>
<td><strong><font size="2" face="Verdana, Arial, Helvetica, sans-serif">Unit
Price</font></strong></td>
<td><strong><font size="2" face="Verdana, Arial, Helvetica, sans-
serif">Total</font></strong></td>
</tr>
<jsp:useBean id="cart" scope="session" class="in.techfreaks.shoppingcart.beans.CartBean" />
<c:if test="${cart.lineItemCount==0}">
<tr>
<td colspan="4"><font size="2" face="Verdana, Arial, Helvetica, sans-serif">- Cart iscurrently empty -
<br/>
</tr>
9
</c:if>
<c:forEach var="cartItem" items="${cart.cartItems}" varStatus="counter">
<form name="item" method="POST" action="servlet/CartController">
<tr>
<td><font size="2" face="Verdana, Arial, Helvetica, sans-serif"><b><c:out
value="${cartItem.partNumber}"/></b><br/>
<c:out value="${cartItem.modelDescription}"/></font></td>
<td><font size="2" face="Verdana, Arial, Helvetica, sans-serif"><input type='hidden' name='itemIndex'
value='<c:out value="${counter.count}"/>'><input type='text' name="quantity" value='<c:out
value="${cartItem.quantity}"/>' size='2'> <input type="submit" name="action" value="Update">
<br/> <input type="submit" name="action" value="Delete"></font></td>
<td><font size="2" face="Verdana, Arial, Helvetica, sans-serif">$<c:out value="${cartItem.unitCost}"/></font></td>
<td><font size="2" face="Verdana, Arial, Helvetica, sans-serif">$<c:out value="${cartItem.totalCost}"/></font></td>
</tr>
</form>
</c:forEach>
<tr>
<td colspan="2"> </td>
<td> </td>
<td><font size="2" face="Verdana, Arial, Helvetica, sans-serif">Subtotal: $<c:out
value="${cart.orderTotal}"/></font></td>
</tr>
</table>
</body>
</html>

Output :

10
Name: Ajinkya Milind Jagtap Class: MCAII
Roll No: 19 Date:
Subject: Advance Java Proramming

Practical No: - 4

Aim: Implement student registration form with enrollment number, first name, last

name, semester, contact number. Store the details in database. Also,implement

search, delete and modify facility for student records.


Code:

Form.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-
1"%>
<html>
<head><title>Student Registration Form</title></head>
<body>
<h2>Register New Student</h2>
<form action="Insert.jsp">
<table>
<tr><td>Enrollment No:</td><td><input type="text" name="en" required></td></tr>
<tr><td>First Name:</td><td><input type="text" name="fn" required></td></tr>
<tr><td>Last Name:</td><td><input type="text" name="ln" required></td></tr>
<tr><td>Semester:</td><td><input type="text" name="se" required></td></tr>
<tr><td>Contact No:</td><td><input type="text" name="no" required></td></tr>
<tr><td colspan="2"><input type="submit" value="Save"></td></tr>
</table>
</form>
<br>
<a href="Search.jsp">Search Student Records</a>
</body>
</html>

Insert.jsp

<%@ page import="java.sql.*" %>


<%
String en = request.getParameter("en");
String fn = request.getParameter("fn");
String ln = request.getParameter("ln");
String se = request.getParameter("se");

11
String no = request.getParameter("no");
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/studentdb", "root", "");
PreparedStatement ps = con.prepareStatement("INSERT INTO students(enrollment_no, first_name, last_name,
semester, contact_no) VALUES (?, ?, ?, ?, ?)");
ps.setString(1, en);
ps.setString(2, fn);
ps.setString(3, ln);
ps.setString(4, se);
ps.setString(5, no);
ps.executeUpdate();
ps.close();
con.close();
response.sendRedirect("Form.jsp");
} catch(Exception e) {
out.println("Error: " + e.getMessage());
}
%>

Search.jsp

<%@ page import="java.sql.*" %>


<html>
<head><title>Search Students</title></head>
<body>
<h2>Student Records</h2>
<table border="1">
<tr>
<th>ID</th><th>Enrollment No</th><th>First Name</th><th>Last Name</th><th>Semester</th><th>Contact
No</th><th>Actions</th>
</tr>
<%
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/studentdb", "root", "");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM students");
while(rs.next()) {
%>
<tr>
<td><%= rs.getInt("id") %></td>
<td><%= rs.getString("enrollment_no") %></td>
<td><%= rs.getString("first_name") %></td>
<td><%= rs.getString("last_name") %></td>
<td><%= rs.getString("semester") %></td>
<td><%= rs.getString("contact_no") %></td>
<td>
<a href="Edit.jsp?id=<%= rs.getInt("id") %>">Edit</a> |
<a href="Delete.jsp?id=<%= rs.getInt("id") %>" onclick="return confirm('Delete this record?');">Delete</a>
12
</td>
</tr>
<%
}
rs.close();
st.close();
con.close();
} catch(Exception e) {
out.println("Error: " + e.getMessage());
}
%>
</table>
<br><a href="Form.jsp">Back to Form</a>
</body>
</html>

Edit.jsp

<%@ page import="java.sql.*" %>


<%
int id = Integer.parseInt(request.getParameter("id"));
String en="", fn="", ln="", se="", no="";
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/studentdb", "root", "");
PreparedStatement ps = con.prepareStatement("SELECT * FROM students WHERE id=?");
ps.setInt(1, id);
ResultSet rs = ps.executeQuery();
if(rs.next()) {
en = rs.getString("enrollment_no");
fn = rs.getString("first_name");
ln = rs.getString("last_name");
se = rs.getString("semester");
no = rs.getString("contact_no");
}
rs.close();
ps.close();
con.close();
} catch(Exception e) {
out.println("Error: " + e.getMessage());
}
%>
<html>
<body>
<h2>Edit Student Record</h2>
<form action="Update.jsp">
13
<input type="hidden" name="id" value="<%= id %>">
<table>
<tr><td>Enrollment No:</td><td><input type="text" name="en" value="<%= en %>" required></td></tr>
<tr><td>First Name:</td><td><input type="text" name="fn" value="<%= fn %>" required></td></tr>
<tr><td>Last Name:</td><td><input type="text" name="ln" value="<%= ln %>" required></td></tr>
<tr><td>Semester:</td><td><input type="text" name="se" value="<%= se %>" required></td></tr>
<tr><td>Contact No:</td><td><input type="text" name="no" value="<%= no %>" required></td></tr>
<tr><td colspan="2"><input type="submit" value="Update"></td></tr>
</table>
</form>
</body>
</html>

Update.jsp

<%@ page import="java.sql.*" %>


<%
int id = Integer.parseInt(request.getParameter("id"));
String en = request.getParameter("en");
String fn = request.getParameter("fn");
String ln = request.getParameter("ln");
String se = request.getParameter("se");
String no = request.getParameter("no");
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/studentdb", "root", "");
PreparedStatement ps = con.prepareStatement("UPDATE students SET enrollment_no=?, first_name=?,
last_name=?, semester=?, contact_no=? WHERE id=?");
ps.setString(1, en);
ps.setString(2, fn);
ps.setString(3, ln);
ps.setString(4, se);
ps.setString(5, no);
ps.setInt(6, id);
ps.executeUpdate();
ps.close();
con.close();
response.sendRedirect("Search.jsp");
} catch(Exception e) {
out.println("Error: " + e.getMessage());

14
}
%>

Delete.jsp

<%@ page import="java.sql.*" %>


<%
int id = Integer.parseInt(request.getParameter("id"));
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/studentdb", "root", "");
PreparedStatement ps = con.prepareStatement("DELETE FROM students WHERE id=?");
ps.setInt(1, id);
ps.executeUpdate();
ps.close();
con.close();
response.sendRedirect("Search.jsp");
} catch(Exception e) {
out.println("Error: " + e.getMessage());
}
%>
Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<session-config>
<session-timeout>30 </session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>Form.jsp</welcome-file>
</welcome-file-list>
</web-app>

Output:

Student Registration Form

15
Record Inserted Successfully.

Update Student Records

Record Updated Successfully:-


The enrollment number of ID=29 has been updated and contact number is changed.

Record Deleted:-
The Record of ID=31 has been deleted.

16
Name: Ajinkya Milind Jagtap Class: MCAII
Roll No: 19 Date:
Subject: Advance Java Proramming

Practical No: - 5

Aim: Write a Servlet program to print system date and time.

Code:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.Date;
public class DateServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException,
ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Date currentDate = new Date();
out.println("<html><body>");
out.println("<h1 style='color:blue;'>Current Date and Time</h1>");
out.println("<h2>" + currentDate.toString() + "</h2>");
out.println("</body></html>");
out.close();
}
}

Output:

17
Name: Ajinkya Milind Jagtap Class: MCAII
Roll No: 19 Date:
Subject: Advance Java Proramming

Practical No: - 6

Aim: Design a web page that takes the Username from user and if it is a valid username

prints “Welcome Username”. Use JSF to implement.

Code:

index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Login Page</title>
</head>
<body>
<form action="loginPage" method="post">
Username: <input type="text" name="uname"/><br/><br/>
Password: <input type="password" name="upass"/><br/><br/>
<input type="submit" value="SUBMIT"/>
</form>
</body>
</html>

Login.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
@WebServlet("/loginPage")
public class Login extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String name = request.getParameter("uname");
String pass = request.getParameter("upass");
if ("Admin".equals(name) && "root".equals(pass)) {
request.setAttribute("uname", name); // Pass to welcome page
RequestDispatcher dispatcher = request.getRequestDispatcher("welcome");
dispatcher.forward(request, response);
} else {
18
out.println("<p style='color:red'>Invalid username or password</p>");
RequestDispatcher dispatcher = request.getRequestDispatcher("index.html");
dispatcher.include(request, response);
}
}
}

Welcome.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
@WebServlet("/welcome")
public class Welcome extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String name = (String) request.getAttribute("uname");
out.println("<h2>Welcome " + name + "!</h2>");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response); // Forward GET to POST
}
}

Web.xml

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


<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XML
Schema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<servlet>
<servlet-name>Login</servlet-name>
<servlet-class>Login</servlet-class>
</servlet>
<servlet>
<servlet-name>Welcome</servlet-name>
<servlet-class>Welcome</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>Login</servlet-name>

19
<url-pattern>/loginPage</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Welcome</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>

Output:

20
Name: Ajinkya Milind Jagtap Class: MCAII
Roll No: 19 Date:
Subject: Advance Java Proramming

Practical No: - 7

Aim: Write Hibernate application to store student records and retrieve the student

record including name, email, course.


Code:

StudentControllerServlet.java File
package com.controller;
import com.dao.StudentDao;
import com.model.Student;
import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.*;
import java.io.IOException;
import java.util.List;
@WebServlet("/StudentControllerServlet")
public class StudentControllerServlet extends HttpServlet {
private final StudentDao studentDao = new StudentDao();
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
String action = request.getParameter("action");
if (action == null) action = "list";
switch (action) {
case "addForm":
showAddForm(request, response);
break;
case "edit":
showEditForm(request, response);
break;
case "delete":
deleteStudent(request, response);
break;
default:
listStudents(request, response);
break;
}
21
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException,
ServletException {
String action = request.getParameter("action");
switch (action) {
case "insert":
insertStudent(request, response);
break;
case "update":
updateStudent(request, response);
break;
default:
response.sendRedirect("StudentControllerServlet");
break;
}
}
private void listStudents(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
List<Student> students = studentDao.getAllStudents();
request.setAttribute("students", students);
RequestDispatcher dispatcher = request.getRequestDispatcher("search.jsp");
dispatcher.forward(request, response);
}
private void showAddForm(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
RequestDispatcher dispatcher = request.getRequestDispatcher("form.jsp");
dispatcher.forward(request, response);
}
private void insertStudent(HttpServletRequest request, HttpServletResponse response) throws IOException {
String name = request.getParameter("name");
String email = request.getParameter("email");
String course = request.getParameter("course");
Student student = new Student();
student.setName(name);
student.setEmail(email);
student.setCourse(course);
studentDao.saveStudent(student);
response.sendRedirect("StudentControllerServlet");
}
private void showEditForm(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
int id = Integer.parseInt(request.getParameter("id"));
Student student = studentDao.getStudentById(id);
request.setAttribute("student", student);
RequestDispatcher dispatcher = request.getRequestDispatcher("edit.jsp");
dispatcher.forward(request, response);

22
}
private void updateStudent(HttpServletRequest request, HttpServletResponse response) throws IOException {
int id = Integer.parseInt(request.getParameter("id"));
String name = request.getParameter("name");
String email = request.getParameter("email");
String course = request.getParameter("course");
Student student = studentDao.getStudentById(id);
student.setName(name);
student.setEmail(email);
student.setCourse(course);
studentDao.updateStudent(student);
response.sendRedirect("StudentControllerServlet");
}
private void deleteStudent(HttpServletRequest request, HttpServletResponse response) throws IOException {
int id = Integer.parseInt(request.getParameter("id"));
studentDao.deleteStudent(id);
response.sendRedirect("StudentControllerServlet");
}
}

StudentDAO.java File

package com.dao;
import java.util.List;
import com.model.Student;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.util.HibernateUtil;
public class StudentDao {
public void saveStudent(Student student) {
Transaction tx = null;
try (Session session = HibernateUtil.getSessionFactory().openSession()) {
tx = session.beginTransaction();
session.persist(student);
tx.commit();
} catch (Exception e) {
if (tx != null && tx.isActive()) {
tx.rollback();
}
throw new RuntimeException("Failed to save student", e);
}
}
public List<Student> getAllStudents() {
try (Session session = HibernateUtil.getSessionFactory().openSession()) {
return session.createQuery("from Student", Student.class).list();
} catch (Exception e) {
throw new RuntimeException("Failed to retrieve students", e);
}
}
23
public Student getStudentById(int id) {
try (Session session = HibernateUtil.getSessionFactory().openSession()) {
return session.get(Student.class, id);
} catch (Exception e) {
throw new RuntimeException("Failed to retrieve student with id: " + id, e);
}
}
public void updateStudent(Student student) {
Transaction tx = null;
try (Session session = HibernateUtil.getSessionFactory().openSession()) {
tx = session.beginTransaction();
session.merge(student);
tx.commit();
} catch (Exception e) {
if (tx != null && tx.isActive()) {
tx.rollback();
}
throw new RuntimeException("Failed to update student", e);
}
}
public void deleteStudent(int id) {
Transaction tx = null;
try (Session session = HibernateUtil.getSessionFactory().openSession()) {
tx = session.beginTransaction();
Student student = session.get(Student.class, id);
if (student != null) {
session.remove(student);
}
tx.commit();
} catch (Exception e) {
if (tx != null && tx.isActive()) {
tx.rollback();
}
throw new RuntimeException("Failed to delete student with id: " + id, e);
}
}
}

Student.java File

package com.model;
import jakarta.persistence.*;
@Entity
@Table(name = "student")
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;

24
private String email;
private String course;
// Getters and Setters
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setEmail(String email) {
this.email = email;
}
public void setCourse(String course) {
this.course = course;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public String getEmail() {
return email;
}
public String getCourse() {
return course;
}
}

HibernateUtil.java File

package com.util;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.model.Student;
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
Configuration configuration = new Configuration();
// Database connection settings for MySQL 8
configuration.setProperty("hibernate.connection.driver_class", "com.mysql.cj.jdbc.Driver");
configuration.setProperty("hibernate.connection.url",
"jdbc:mysql://localhost:3306/manual?useSSL=false&serverTimezone=UTC");
configuration.setProperty("hibernate.connection.username", "root");
configuration.setProperty("hibernate.connection.password", "");
25
configuration.setProperty("hibernate.connection.pool_size", "10");
configuration.setProperty("hibernate.show_sql", "true");
configuration.setProperty("hibernate.format_sql", "true");
configuration.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL8Dialect");
configuration.setProperty("hibernate.hbm2ddl.auto", "update");
// Explicitly add annotated entity class
configuration.addAnnotatedClass(Student.class);
// Build and return the SessionFactory
return configuration.buildSessionFactory();
} catch (Exception ex) {
System.err.println("Initial SessionFactory creation failed: " + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static void shutdown() {
if (sessionFactory != null && !sessionFactory.isClosed()) {
sessionFactory.close();
}
}
}

form.jsp File
<%@ page contentType="text/html;charset=UTF-8" %>
<html>
<head><title>Add Student</title></head>
<body>
<h2>Add New Student</h2>
<form action="StudentControllerServlet" method="post">
<input type="hidden" name="action" value="insert">
Name : <input type="text" name="name" required><br>
Email : <input type="email" name="email" required><br>
Course: <input type="text" name="course" required><br>
<input type="submit" value="Add Student">
</form>
</body>
</html>

edit.jsp File

<%@ page contentType="text/html;charset=UTF-8" %>


<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head><title>Edit Student</title></head>
<body>
<h2>Edit Student</h2>
<form action="StudentControllerServlet" method="post">
<input type="hidden" name="action" value="update">
<input type="hidden" name="id" value="${student.id}">
Name: <input type="text" name="name" value="${student.name}" required><br>
Email: <input type="email" name="email" value="${student.email}" required><br>

26
Course: <input type="text" name="course" value="${student.course}" required><br>
<input type="submit" value="Update Student">
</form>
</body>
</html>

search.jsp File

<%@ page contentType="text/html;charset=UTF-8" %>


<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head><title>Students</title></head>
<body>
<h2>Student List</h2>
<a href="StudentControllerServlet?action=addForm">Add New Student</a>
<br>
</br>
<table border="1">
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Course</th>
<th>Action</th>
</tr>
<c:forEach var="student" items="${students}">
<tr>
<td>${student.id}</td>
<td>${student.name}</td>
<td>${student.email}</td>
<td>${student.course}</td>
<td>
<a href="StudentControllerServlet?action=edit&id=${student.id}">Edit</a> |
<a href="StudentControllerServlet?action=delete&id=${student.id}"
onclick="return confirm('Are you sure you want to delete this student?')">Delete</a>
</td>
</tr>
</c:forEach>
</table>
</body>
</html>

27
Output:

28
Name: Ajinkya Milind Jagtap Class: MCAII
Roll No: 19 Date:
Subject: Advance Java Proramming

Practical No: - 8

Aim: Write an application to keep record and retrieve record of student. The record
includes student id, enrollment number, semester, SPI. Use MVC architectures

Code:

index.jsp

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


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>INDEX PAGE</title>
</head>
<body>
<a href="load.html">INSERT</a>
<br />
<a href="search.html">SEARCH</a>
<br />
</body>
</html>

spring-servlet.xml

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


<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">

29
<context:component-scan base-package="com"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/"/>
<property name="suffix" value=".jsp"/>
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/studentdb?useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="annotatedClasses">
<list>
<value>com.model.RegVO</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL8Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>
</beans>

30
RegController.java

package com.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.dao.RegDAO;
import com.model.RegVO;
@Controller
public class RegController {
@Autowired
RegDAO regDAO;
@RequestMapping(value = "load.html", method = RequestMethod.GET)
public ModelAndView load() {
return new ModelAndView("Registration", "RegVO", new RegVO());
}
@RequestMapping(value = "insert.html", method = RequestMethod.POST)
public ModelAndView insert(@ModelAttribute RegVO regVO) {
regDAO.insert(regVO);
return new ModelAndView("redirect:/search.html");
}
@RequestMapping(value = "search.html", method = RequestMethod.GET)
public ModelAndView search() {
List<RegVO> searchList = regDAO.search();
return new ModelAndView("Search", "SearchList", searchList);
}
@RequestMapping(value = "delete.html", method = RequestMethod.GET)
public ModelAndView delete(@RequestParam int id, @ModelAttribute RegVO regVO) {
regVO.setId(id);
regDAO.delete(regVO);
return new ModelAndView("redirect:/search.html");
}
@RequestMapping(value = "edit.html", method = RequestMethod.GET)
public ModelAndView edit(@RequestParam int id, @ModelAttribute RegVO regVO) {
regVO.setId(id);
List<RegVO> editList = regDAO.edit(regVO);
return new ModelAndView("Registration", "RegVO", editList.get(0));
31
}
}

RegDAO.java

package com.dao;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.model.RegVO;
@Repository
public class RegDAO {
@Autowired
private SessionFactory sessionFactory;
public void insert(RegVO regVO) {
try (Session session = sessionFactory.openSession()) {
Transaction transaction = session.beginTransaction();
session.saveOrUpdate(regVO);
transaction.commit();
} catch (Exception e) {
e.printStackTrace();
}
}
public List<RegVO> search() {
try (Session session = sessionFactory.openSession()) {
Query<RegVO> query = session.createQuery("from RegVO", RegVO.class);
return query.list();
}
}
public void delete(RegVO regVO) {
try (Session session = sessionFactory.openSession()) {
Transaction transaction = session.beginTransaction();
session.delete(regVO);
transaction.commit();
}
}
public List<RegVO> edit(RegVO regVO) {
try (Session session = sessionFactory.openSession()) {
Query<RegVO> query = session.createQuery("from RegVO where id = :id", RegVO.class);
query.setParameter("id", regVO.getId());
return query.list();
}
}
}

32
RegVO.java

package com.model;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
@Entity
@Table(name = "Spring")
public class RegVO {
@Id
@Column(name = "Id")
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
@Column(name = "StudentID")
private String studentID;
@Column(name = "Enrollment")
private String enrollment;
@Column(name = "Semester")
private String semester;
@Column(name = "SPI")
private String spi;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getStudentID() {
return studentID;
}
public void setStudentID(String studentID) {
this.studentID = studentID;
}
public String getEnrollment() {
return enrollment;
}
public void setEnrollment(String enrollment) {
this.enrollment = enrollment;
}
public String getSemester() {
return semester;
}
public void setSemester(String semester) {
this.semester = semester;
}

public String getSpi() {


return spi;
}
33
public void setSpi(String spi) {
this.spi = spi;
}
}

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"


xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com</groupId>
<artifactId>Assignment8</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<spring.version>6.2.1</spring.version>
<hibernate.version>6.4.4</hibernate.version>
<mysql.version>8.0.33</mysql.version>
<java.version>17</java.version>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
</properties>
<dependencies>
<!-- Spring Web MVC -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>6.2.1</version>
</dependency>
<!-- Spring ORM -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>6.2.1</version>
</dependency>
<!-- Hibernate Core -->
<dependency>
<groupId>org.hibernate.orm</groupId>
<artifactId>hibernate-core</artifactId>
<version>6.4.4.Final</version>
</dependency>
<!-- MySQL Connector -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
</dependency>
<!-- Apache Commons DBCP -->
<dependency>
<groupId>org.apache.commons</groupId>
34
<artifactId>commons-dbcp2</artifactId>
<version>2.12.0</version>
</dependency>
<!-- JSTL -->
<dependency>
<groupId>jakarta.servlet.jsp.jstl</groupId>
<artifactId>jakarta.servlet.jsp.jstl-api</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>jakarta.servlet.jsp.jstl</artifactId>
<version>3.0.1</version>
</dependency>
<!-- Servlet API -->
<dependency>
<groupId>jakarta.servlet</groupId>
<artifactId>jakarta.servlet-api</artifactId>
<version>6.0.0</version>
<scope>provided</scope>
</dependency>
<!-- JSP API -->
<dependency>
<groupId>jakarta.servlet.jsp</groupId>
<artifactId>jakarta.servlet.jsp-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.13.0</version>
<configuration>
<source>17</source>
<target>17</target>
<compilerArgs>
<arg>-parameters</arg>
</compilerArgs>
</configuration>
</plugin>
<!-- Maven WAR Plugin, version 3.4.0 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.4.0</version>
<configuration>
<warSourceDirectory>src/main/webapp</warSourceDirectory>

35
</configuration>
</plugin>
</plugins>
</build>
</project>

Output:

36

You might also like