AJP Praticals Dhvanit

Download as pdf or txt
Download as pdf or txt
You are on page 1of 62

Diploma Engineering

Laboratory Manual
(Advanced JAVA Programming)
4351603
Information Technology 5th Semester
Enrollment No. 226170316152
Name Vara Dhvanit M.
Branch Information Technology
Academic Term 2024-25
Institute Government Polytechnic
Ahamedabad

Directorate Of Technical Education


Gandhinagar - Gujarat
Advanced JAVA Programming (4351603)

DTE’s Vision:
● To provide globally competitive technical education;
● Remove geographical imbalances and inconsistencies;
● Develop student friendly resources with a special focus on girls’ education
and support to weaker sections;
● Develop programs relevant to industry and create a vibrant pool of technical
professionals.

DTE’s Mission:

 Quality technical and professional education with continuous improvement of all the
resources and personnel

Institute’s Vision:

To be a leading technical institute that provides transformative education to learners for achieving
competency as per the needs of industry and society, thus contributing to nation building.

Institute’s Mission:

 To provide a conducive learning environment to nurture learners.


 To act as a catalyst for achieving academic excellence by bringing stake holders on same
platform.
 To be committed towards continuous improvement and enrichment of learners by a holistic
approach to

Department’s Vision:

 To acquire quality Education, Research and Development in the field of Information


technology meeting the global standards and comply with the ever-growing technology

Department’s Mission:
 The graduates of our department will be efficient in technical and ethical responsibilities to
become globally recognised by pursuing opportunities for higher studies and real time
problem solving.
 Project development in association with the Government, Industries and Professionals will
be done that can meet industrial needs.
 Students will be competent by learning the principals of Information technology that can
match national and international standards.
Advanced JAVA Programming (4351603)

Certificate

This is to certify that Mr. Dhvanit Vara Enrollment No.226170316152 of 5th


Semester of Diploma in Informatio Techology of Government Polytechnic
ahmedabad (617) has satisfactorily completed the term work in Advanced JAVA
Programming course for the academic year: 2024 Term: Even prescribed in the
GTU curriculum.

Place:……………..
Date: …………………..

Signature of Course Faculty Head of the Department


Advanced JAVA Programming (4351603)

Preface
The primary aim of any laboratory/Practical/field work is enhancement of required skills as well
as creative ability amongst students to solve real time problems by developing relevant competencies in
psychomotor domain. Keeping in view, GTU has designed competency focused outcome-based
curriculum -2021 (COGC-2021) for Diploma engineering programmes. In this more time is allotted to
practical work than theory. It shows importance of enhancement of skills amongst students and it pays
attention to utilize every second of time allotted for practical amongst Students, Instructors and Lecturers
to achieve relevant outcomes by performing rather than writing practice in study type. It is essential for
effective implementation of competency focused outcome- based Green curriculum-2021. Every
practical has been keenly designed to serve as a tool to develop & enhance relevant industry needed
competency in each and every student. These psychomotor skills are very difficult to develop through
traditional chalk and board content delivery method in the classroom. Accordingly, this lab manual has
been designed to focus on the industry defined relevant outcomes, rather than old practice of conducting
practical to prove concept and theory.

By using this lab manual, students can read procedure one day in advance to actual performance
day of practical experiment which generates interest and also, they can have idea of judgement of
magnitude prior to performance. This in turn enhances predetermined outcomes amongst students. Each
and every Experiment /Practical in this manual begins by competency, industry relevant skills, course
outcomes as well as practical outcomes which serve as a key role for doing the practical. The students
will also have a clear idea of safety and necessary precautions to be taken while performing experiments.

This manual also provides guidelines to lecturers to facilitate student-centered lab activities for
each practical/experiment by arranging and managing necessary resources in order that the students
follow the procedures with required safety and necessary precautions to achieve outcomes. It also gives
an idea of how students will be assessed by providing Rubrics.
This course provides the knowledge necessary to develop dynamic web pages using Servlet, JSP,
MVC web frameworks and hibernate. It covers the basic underlying concepts and techniques recently
used in the IT industry. After going through this course students will be able to design MVC based Web
applications.

Although we try our level best to design this lab manual, there are always chances of
improvement. We welcome any suggestions for improvement.
Advanced JAVA Programming (4351603)

Programme Outcomes (POs):

1. Basic and Discipline specific knowledge: Apply knowledge of basic mathematics,


science and engineering fundamentals and engineering specialization to solve the
engineering problems.

2. Problem analysis: Identify and analyse well-defined engineering problems using


