AJP LabManual
AJP LabManual
Lab Manual
BE-Semester: VI
Advance Java Programming
(3160707)
2023-24
Name :
Branch :
Batch :
Enrollment No. :
CERTIFICATE
in Course of Advance Java Programming with subject code 3160707 for the
INDEX
Sr. Page
Practical Aim Date Signature
No. No.
02
Implement cookies to store firstname and
lastname using Java server pages
03
Implement the shopping cart for users for the
online shopping. Apply the concept of session.
Implement student registration form with
enrollment number, first name, last name,
04 semester, contact number. Store the details in
database. Also implement search, delete and
modify facility for student records.
05 Write a Servlet program to print system date
and time
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;
while (true) {
Socket clientSocket = serverSocket.accept();
System.out.println("Connection accepted from " + clientSocket.getInetAddress());
receiveFile(clientSocket, savePath);
clientSocket.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
Page 1
Advance Java Programming (3160707) Enrollment No. :
fileOutputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output:
Server listening on port 12345
Page 2
Advance Java Programming (3160707) Enrollment No. :
Practical : 2
Aim: Implement cookies to store firstname and lastname using Java server pages
<%
// 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>
<%
// Check if first name and last name are available in cookies
if (firstName != null && lastName != null) {
%>
<p>Hello, <%= firstName %> <%= lastName %>!</p>
<%
} else {
%>
<p>Enter your information:</p>
Page 3
Advance Java Programming (3160707) Enrollment No. :
</body>
</html>
Jsp file
<%
String firstNameParam = request.getParameter("firstName");
String lastNameParam = request.getParameter("lastName");
// 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);
Output:
Page 4
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
<%
// 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>
</body>
</html>
Page 5
Advance Java Programming (3160707) Enrollment No. :
AddToCartServlet.java:
import java.io.IOException;
import java.util.List;
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");
web.xml:
<servlet>
<servlet-name>AddToCartServlet</servlet-name>
<servlet-class>AddToCartServlet</servlet-class>
</servlet>
Page 6
Advance Java Programming (3160707) Enrollment No. :
<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>
Output:
Products:
- Product 1 - $10.00 [Add to Cart]
- Product 2 - $20.00 [Add to Cart]
- Product 3 - $30.00 [Add to Cart]
And if the user then adds "Product 2" and "Product 3" to the cart, the output would be:
Products:
- Product 1 - $10.00 [Add to Cart]
- Product 2 - $20.00 [Add to Cart]
- Product 3 - $30.00 [Add to Cart]
Page 7
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 8
Advance Java Programming (3160707) Enrollment No. :
</tr>
</table>
</form>
<a href="Search.jsp">Search</a>
</body>
</html>
Insert.jsp:
Search.jsp:
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>
<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>
Page 10
Advance Java Programming (3160707) Enrollment No. :
<td><% out.println(se);%></td>
<td><% out.println(no);%></td>
<td><a href="Delete.jsp?x=<%=id%>">Delete</a></td>
<td><a href="Edit.jsp?y=<%=id%>">Edit</a></td>
</tr>
<%
}
%>
</body>
</html>
Edit.jsp:
<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>
</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>
</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"
Page 12
Advance Java Programming (3160707) Enrollment No. :
"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+"',
Semester='"+se+"', Contactno='"+no+"' where id='"+id+"'");
st.close();
c.close();
response.sendRedirect("Search.jsp");
%>
</body>
</html>
Delete.jsp:
Class.forName("com.mysql.jdbc.Driver");
Connection
c=DriverManager.getConnection("jdbc:mysql://localhost:3306/manual","root","root");
Statement st = c.createStatement();
st.executeUpdate("delete from Prac5 where id="+id);
st.close();
c.close();
response.sendRedirect("Search.jsp");
%>
</body>
</html>
Output:
Page 14
Advance Java Programming (3160707) Enrollment No. :
Page 15
Advance Java Programming (3160707) Enrollment No. :
Page 16
Advance Java Programming (3160707) Enrollment No. :
Practical: 5
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 {
Output:
2024-01-05 11:57:08
Page 17
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>
</body>
</html>
UserBean.java:
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
@ManagedBean
@SessionScoped
public class UserBean {
Page 18
Advance Java Programming (3160707) Enrollment No. :
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.
Page 19
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;
public Customer() {
}
hibernate.cfg.xml:
<session-factory>
<!-- JDBC Database connection settings -->
Page 20
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>
CustomerDAO.java:
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public CustomerDAO() {
Configuration configuration = new Configuration().configure();
sessionFactory = configuration.buildSessionFactory();
}
try {
transaction = session.beginTransaction();
session.save(customer);
Page 21
Advance Java Programming (3160707) Enrollment No. :
transaction.commit();
} catch (Exception e) {
if (transaction != null) {
transaction.rollback();
}
e.printStackTrace();
} finally {
session.close();
}
}
try {
customer = session.get(Customer.class, customerId);
} catch (Exception e) {
e.printStackTrace();
} finally {
session.close();
}
return customer;
}
}
MainApplication.java:
Page 22
Advance Java Programming (3160707) Enrollment No. :
Output:
Page 23
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:
StudentController.java:
import java.util.ArrayList;
import java.util.List;
public StudentController() {
studentList = new ArrayList<>();
}
Page 24
Advance Java Programming (3160707) Enrollment No. :
StudentView.java
StudentApp.java:
import java.util.List;
import java.util.Scanner;
switch (choice) {
case 1:
System.out.print("Enter Student ID: ");
int studentId = scanner.nextInt();
System.out.print("Enter Enrollment Number: ");
int enrollmentNumber = scanner.nextInt();
System.out.print("Enter Semester: ");
int semester = scanner.nextInt();
System.out.print("Enter SPI: ");
double spi = scanner.nextDouble();
Page 25
Advance Java Programming (3160707) Enrollment No. :
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
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!
Page 26