0% found this document useful (0 votes)
5 views33 pages

Ajp Lab Manual

The document outlines practical implementations for advanced Java programming, including 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 includes code snippets and explanations for setting up the server, handling cookies, managing a shopping cart, and performing CRUD operations on student records. The document serves as a comprehensive guide for implementing these functionalities in Java applications.

Uploaded by

aum lad
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)
5 views33 pages

Ajp Lab Manual

The document outlines practical implementations for advanced Java programming, including 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 includes code snippets and explanations for setting up the server, handling cookies, managing a shopping cart, and performing CRUD operations on student records. The document serves as a comprehensive guide for implementing these functionalities in Java applications.

Uploaded by

aum lad
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/ 33

Advance Java Programming (3160707) Enrollment No:

Practical:1

Aim : Implement TCP Server for transferring files using Socket and
ServerSocket

import java.io.FileOutputStream;

import java.io.InputStream;

import java.net.ServerSocket;

import java.net.Socket;

public class FileServer {

public static void main(String[] args) {

int port = 12345; // Specify the port number you want to use

String savePath = "path/to/save/files"; // Specify the directory where you want to save

received files

try (ServerSocket serverSocket = new ServerSocket(port)) {

System.out.println("Server listening on port " + port);

while (true) {

Socket clientSocket = serverSocket.accept();

System.out.println("Connection accepted from " + clientSocket.getInetAddress());

receiveFile(clientSocket, savePath);

System.out.println("File received successfully from " + clientSocket.getInetAddress());

clientSocket.close();

} catch (Exception e) {

e.printStackTrace();

private static void receiveFile(Socket clientSocket, String savePath) {

1
Advance Java Programming (3160707) Enrollment No:

try {

InputStream inputStream = clientSocket.getInputStream();

byte[] buffer = new byte[4096];

int bytesRead;

// Read the file name

bytesRead = inputStream.read(buffer, 0, buffer.length);

String fileName = new String(buffer, 0, bytesRead);

// Create a FileOutputStream to save the fil

FileOutputStream fileOutputStream = new FileOutputStream(savePath + "/" + fileName);

// Read the file content and save it

while ((bytesRead = inputStream.read(buffer)) != -1) {

fileOutputStream.write(buffer, 0, bytesRead);

fileOutputStream.close();

} catch (Exception e) {

e.printStackTrace();

Output:
Server listening on port 12345

2
Advance Java Programming (3160707) Enrollment No:

Practical:2

Aim: Implement cookies to store firstname and lastname using Java server pages

<%@ page import="java.net.URLEncoder" %>


<%@ page import="java.net.URLDecoder" %>
<%@ page import="java.util.Map" %>
<%@ page import="java.util.HashMap" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
// Function to retrieve cookie value by name
String getCookieValue(String cookieName) {
Map<String, String> cookieMap = new HashMap<>();
if (request.getCookies() != null) {
for (javax.servlet.http.Cookie cookie : request.getCookies()) {
cookieMap.put(cookie.getName(), cookie.getValue());
}
}
return cookieMap.get(cookieName);
}
%>
<%
// Retrieve values from cookies
String firstName = getCookieValue("firstName");
String lastName = getCookieValue("lastName");
%>
<html>
<head>
<title>Cookie Example</title>
</head>
<body>
<h2>Welcome to the Cookie Example</h2>
<%
// Check if first name and last name are available in cookies

3
Advance Java Programming (3160707) Enrollment No:

if (firstName != null && lastName != null) {


%>
<p>Hello, <%= firstName %> <%= lastName %>!</p>
<%
} else {
%>
<p>Enter your information:</p>

<form action="setCookies.jsp" method="post">


First Name: <input type="text" name="firstName"><br>
Last Name: <input type="text" name="lastName"><br>
<input type="submit" value="Submit">
</form>
<%
}
%>
</body>
</html>
Jsp file
<%
String firstNameParam = request.getParameter("firstName");
String lastNameParam = request.getParameter("lastName");
// Encode values to handle special characters in cookie values
String encodedFirstName = URLEncoder.encode(firstNameParam, "UTF-8");
String encodedLastName = URLEncoder.encode(lastNameParam, "UTF-8");
// Create cookies
javax.servlet.http.Cookie firstNameCookie = new javax.servlet.http.Cookie("firstName",
encodedFirstName);
javax.servlet.http.Cookie lastNameCookie = new javax.servlet.http.Cookie("lastName",
encodedLastName);
// Set cookies' expiration time (optional)
firstNameCookie.setMaxAge(60 * 60 * 24 * 30); // 30 days
lastNameCookie.setMaxAge(60 * 60 * 24 * 30);
// Add cookies to the response

4
Advance Java Programming (3160707) Enrollment No:

response.addCookie(firstNameCookie);
response.addCookie(lastNameCookie);
// Redirect to the main page
response.sendRedirect("main.jsp");
%>

Output:
Welcome to the Cookie Example
Hello, John Doe!

5
Advance Java Programming (3160707) Enrollment No:

Practical:3

Aim: Implement the shopping cart for users for the online shopping. Apply the
concept of session.

index.jsp

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


<html>
<head>
<title>Online Shopping</title>
</head>
<body>
<h2>Welcome to Online Shopping</h2>
<%
// Check if the user has a shopping cart in the session
if (session.getAttribute("cart") == null) {
// If not, create a new shopping cart (a List of product names)
session.setAttribute("cart", new java.util.ArrayList<String>());
}
%>
<p>Products:</p>
<ul>
<li>Product 1 - $10.00 <a href="AddToCart?product=Product1">Add to Cart</a></li>
<li>Product 2 - $20.00 <a href="AddToCart?product=Product2">Add to Cart</a></li>
<li>Product 3 - $30.00 <a href="AddToCart?product=Product3">Add to Cart</a></li>
</ul>
<p>Your Shopping Cart:</p>
<ul>
<%
// Display the items in the user's shopping cart
java.util.List<String> cart = (java.util.List<String>) session.getAttribute("cart");
for (String item : cart) {
%>
<li><%= item %></li>
<%
}
%>
</ul>
</body>
</html>
AddToCartServlet.java:
import java.io.IOException;
import java.util.List;

6
Advance Java Programming (3160707) Enrollment No:

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebServlet("/AddToCart")
public class AddToCartServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Get the product name from the request parameter
String product = request.getParameter("product");
// Get the user's session
HttpSession session = request.getSession();
// Get the shopping cart from the session
List<String> cart = (List<String>) session.getAttribute("cart");
// Add the selected product to the shopping cart
cart.add(product);
// Redirect back to the main page
response.sendRedirect("index.jsp");
}
}
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/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">

<servlet>
<servlet-name>AddToCartServlet</servlet-name>
<servlet-class>AddToCartServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>AddToCartServlet</servlet-name>
<url-pattern>/AddToCart</url-pattern>
</servlet-mapping>

<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

7
Advance Java Programming (3160707) Enrollment No:

Output:
Welcome to Online Shopping
Products:
- Product 1 - $10.00 [Add to Cart]
- Product 2 - $20.00 [Add to Cart]
- Product 3 - $30.00 [Add to Cart]
Your Shopping Cart:
- Product 1
And if the user then adds "Product 2" and "Product 3" to the cart, the output would be:
Welcome to Online Shopping
Products:
- Product 1 - $10.00 [Add to Cart]
- Product 2 - $20.00 [Add to Cart]
- Product 3 - $30.00 [Add to Cart]
Your Shopping Cart:
- Product 1
- Product 2
- Product 3

8
Advance Java Programming (3160707) Enrollment No:

Practical: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.

Form.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>Insert title here</title>

</head>

<body>

<form action="Insert.jsp">

<table border="1px solid black">

<tr>

<td>ENROLLMENT_NUMBER: </td>

<td><input type="text" name="en"></td>

</tr>

<tr>

<td>FIRSTNAME: </td>

<td><input type="text" name="fn"></td>

9
Advance Java Programming (3160707) Enrollment No:

</tr>

<tr>

<td>LASTNAME: </td>

<td><input type="text" name="ln"></td>

</tr>

<tr>

<td>SEMESTER: </td>

<td><input type="text" name="se"></td>

</tr>

<tr>

<td>CONTACT_NUMBER: </td>

<td><input type="text" name="no"></td>

</tr>

<tr>

<td><input type="submit" value="Save"></td>

</tr>

</table>

</form>

<a href="Search.jsp">Search</a>

</body>

</html>

Insert.jsp:

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

pageEncoding="ISO-8859-1" import="java.sql.*"%>

10
Advance Java Programming (3160707) Enrollment No:

<!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>Insert title here</title>

</head>

<body>

<%

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");

Class.forName("com.mysql.jdbc.Driver");

Connection

c=DriverManager.getConnection("jdbc:mysql://localhost:3306/manual","root","root");

Statement s2 = c.createStatement();

s2.executeUpdate("insert into Prac5(Enrollment,Firstname,Lastname,Semester,Contactno)

values('"+en+"','"+fn+"','"+ln+"','"+se+"','"+no+"')");

s2.close();

c.close();

response.sendRedirect("Form.jsp");

%>

11
Advance Java Programming (3160707) Enrollment No:

</body>

</html>

Search.jsp:

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

pageEncoding="ISO-8859-1" import="java.sql.*"%>

<!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>Insert title here</title>

</head>

<body>

<%

Class.forName("com.mysql.jdbc.Driver");

Connection

c=DriverManager.getConnection("jdbc:mysql://localhost:3306/manual","root","root");

Statement st = c.createStatement();

ResultSet rs = st.executeQuery("select* from Prac5");

%>

<table border="1px solid black">

<tr>

<th>ID</th>

<th>ENROLLMENT_NUMBER</th>

12
Advance Java Programming (3160707) Enrollment No:

<th>FIRSTNAME</th>

<th>LASTNAME</th>

<th>SEMESTER</th>

<th>CONTACT_NUMBER</th>

<th>Action</th>

</tr>

<%

while(rs.next())

int id = rs.getInt("id");

String en = rs.getString("Enrollment");

String fn = rs.getString("Firstname");

String ln = rs.getString("Lastname");

String se = rs.getString("Semester");

String no = rs.getString("Contactno");

%>

<tr>

<td><% out.println(id);%></td>

<td><% out.println(en);%></td>

<td><% out.println(fn);%></td>

<td><% out.println(ln);%></td>

<td><% out.println(se);%></td>

<td><% out.println(no);%></td>

<td><a href="Delete.jsp?x=<%=id%>">Delete</a></td>

13
Advance Java Programming (3160707) Enrollment No:

<td><a href="Edit.jsp?y=<%=id%>">Edit</a></td>

</tr>

<%

%>

</body>

</html>

Edit.jsp:

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

pageEncoding="ISO-8859-1" import="java.sql.*"%>

<!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>Insert title here</title>

</head>

<body>

<%

int id = Integer.parseInt(request.getParameter("y"));

int i=0;

Class.forName("com.mysql.jdbc.Driver");

Connection c = DriverManager.getConnection("jdbc:mysql://localhost/manual","root","root");

Statement st = c.createStatement();

14
Advance Java Programming (3160707) Enrollment No:

ResultSet rs =st.executeQuery("select * from Prac5 where id = "+ id);

%>

<%

while(rs.next())

int id1 = rs.getInt("id");

String en = rs.getString("Enrollment");

String fn = rs.getString("Firstname");

String ln = rs.getString("Lastname");

String se = rs.getString("Semester");

String no = rs.getString("Contactno");

%>

<form action="Update.jsp">

<table border="1px solid black">

<tr>

<td><input type="hidden" name="id1" value='<%=id1%>'></td>

</tr>

<tr>

<td>ENROLLMENT_NUMBER: </td>

<td><input type="text" name="en" value="<%=en%>"></td>

</tr>

<tr>

<td>FIRSTNAME: </td>

<td><input type="text" name="fn" value="<%=fn%>"></td>

15
Advance Java Programming (3160707) Enrollment No:

</tr>

<tr>

<td>LASTNAME: </td>

<td><input type="text" name="ln" value="<%=ln%>"></td>

</tr>

<tr>

<td>SEMESTER: </td>

<td><input type="text" name="se" value="<%=se%>"></td>

</tr>

<tr>

<td>CONTACT_NUMBER: </td>

<td><input type="text" name="no" value="<%=no%>"></td>

</tr>

<tr>

<td><input type="submit" value="Update"></td>

</tr>

</table>

</form>

<%

c.close();

st.close();

%>

</body>

16
Advance Java Programming (3160707) Enrollment No:

</html>

Update.jsp:

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

pageEncoding="ISO-8859-1" import="java.sql.*"%>

<!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>Insert title here</title>

</head>

<body>

<%

int id =Integer.parseInt( request.getParameter("id1"));

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");

Class.forName("com.mysql.jdbc.Driver");

Connection c = DriverManager.getConnection("jdbc:mysql://localhost/manual","root","root");

Statement st =c.createStatement();

st.executeUpdate("update Prac5 set Enrollment='"+en+"', Firstname='"+fn+"',

Lastname='"+ln+"',

17
Advance Java Programming (3160707) Enrollment No:

Semester='"+se+"', Contactno='"+no+"' where id='"+id+"'");

st.close();

c.close();

response.sendRedirect("Search.jsp");

%>

</body>

</html>

Delete.jsp:

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

pageEncoding="ISO-8859-1" import="java.sql.*"%>

<!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>Insert title here</title>

</head>

<body>

<%

int id = Integer.parseInt(request.getParameter("x"));

Class.forName("com.mysql.jdbc.Driver");

Connection

c=DriverManager.getConnection("jdbc:mysql://localhost:3306/manual","root","root");

Statement st = c.createStatement();

18
Advance Java Programming (3160707) Enrollment No:

st.executeUpdate("delete from Prac5 where id="+id);

st.close();

c.close();

response.sendRedirect("Search.jsp");

%>

</body>

</html>

19
Advance Java Programming (3160707) Enrollment No:

20
Advance Java Programming (3160707) Enrollment No:

21
Advance Java Programming (3160707) Enrollment No:

Practical:5

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

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/DateTimeServlet")
public class DateTimeServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
IOException {
// Set content type
response.setContentType("text/html");
// Get the current date and time
Date currentDate = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDate = dateFormat.format(currentDate);
// Prepare the HTML response
PrintWriter out = response.getWriter();
out.println("<html><head><title>System Date and Time</title></head><body>");
out.println("<h2>System Date and Time:</h2>");
out.println("<p>" + formattedDate + "</p>");
out.println("</body></html>");
}
}
Output:
2024-01-05 11:57:

22
Advance Java Programming (3160707) Enrollment No:

Practical: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.

welcome.xhtml:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core">
<head>
<title>Welcome Page</title>
</head>
<body>
<h:form>
<h:outputLabel for="username">Enter Username:</h:outputLabel>
<h:inputText id="username" value="#{userBean.username}" required="true" />
<h:commandButton value="Submit" action="#{userBean.validateUsername}" />
</h:form>
<h:outputText value="#{userBean.welcomeMessage}" rendered="#{not empty
userBean.welcomeMessage}" />
</body>
</html>
UserBean.java:
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
@ManagedBean
@SessionScoped
public class UserBean {
private String username;
private String welcomeMessage;
public String getUsername() {
return username;
}

23
Advance Java Programming (3160707) Enrollment No:

public void setUsername(String username) {


this.username = username;
}
public String getWelcomeMessage() {
return welcomeMessage;
}
public void setWelcomeMessage(String welcomeMessage) {
this.welcomeMessage = welcomeMessage;
}
public void validateUsername() {
if (username != null && !username.trim().isEmpty()) {
welcomeMessage = "Welcome " + username + "!";
} else {
welcomeMessage = null;
}
}
}
Output:
If you enter a username and submit, it will display a welcome message like
"Welcome Parth!".
If you submit without entering a username, the welcome message will not be displayed.

24
Advance Java Programming (3160707) Enrollment No:

Practical:7

Aim: Write Hibernate application to store customer records and retrieve the
customer record including name, contact number, address.
Customer.java:
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Customer {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String contactNumber;
private String address;
// Constructors, getters, and setters
public Customer() {
}
public Customer(String name, String contactNumber, String address) {
this.name = name;
this.contactNumber = contactNumber;
this.address = address;
}
// Getters and setters
}
hibernate.cfg.xml:
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD
3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- JDBC Database connection settings -->

25
Advance Java Programming (3160707) Enrollment No:

<property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/your_database</
property>
<property name="hibernate.connection.username">your_username</property>
<property name="hibernate.connection.password">your_password</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>

<!-- Specify dialect -->


<property name="hibernate.show_sql">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- JDBC connection pool settings -->
<property name="hibernate.c3p0.min_size">5</property>
<property name="hibernate.c3p0.max_size">20</property>
<property name="hibernate.c3p0.timeout">300</property>
<property name="hibernate.c3p0.max_statements">50</property>
<property name="hibernate.c3p0.idle_test_period">3000</property>
<!-- Specify annotated class -->
<mapping class="com.example.Customer"/>
</session-factory>
</hibernate-configuration>
CustomerDAO.java:
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class CustomerDAO {
private SessionFactory sessionFactory;
public CustomerDAO() {
Configuration configuration = new Configuration().configure();
sessionFactory = configuration.buildSessionFactory();
}
public void saveCustomer(Customer customer) {
Session session = sessionFactory.openSession();
Transaction transaction = null;

26
Advance Java Programming (3160707) Enrollment No:

try {
transaction = session.beginTransaction();
session.save(customer);
transaction.commit();
} catch (Exception e) {
if (transaction != null) {
transaction.rollback();
}
e.printStackTrace();
} finally {
session.close();
}
}
public Customer getCustomer(Long customerId) {
Session session = sessionFactory.openSession();
Customer customer = null;
try {
customer = session.get(Customer.class, customerId);
} catch (Exception e) {
e.printStackTrace();
} finally {
session.close();
}
return customer;
}
}
MainApplication.java:
public class MainApplication {
public static void main(String[] args) {
// Create a customer
Customer customer = new Customer("John Doe", "1234567890", "123 Main Street");
// Save the customer
CustomerDAO customerDAO = new CustomerDAO();
customerDAO.saveCustomer(customer);

27
Advance Java Programming (3160707) Enrollment No:

// Retrieve the customer by ID


Long customerId = customer.getId();
Customer retrievedCustomer = customerDAO.getCustomer(customerId);
// Display the retrieved customer details
if (retrievedCustomer != null) {
System.out.println("Retrieved Customer Details:");
System.out.println("Name: " + retrievedCustomer.getName());
System.out.println("Contact Number: " + retrievedCustomer.getContactNumber());
System.out.println("Address: " + retrievedCustomer.getAddress());
} else {
System.out.println("Customer not found.");
}
}
}
Output:
Retrieved Customer Details:
Name: John Doe
Contact Number: 1234567890
Address: 123 Main Stree

28
Advance Java Programming (3160707) Enrollment No:

Practical:8

Aim: Write an application to keep record and retrieve record of student.


The record includes student id, enrollment number, semester, SPI. Use MVC
arechitecture.
StudentModel.java:
public class StudentModel {
private int studentId;
private int enrollmentNumber;
private int semester;
private double spi;
// Constructors, getters, and setters
public StudentModel(int studentId, int enrollmentNumber, int semester, double spi) {
this.studentId = studentId;
this.enrollmentNumber = enrollmentNumber;
this.semester = semester;
this.spi = spi;
}
// Getters and setters
}
StudentController.java:
import java.util.ArrayList;
import java.util.List;
public class StudentController {
private List<StudentModel> studentList;
public StudentController() {
studentList = new ArrayList<>();
}
public void addStudent(StudentModel student) {
studentList.add(student);
}
public List<StudentModel> getAllStudents() {
return studentList;
}

29
Advance Java Programming (3160707) Enrollment No:

}
StudentView.java
public class StudentView {
public void printStudentDetails(List<StudentModel> students) {
for (StudentModel student : students) {
System.out.println("Student ID: " + student.getStudentId());
System.out.println("Enrollment Number: " + student.getEnrollmentNumber());
System.out.println("Semester: " + student.getSemester());
System.out.println("SPI: " + student.getSpi());
System.out.println("--------------------");
}
}
}
StudentApp.java:
import java.util.List;
import java.util.Scanner;
public class StudentApp {
public static void main(String[] args) {
StudentController controller = new StudentController();
StudentView view = new StudentView();
Scanner scanner = new Scanner(System.in);
int choice;
do {
System.out.println("1. Add Student");
System.out.println("2. View All Students");
System.out.println("3. Exit");
System.out.print("Enter your choice: ");
choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.print("Enter Student ID: ");
int studentId = scanner.nextInt();
System.out.print("Enter Enrollment Number: ");
int enrollmentNumber = scanner.nextInt();

30
Advance Java Programming (3160707) Enrollment No:

System.out.print("Enter Semester: ");


int semester = scanner.nextInt();
System.out.print("Enter SPI: ");
double spi = scanner.nextDouble();
StudentModel student = new StudentModel(studentId, enrollmentNumber, semester, spi);
controller.addStudent(student);
break;
case 2:
List<StudentModel> students = controller.getAllStudents();
view.printStudentDetails(students);
break;
case 3:
System.out.println("Exiting the application. Goodbye!");
break;
default:
System.out.println("Invalid choice. Please try again.");
}
} while (choice != 3);
scanner.close();
}
}
Output:
1. Add Student
2. View All Students
3. Exit
Enter your choice: 1
Enter Student ID: 1
Enter Enrollment Number: 2023001
Enter Semester: 3
Enter SPI: 8.5
1. Add Student
2. View All Students
3. Exit
Enter your choice: 2

31
Advance Java Programming (3160707) Enrollment No:

Student ID: 1
Enrollment Number: 2023001
Semester: 3
SPI: 8.5
--------------------
1. Add Student
2. View All Students
3. Exit
Enter your choice: 3
Exiting the application. Goodbye!

32
Advance Java Programming (3160707) Enrollment No:

33

You might also like