codified standard methods.

3. Design/ development of solutions: Design solutions for engineering well-defined


technical problems and assist with the design of systems components or processes to
meet specified needs.

4. Engineering Tools, Experimentation and Testing: Apply modern engineering tools


and appropriate technique to conduct standard tests and measurements.

5. Engineering practices for society, sustainability and environment: Apply


appropriate technology in context of society, sustainability, environment and ethical
practices.

6. Project Management: Use engineering management principles individually, as a


team member or a leader to manage projects and effectively communicate about well-
defined engineering activities.

7. Life-long learning: Ability to analyze individual needs and engage in updating in the
context of technological changes in field of engineering.
Advanced JAVA Programming (4351603)

Practical Outcome - Course Outcome matrix


Course Outcomes (COs):

CO1. Develop a GUI application using swing components.


CO2. Apply ORM based Methodology for Application Development.
CO3. Develop Web Applications using Servlets and deploy in popular servers like Tomcat
CO4. Develop JSP based applications with database connectivity.
CO5. Apply MVC architecture using Spring framework.

CO1 CO2 CO3 CO4 CO5


Sr. Practical Outcome/Title of
No. experiment

1.
Develop a GUI program by using
one swing button and adding it
√ - - - -
on the JFrame object

2.
Develop a program to create
checkboxes for different courses
belonging to a university such
that the course selected would √ - - - -
be displayed.

3.
Develop a program to Implement
Traffic signal(Red, Green and
Yellow) by using Swing
components ( Using JFrame, √ - - - -
JRadioButton, ItemListener etc.)

4. Develop a program using JDBC


to display student’s record
(Enroll No, Name, Address,
Mobile No,and Email-ID) into
- √ - - -
table ‘StuRec’
Advanced JAVA Programming (4351603)

5. Develop a program using JDBC


to edit (insert, update, delete)
Student’s profile stored in the
database
- √ - - -

6. Develop an application to store,


update, fetch and delete data of
Employee (NAME, AGE, SALARY
and DEPARTMENT) using
- √ - - -
Hibernate CRUD operations.
7.
Develop a simple servlet
program which maintains a
counter for the number of times
it has been accessed since its
- - √ - -
loading; initialize the counter
using deployment descriptor.
8. Create a web form which
processes servlet and
demonstrates use of cookies
and sessions.
- - √ - -

Develop a web form which √


9.
processes servlet for user login
functionality

10. Develop a JSP web application √


to display student monthly
attendance in each subject of
current semester via
enrollment number.

Develop a JSP web application √


11.
to select shopping products,
buy any products and product
billing page using session
management.
Advanced JAVA Programming (4351603)

12. Develop a JSP program for √


student registration for new
admission in college and display
stored data into admin
dashboard.

13. Develop a Web MVC √


Architecture based application
to provide user Login and
Register using Spring Boot.
Advanced JAVA Programming (4351603)

Industry Relevant Skills


The following industry relevant skills are expected to be developed in the
students by performance of experiments of this course.

1. Analytical and logical thinking.


2. Project management, Team-based working, communication skill
3. Creativity & Design ability
4. Effective Analysis and Organizing.

Guidelines to Course Faculty

1. Course faculty should demonstrate experiment with all necessary


implementation strategies described in the curriculum.
2. Course faculty should explain industrial relevance before starting each
experiment.
3. Course faculty should Involve & give opportunity to all students for hands-on
experience.
4. Course faculty should ensure mentioned skills are developed in the students
by asking.
5. Utilise 2 hrs of lab hours effectively and ensure completion of write up with
quiz also.
6. Encourage peer to peer learning by doing the same experiment through fast
learners.

Instructions for Students

1. Organize the work in the group and make a record of all observations.
2. Students shall develop maintenance skills as expected by industries.
3. Students shall attempt to develop related hand-on skills and build
confidence.
4. Students shall develop the habits of evolving more ideas, innovations, skills
etc.
5. Students shall refer to technical magazines and data books.
6. Students should develop the habit to submit the practical on date and time.
7. Students should prepare well while submitting a write-up of exercise.

8 | Page
Advanced JAVA Programming (4351603)

Continuous Assessment Sheet


Enrolment No: 226170316152 Batch: Even
Name: Dhvanit Vara Term:2024-25

Sr. Practical Outcome/Title of experiment Page Date Marks


(10) Sign
no No.

1
Develop a GUI program by using one swing button and
adding it on the JFrame object

2
Develop a program to create checkboxes for different
courses belonging to a university such that the course
selected would be displayed.

Develop a program to Implement Traffic signal(Red,


3
Green and Yellow) by using Swing components ( Using
JFrame, JRadioButton, ItemListener etc.)

4 Develop a program using JDBC to display student’s


record (Enroll No, Name, Address, Mobile No,and
Email-ID) into table ‘StuRec’

5
Develop a program using JDBC to edit (insert, update,
delete) Student’s profile stored in the database

6 Develop an application to store, update, fetch and


delete data of Employee (NAME, AGE, SALARY and
DEPARTMENT) using Hibernate CRUD operations.

7
Develop a simple servlet program which maintains a
counter for the number of times it has been accessed
since its loading; initialize the counter using
deployment descriptor.

9 | Page
Advanced JAVA Programming (4351603)

8
Create a web form which processes servlet and
demonstrates use of cookies and sessions.

9 Develop a web form which processes servlet for user


login functionality

10
Develop a JSP web application to display student
monthly attendance in each subject of current
semester via enrollment number.

11
Develop a JSP web application to select shopping
products, buy any products and product billing page
using session management.

12
Develop a JSP program for student registration for
new admission in college and display stored data into
admin dashboard.

13 Develop a Web MVC Architecture based application


to provide user Login and Register using Spring Boot.

10 | Page
Advanced JAVA Programming (4351603) Dhvanit Vara (226170316152)

Practical: 1 Develop a GUI program by using one swing button and adding it on the
JFrame object.

Code:
import javax.swing.*;
import java.awt.*;

public class p1 {
public static void main(String[] args) {

JFrame f = new JFrame("p1");

JButton h = new JButton("RS world");

h.setForeground(Color.white);

h.setBounds(600, 300, 100, 40);


h.setBackground(Color.black);

f.add(h);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(3000, 800);
f.setLayout(null);
f.setVisible(true);
}

}
Advanced JAVA Programming (4351603) Dhvanit Vara (226170316152)

Assessment-Rubrics

Faculty
Date
Signature
Marks Obtained
Program Total
correctness Implementation Studnet’s
and Presentation engagement in (10)
(4) Methodology practical activities
R1 (3) (3)

R2 R3

Sign with Date


Advanced JAVA Programming (4351603) Dhvanit Vara (226170316152)

Practical: 2 Develop a program to create checkboxes for different courses belonging to a


university such that the course selected would be displayed.

Code:

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class p2 extends JFrame {


private JCheckBox[] checkBoxes;
private JTextArea selectedCoursesTextArea;

public p2() {
// Create checkboxes for courses
String[] courses = { "MCN", "AJP", "AIML", "start up" };
checkBoxes = new JCheckBox[courses.length];

// Set up the layout


JPanel checkBoxPanel = new JPanel();
checkBoxPanel.setLayout(new GridLayout(courses.length, 1));
for (int i = 0; i < courses.length; i++) {
checkBoxes[i] = new JCheckBox(courses[i]);
checkBoxes[i].addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
showSelectedCourses();
}
});
checkBoxPanel.add(checkBoxes[i]);
}

selectedCoursesTextArea = new JTextArea(5, 20);


selectedCoursesTextArea.setEditable(false);

// Add components to the frame


add(checkBoxPanel, BorderLayout.WEST);
add(selectedCoursesTextArea, BorderLayout.SOUTH);

setTitle("University Course Selector");


pack();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
}

private void showSelectedCourses() {


Advanced JAVA Programming (4351603) Dhvanit Vara (226170316152)

StringBuilder selectedCourses = new StringBuilder("Selected


Courses:\n");

for (JCheckBox checkBox : checkBoxes) {


if (checkBox.isSelected()) {
selectedCourses.append(checkBox.getText()).append("\n");
}
}

selectedCoursesTextArea.setText(selectedCourses.toString());
}

public static void main(String[] args) {


SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new p2().setVisible(true);
}
});
}
}
Advanced JAVA Programming (4351603) Dhvanit Vara (226170316152)

Output:

Assessment-Rubrics

Faculty
Date
Signature
Marks Obtained
Program Total
correctness Implementation Studnet’s
and Presentation engagement in (10)
(4) Methodology practical activities
R1 (3) (3)

R2 R3

Sign with Date


Advanced JAVA Programming (4351603) Dhvanit Vara (226170316152)

Practical :3 Develop a program to Implement Traffic signal(Red, Green and Yellow) by


using Swing components ( Using JFrame, JRadioButton, ItemListener etc.)

Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class p3 extends JFrame implements ItemListener {


private JRadioButton redButton, greenButton, yellowButton;
private JLabel signalLabel;

public p3() {
setTitle("Traffic Signal");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());

redButton = new JRadioButton("Red");


greenButton = new JRadioButton("Green");
yellowButton = new JRadioButton("Yellow");

ButtonGroup buttonGroup = new ButtonGroup();


buttonGroup.add(redButton);
buttonGroup.add(greenButton);
buttonGroup.add(yellowButton);

redButton.addItemListener(this);
greenButton.addItemListener(this);
yellowButton.addItemListener(this);

signalLabel = new JLabel("Select a signal color");

add(redButton);
add(greenButton);
add(yellowButton);
add(signalLabel);

pack();
setVisible(true);
}

public void itemStateChanged(ItemEvent e) {


if (e.getSource() == redButton && redButton.isSelected()) {
signalLabel.setText("Signal: Red");
signalLabel.setForeground(Color.RED);
Advanced JAVA Programming (4351603) Dhvanit Vara (226170316152)

} else if (e.getSource() == greenButton &&


greenButton.isSelected()) {
signalLabel.setText("Signal: Green");
signalLabel.setForeground(Color.GREEN);
} else if (e.getSource() == yellowButton &&
yellowButton.isSelected()) {
signalLabel.setText("Signal: Yellow");
signalLabel.setForeground(Color.YELLOW);
}
}

public static void main(String[] args) {


new p3();
}
}

Output:
Advanced JAVA Programming (4351603) Dhvanit Vara (226170316152)

Assessment-Rubrics

Faculty
Date
Signature
Marks Obtained
Program Total
correctness Implementation Studnet’s
and Presentation engagement in (10)
(4) Methodology practical activities
R1 (3) (3)

R2 R3

Sign with Date


Advanced JAVA Programming (4351603) Dhvanit Vara (226170316152)

Practical – 4: Develop a program using JDBC to display student’s record


(Enroll No, Name, Address, Mobile No,and Email-ID) into table ‘StuRec’.

Code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class pr4 {


public static void main(String[] args) {
String jdbcUrl = "jdbc:mysql://localhost:3306/StudentDB";
String user = "ridham";
String password = "Ridham4580";
try {
Connection connection = DriverManager.getConnection(jdbcUrl, user, password);
Statement statement = connection.createStatement();
String sqlQuery = "SELECT EnrollNo, Name, Address, MobileNo, Email FROM StuRec";
ResultSet resultSet = statement.executeQuery(sqlQuery);
System.out.println("EnrollNo\tName\t\t\tAddress\t\tMobile_No\t\tEmail");
while (resultSet.next()) {
int enrollNo = resultSet.getInt("EnrollNo");
String name = resultSet.getString("Name");
String address = resultSet.getString("Address");
String mobileNo = resultSet.getString("MobileNo");
String email = resultSet.getString("Email");
System.out.println(enrollNo + "\t\t" + name + "\t\t" + address + "\t\t" + mobileNo + "\t\t" + email);
}
resultSet.close();
statement.close();
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

Output:
Advanced JAVA Programming (4351603) Dhvanit Vara (226170316152)

Assessment-Rubrics

Faculty
Date
Signature
Marks Obtained
Program Total
correctness Implementation Studnet’s
and Presentation engagement in (10)
(4) Methodology practical activities
R1 (3) (3)

R2 R3

Sign with Date


Advanced JAVA Programming (4351603) Dhvanit Vara (226170316152)

Practical – 5: Develop a program using JDBC to edit (insert, update, delete)


Student’s profile stored in the database.

Code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;
public class pr5 {
public static void main(String[] args) {
String jdbcUrl = "jdbc:mysql://localhost:3306/StudentDB";
String user = "root";
String password = "Ridham4580";
try {
Connection connection = DriverManager.getConnection(jdbcUrl, user, password);
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("Choose an operation:");
System.out.println("1. Insert Student Profile");
System.out.println("2. Update Student Profile");
System.out.println("3. Delete Student Profile");
System.out.println("4. Exit");
System.out.print("Enter your choice: ");
int choice = scanner.nextInt();
scanner.nextLine();
switch (choice) {
case 1:
insertStudentProfile(connection, scanner);
break;
case 2:
updateStudentProfile(connection, scanner);
break;
case 3:
deleteStudentProfile(connection, scanner);
break;
case 4:
System.out.println("Exiting the program.");
connection.close();
System.exit(0);
break;
default:
System.out.println("Invalid choice. Please try again.");
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
Advanced JAVA Programming (4351603) Dhvanit Vara (226170316152)

private static void insertStudentProfile(Connection connection, Scanner scanner) throws


SQLException {
System.out.print("Enter Enroll_No: ");
long enrollNo = scanner.nextLong();
scanner.nextLine();
System.out.print("Enter Name: ");
String name = scanner.nextLine();
System.out.print("Enter Address: ");
String address = scanner.nextLine();
System.out.print("Enter Mobile No: ");
String mobileNo = scanner.nextLine();
System.out.print("Enter Email: ");
String email = scanner.nextLine();
String insertSQL = "INSERT INTO StuRec (EnrollNo, Name, Address, MobileNo, Email) VALUES (?,
?, ?, ?, ?)";
PreparedStatement preparedStatement = connection.prepareStatement(insertSQL);
preparedStatement.setLong(1, enrollNo);
preparedStatement.setString(2, name);
preparedStatement.setString(3, address);
preparedStatement.setString(4, mobileNo);
preparedStatement.setString(5, email);
int rowsAffected = preparedStatement.executeUpdate();
if (rowsAffected > 0) {
System.out.println("Student profile inserted successfully.");
} else {
System.out.println("Failed to insert the student profile.");
}
}
private static void updateStudentProfile(Connection connection, Scanner scanner) throws
SQLException {
System.out.print("Enter Enroll_No to Update: ");
long enrollNo = scanner.nextLong();
scanner.nextLine();
System.out.print("Enter New Name: ");
String newName = scanner.nextLine();
String updateSQL = "UPDATE StuRec SET Name = ? WHERE EnrollNo = ?";
PreparedStatement preparedStatement = connection.prepareStatement(updateSQL);
preparedStatement.setString(1, newName);
preparedStatement.setLong(2, enrollNo);
int rowsAffected = preparedStatement.executeUpdate();
if (rowsAffected > 0) {
System.out.println("Student profile updated successfully.");
} else {
System.out.println("No student profile found for the given Enroll_No.");
}
}
private static void deleteStudentProfile(Connection connection, Scanner scanner) throws
SQLException {
System.out.print("Enter Enroll_No to Delete: ");
long enrollNo = scanner.nextLong();
String deleteSQL = "DELETE FROM StuRec WHERE EnrollNo = ?";
PreparedStatement preparedStatement = connection.prepareStatement(deleteSQL);
Advanced JAVA Programming (4351603) Dhvanit Vara (226170316152)

preparedStatement.setLong(1, enrollNo);
int rowsAffected = preparedStatement.executeUpdate();
if (rowsAffected > 0) {
System.out.println("Student profile deleted successfully.");
} else {
System.out.println("No student profile found for the given Enroll_No.");
}
}
}

Output:
1. Insert in database

2. Update Name

3. Delete Data of Enroll_No


Advanced JAVA Programming (4351603) Dhvanit Vara (226170316152)

Assessment-Rubrics

Faculty
Date
Signature
Marks Obtained
Program Total
correctness Implementation Studnet’s
and Presentation engagement in (10)
(4) Methodology practical activities
R1 (3) (3)

R2 R3

Sign with Date


Advanced JAVA Programming (4351603) Dhvanit Vara (226170316152)

Practical – 6: Develop an application to store, update, fetch and delete data of


Employee (NAME, AGE, SALARY and DEPARTMENT) using Hibernate CRUD
operations.

Code: File Name: - App.java


package com.employeeapp;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.sql.Date;
import com.employeeapp.dao.UserDao;
import com.employeeapp.dao.UserDaoImpl;
import com.employeeapp.model.User;
public class App {
public static void main(String[] args) {
UserDao dao = new UserDaoImpl();
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
while (true) {
try {
System.out.println("==================MENU=================");
System.out.println("1. Create a new user");
System.out.println("2. See a user");
System.out.println("3. See all the users");
System.out.println("4. Update a user information");
System.out.println("5. Delete a user");
System.out.println("6. Exit");
System.out.print("Enter your choice: ");
int choice = Integer.parseInt(input.readLine());
switch (choice) {
case 1: {
System.out.print("Enter the firstname: ");
String firstname = input.readLine().trim();
System.out.print("Enter the lastname: ");
String lastname = input.readLine().trim();
System.out.println();
System.out.println("Dob format will be yyyy-mm-dd");
System.out.print("Enter the dob: ");
String date = input.readLine().trim();
User user = new User(firstname, lastname, Date.valueOf(date));
System.out.println("\nAdding the user.........");
dao.saveUser(user);
System.out.println("User added successfully!");
break;
}
case 2: {
System.out.print("Enter the userId: ");
long id = Long.parseLong(input.readLine());
System.out.println(dao.getUserById(id));
break;
}
case 3: {
dao.getAllUsers().forEach(System.out::println);
break;
}
case 4: {
System.out.println("Enter the userId: ");
long id = Long.parseLong(input.readLine());
User user = dao.getUserById(id);
if (user == null) {
System.out.println("Sorry! The user does not exit.");
break;
}
System.out.println("Leave blank if don't want to change.");
System.out.print("Enter the firstname: ");
String firstname = input.readLine().trim();
if (firstname != "")
user.setFirstname(firstname);
Advanced JAVA Programming (4351603) Dhvanit Vara (226170316152)

System.out.print("Enter the lastname: ");


String lastname = input.readLine().trim();
if (lastname != "")
user.setLastname(lastname);
System.out.println();
System.out.println("Dob format will be yyyy-mm-dd");
System.out.print("Enter the dob: ");
String date = input.readLine().trim();
if (date != "")
user.setDob(Date.valueOf(date));
System.out.println("\nUpdating the user.........");
dao.updateUser(user);
System.out.println("User updated successfully!");
break;
}
case 5: {
System.out.println("Enter the userId: ");
long id = Long.parseLong(input.readLine());
System.out.println("Deleting the user.......");
dao.deleteUserById(id);
System.out.println("User deleted successfully!");
break;
}
case 6:
System.exit(0);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}

File Name: - UserDao.java

package com.employeeapp.dao;
import java.util.List;
import com.employeeapp.model.User;

public interface UserDao {

void saveUser(User user);


User getUserById(long id);
List<User> getAllUsers();
void updateUser(User user);
void deleteUserById(long id);

File Name: - HiebrnateConf.java


package com.employeeapp.util;
import java.util.Properties;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
Advanced JAVA Programming (4351603) Dhvanit Vara (226170316152)

import com.employeeapp.model.User;
public class HibernateConf {
private static SessionFactory factory;
private HibernateConf() {
}
public static SessionFactory getFactory() {
if (factory == null) {
Configuration configuration = new Configuration();
Properties settings = new Properties();
settings.put("hibernate.connection.driver_class", "com.mysql.cj.jdbc.Driver");
settings.put("hibernate.connection.url", "jdbc:mysql://localhost:3306/StudentDB");
settings.put("hibernate.connection.username", "root");
settings.put("hibernate.connection.password", "Ridham4580");
settings.put("hibernate.dialect", "org.hibernate.dialect.MySQL8Dialect");
settings.put("hibernate.show_sql", "true");
settings.put("hibernate.hbm2ddl.auto", "update");
configuration.setProperties(settings);
configuration.addAnnotatedClass(User.class);
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties())
.build();
factory = configuration.buildSessionFactory(serviceRegistry);
}
return factory;
}
}

File Name: - User.java


package com.employeeapp.model;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
@Entity
@Table(name = "user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private String firstname;
private String lastname;
@Temporal(TemporalType.DATE)
private Date dob;
public User() {
super();
}
public User(String firstname, String lastname, Date dob) {
super();
this.firstname = firstname;
this.lastname = lastname;
this.dob = dob;
}
public long getId() {return id;}
public void setId(long id) {this.id = id;}
public String getFirstname() {return firstname;}
public void setFirstname(String firstname) {this.firstname = firstname;}
Advanced JAVA Programming (4351603) Dhvanit Vara (226170316152)

public String getLastname() {return lastname;}


public void setLastname(String lastname) {this.lastname = lastname;}
public Date getDob() {return dob;}
public void setDob(Date dob) {this.dob = dob;}
@Override
public String toString() {
return "User [id=" + id + ", firstname=" + firstname + ", lastname=" + lastname + ", dob=" + dob + "]";
}
}

File Name: - UserDaolmpl.java


package com.employeeapp.dao;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import com.employeeapp.model.User;
import com.employeeapp.util.HibernateConf;
public class UserDaoImpl implements UserDao {
private SessionFactory factory = HibernateConf.getFactory();
@Override
public void saveUser(User user) {
Transaction transaction = null;
try (Session session = factory.openSession()) {
transaction = session.beginTransaction();
session.persist(user);
transaction.commit();
} catch (Exception e) {
}
}
@Override
public User getUserById(long id) {
Transaction transaction = null;
User user = null;
try (Session session = factory.openSession()) {
transaction = session.beginTransaction();
user = session.get(User.class, id);
transaction.commit();
} catch (Exception e) {

}
return user;
}
@Override
public List<User> getAllUsers() {
Transaction transaction = null;
List<User> users = null;
try (Session session = factory.openSession()) {
transaction = session.beginTransaction();
users = session.createQuery("from User", User.class).getResultList();
transaction.commit();
} catch (Exception e) {

}
return users;
}
@Override
public void updateUser(User user) {
Transaction transaction = null;
try (Session session = factory.openSession()) {
Advanced JAVA Programming (4351603) Dhvanit Vara (226170316152)

transaction = session.beginTransaction();
session.merge(user);
transaction.commit();
} catch (Exception e) {

}
}
@Override
public void deleteUserById(long id) {
Transaction transaction = null;
try (Session session = factory.openSession()) {
transaction = session.beginTransaction();
User user = session.get(User.class, id);
if (user != null) {
session.remove(user);
}
transaction.commit();
} catch (Exception e) {

}
}
}

Output:
Advanced JAVA Programming (4351603) Dhvanit Vara (226170316152)

Assessment-Rubrics

Faculty
Date
Signature
Marks Obtained
Program Total
correctness Implementation Studnet’s
and Presentation engagement in (10)
(4) Methodology practical activities
R1 (3) (3)

R2 R3

Sign with Date


Advanced JAVA Programming (4351603) Dhvanit Vara (226170316152)

Practical – 7: Develop a simple servlet program which maintains a counter


for the number of times it has been accessed since its loading; initialize the
counter using deployment descriptor.

Code:
File Name: - CounterServlet.java
package servlets;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CounterServlet extends HttpServlet {


private int accessCount;
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
accessCount = 0;
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
accessCount++;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h2>Access Count: " + accessCount + "</h2>");
out.println("</body></html>");
}
}

File Name: - index.html


<html>
<head>
<title>Counter</title>
</head>
<body>
<h1>Welcome to the Servlet Counter</h1>
<p>This page serves as the default page for the Servlet Counter example.</p>
<p>To access the counter, go to<a href="CounterServlet">Counter</a>
</p>
</body>
</html>

File Name: - web.xml


Advanced JAVA Programming (4351603) Dhvanit Vara (226170316152)

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


<web-app>
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>CounterServlet</servlet-name>
<servlet-class>servlets.CounterServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CounterServlet</servlet-name>
<url-pattern>/CounterServlet</url-pattern>
</servlet-mapping>
</web-app>

Add this dependency in pom.xml

<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>

Output:
Advanced JAVA Programming (4351603) Dhvanit Vara (226170316152)

Assessment-Rubrics

Faculty
Date
Signature
Marks Obtained
Program Total
correctness Implementation Studnet’s
and Presentation engagement in (10)
(4) Methodology practical activities
R1 (3) (3)

R2 R3

Sign with Date


Advanced JAVA Programming (4351603) Dhvanit Vara (226170316152)

Practical 8: Create a web form which processes servlet and demonstrates


use of cookies and sessions.
File Name: - practical8.java

Code:
package servlets;
import java.io.IOException;
import javax.servlet.ServletException;
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 practical8 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
HttpSession session = request.getSession();
session.setAttribute("username", username);
session.setAttribute("password", password);
Cookie usernameCookie = new Cookie("username", username);
usernameCookie.setMaxAge(3600);
response.addCookie(usernameCookie);
response.sendRedirect("result.jsp");
}
}

File Name: - index.html

<!DOCTYPE html>
<html>
<head><title>Registration Form</title></head>
<body>
<h1>Registration Form</h1>
<form action="practical8" method="POST">
<label for="username">Username:</label>
<input type="text" name="username" required /><br />
<label for="password">Password:</label>
<input type="password" name="password" required /><br />
<input type="submit" value="Register" />
</form>
</body>
</html>
File Name: - result.jsp

<!DOCTYPE html>
<html>
<head>
<title>Registration Successful</title>
</head>
<body>
Advanced JAVA Programming (4351603) Dhvanit Vara (226170316152)

<h1>Registration Successful</h1>
<p>Thank you for registering, ${sessionScope.username}!</p>
<p>Your username is also stored in a cookie.</p>
</body>
</html>

File Name: - web.xml

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


<web-app>
<display-name>session</display-name>
<servlet>
<servlet-name>practical8</servlet-name>
<servlet-class>servlets.practical8</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>practical8</servlet-name>
<url-pattern>/practical8</url-pattern>
</servlet-mapping>
</web-app>

Output:
Advanced JAVA Programming (4351603) Dhvanit Vara (226170316152)

Assessment-Rubrics

Faculty
Date
Signature
Marks Obtained
Program Total
correctness Implementation Studnet’s
and Presentation engagement in (10)
(4) Methodology practical activities
R1 (3) (3)

R2 R3

Sign with Date


Advanced JAVA Programming (4351603) Dhvanit Vara (226170316152)

Practical 9: Develop a web form which processes servlet for user login functionality.

Code:
File Name: - practical9.java
package servlets;
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 practical9 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
if (username.equals("Manav") && password.equals("saliya123")) {
HttpSession session = request.getSession();
session.setAttribute("username", username);
response.sendRedirect("welcome.jsp");
} else {
response.sendRedirect("index.html");
}
}
}

File Name: - index.html


<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<h2>Login</h2>
<form action="practical9" method="post">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required>
<input type="submit" value="Login" />
</form>
</body>
</html>
File Name: - welcome.jsp
<!DOCTYPE html>
<html>
<head><title>Welcome Page</title></head>
<body><h2>Welcome, <%= session.getAttribute("username") %></h2></body>
</html>
Advanced JAVA Programming (4351603) Dhvanit Vara (226170316152)

File Name: - web.xml


<servlet>
<servlet-name>practical9</servlet-name>
<servlet-class>servlets.practical9</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>practical9</servlet-name>
<url-pattern>/practical9</url-pattern>
</servlet-mapping>

Output:
Advanced JAVA Programming (4351603) Dhvanit Vara (226170316152)

Assessment-Rubrics

Faculty
Date
Signature
Marks Obtained
Program Total
correctness Implementation Studnet’s
and Presentation engagement in (10)
(4) Methodology practical activities
R1 (3) (3)

R2 R3

Sign with Date


AJP Dhvanit Vara (226170316152)

Practical 10: Develop a JSP web application to display student monthly


attendance in each subject of current semester via enrollment number.

Code:
AJP Dhvanit Vara (226170316152)
AJP Dhvanit Vara (226170316152)

Assessment-Rubrics

Faculty
Date
Signature
Marks Obtained
Program Total
correctness Implementation Studnet’s
and Presentation engagement in (10)
(4) Methodology practical activities
R1 (3) (3)

R2 R3

Sign with Date


AJP Dhvanit Vara (226170316152)

Practical 11: Develop a JSP web application to select shopping products,


buy any products and product billing page using session management.

Code:
AJP Dhvanit Vara (226170316152)
AJP Dhvanit Vara (226170316152)
AJP Dhvanit Vara (226170316152)
AJP Dhvanit Vara (226170316152)
AJP Dhvanit Vara (226170316152)

Output:
Index.jsp

Product.jsp

Cart.jsp
AJP Dhvanit Vara (226170316152)

Billing.jsp

Logout.jsp
AJP Dhvanit Vara (226170316152)

Assessment-Rubrics

Faculty
Date
Signature
Marks Obtained
Program Total
correctness Implementation Studnet’s
and Presentation engagement in (10)
(4) Methodology practical activities
R1 (3) (3)

R2 R3

Sign with Date


AJP Dhvanit Vara (226170316152)

Practical 12: Develop a JSP program for student registration for new
admission in college and display stored data it into admin dashboard.

Code:
AJP Dhvanit Vara (226170316152)
AJP Dhvanit Vara (226170316152)
AJP Dhvanit Vara (226170316152)

Output:
registration.jsp

registered.jsp
AJP Dhvanit Vara (226170316152)

admin.jsp
AJP Dhvanit Vara (226170316152)

Assessment-Rubrics

Faculty
Date
Signature
Marks Obtained
Program Total
correctness Implementation Studnet’s
and Presentation engagement in (10)
(4) Methodology practical activities
R1 (3) (3)

R2 R3

Sign with Date


AJP Dhvanit Vara (226170316152)

Practical 13: Develop a Web MVC Architecture based application to provide


user Login and Register using Spring Boot.
AJP Dhvanit Vara (226170316152)
AJP Dhvanit Vara (226170316152)
AJP Dhvanit Vara (226170316152)

Output:
AJP Dhvanit Vara (226170316152)

Assessment-Rubrics

Faculty
Date
Signature
Marks Obtained
Program Total
correctness Implementation Studnet’s
and Presentation engagement in (10)
(4) Methodology practical activities
R1 (3) (3)

R2 R3

Sign with Date

You might also like