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

Jsp Lop Solved All

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)
8 views

Jsp Lop Solved All

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/ 35

VIVEKANANDA INSTITUTE OF PROFESSIONAL STUDIES -

TECHNICAL CAMPUS

VIVEKANANDA SCHOOL OF INFORMATION TECHNOLOGY

BACHELOR OF COMPUTER APPLICATION


WEB DEVELOPMENT WITH JAVA & JSP
BCA 315

Guru Gobind Singh Indraprastha University


Sector-16C. Dwarka, Delhi-110078

SUBMITTED TO: SUBMITTED BY:


Dr. Alpana Chawla Rahul Singh
Assistant Professor 13817702022
VSIT BCA 5C
Index
S.NO. Practicals Sign
Create a webpage that prints your name to the screen,
1 print your name in Tahoma font, print a definition list with
5 items. Create links to 5 different web pages etc.

2 Program to demonstrate Swing components

3 Configure Apache Tomcat and write a Hello World JSP.

Write a java program that connects to a database using


4
JDBC and does add, delete and retrieve operations.

5 Create and Develop a web application using JSF.

Write a program to implement Java Beans to set and get


6
values.

Create a Java application to demonstrate Socket


7
Programming in Java.

Write a program to retrieve hostname using methods in


8
Inetaddress class

Write a client-server program which displays the server


9
machine’s date and time on the client machine.

Create a table in the database containing the columns to


store book details like: name, authors, desc, price and url.
10
Using JSP and JDBC retrieve the details in the table and
display them on the webpage.

Write a program to create a login page using Java Beans.


11 Also validate the username and password from the
database.

Create a form for inputting text and uploading images


12
using struts.

13 Create a student registration form using Hibernate.

Write a program to implement MVC using Spring


14
framework.
1. Create a webpage that prints your name to the screen, print
your name in Tahoma font, print a definition list with 5
items. Create links to 5 different web pages etc.

<!DOCTYPE html>
<html>
<head>
<title>My Web Page</title>
<style>
body {
font-family: Tahoma, sans-serif;
}
</style>
</head>
<body>
<h1>Rahul singh</h1>

<h2>Definition List</h2>
<dl>
<dt>Item 1</dt>
<dd>Definition for Item 1</dd>

<dt>Item 2</dt>
<dd>Definition for Item 2</dd>

<dt>Item 3</dt>
<dd>Definition for Item 3</dd>

<dt>Item 4</dt>
<dd>Definition for Item 4</dd>

<dt>Item 5</dt>
<dd>Definition for Item 5</dd>
</dl>

<h2>Links</h2>
<ul>
<li><a href="https://www.example1.com">Example Link 1</a></li>
<li><a href="https://www.example2.com">Example Link 2</a></li>
<li><a href="https://www.example3.com">Example Link 3</a></li>
<li><a href="https://www.example4.com">Example Link 4</a></li>
<li><a href="https://www.example5.com">Example Link 5</a></li>
</ul>
</body>
</html>
Output:
2. Program to demonstrate Swing components.
.
Swing.java
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JLabel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class SwingAppletDemo extends JApplet {


private JLabel label;
@Override
public void init() {
label = new JLabel("Hello from Swing!");
JButton button = new JButton("Click me");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
label.setText("Button Clicked!");
}
});
add(label);
add(button);
}
}

SwingAppletDemo.html
<!DOCTYPE html>
<html>
<head>
<title>Swing Applet Demo</title>
</head>
<body>
<applet code="SwingAppletDemo.class" width="400" height="300">
Your browser does not support Java applets.
</applet>
</body>
</html>
3. Configure Apache Tomcat and write a Hello World JSP page.

HelloWorld.jsp

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


pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello World JSP</title>
</head>
<body>
<h1>Hello world</h1>
</body>
</html>

Output:
4. Write a java program that connects to a database using
JDBC and does add, delete and retrieve operations.

AddUser.java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class AddUser {
private static final String JDBC_URL = "jdbc:mysql://localhost:3306/testdb";
private static final String USERNAME = "your_username";
private static final String PASSWORD = "your_password";
public static void main(String[] args) {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection = DriverManager.getConnection(JDBC_URL,
USERNAME, PASSWORD);
addUser(connection, "JohnDoe", "[email protected]");
connection.close();
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
private static void addUser(Connection connection, String username, String email)
throws SQLException {
String insertQuery = "INSERT INTO users (username, email) VALUES (?, ?)";
try (PreparedStatement preparedStatement =
connection.prepareStatement(insertQuery)) {
preparedStatement.setString(1, username);
preparedStatement.setString(2, email);
preparedStatement.executeUpdate();
System.out.println("User added successfully");
}
}
}
RetrieveUsers.java
public class RetrieveUsers {
private static final String JDBC_URL = "jdbc:mysql://localhost:3306/testdb";
private static final String USERNAME = "your_username";
private static final String PASSWORD = "your_password";
public static void main(String[] args) {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection = DriverManager.getConnection(JDBC_URL,
USERNAME, PASSWORD);
retrieveUsers(connection);
connection.close();
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
private static void retrieveUsers(Connection connection) throws SQLException {
String selectQuery = "SELECT * FROM users";
try (Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(selectQuery)) {
System.out.println("Users in the database:");
while (resultSet.next()) {
int id = resultSet.getInt("id");
String username = resultSet.getString("username");
String email = resultSet.getString("email");
System.out.println("ID: " + id + ", Username: " + username + ", Email: " +
email);
}
System.out.println();
}
}
}
DeleteUser.java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class DeleteUser {
private static final String JDBC_URL = "jdbc:mysql://localhost:3306/testdb";
private static final String USERNAME = "your_username";
private static final String PASSWORD = "your_password";
public static void main(String[] args) {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection = DriverManager.getConnection(JDBC_URL,
USERNAME, PASSWORD);
deleteUser(connection, "JohnDoe");
connection.close();
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
private static void deleteUser(Connection connection, String username) throws
SQLException {
String deleteQuery = "DELETE FROM users WHERE username = ?";
try (PreparedStatement preparedStatement =
connection.prepareStatement(deleteQuery)) {
preparedStatement.setString(1, username);
int rowsAffected = preparedStatement.executeUpdate();
if (rowsAffected > 0) {
System.out.println("User deleted successfully");
} else {
System.out.println("User not found");
}
}
}
}
Output:
Add user

rahul

Retrieve user

Delete user
5. Create and Develop a web application using JSF.

Creating Managed Bean


package com.example;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
@ManagedBean
@SessionScoped
public class HelloBean {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGreeting() {
return "Hello, " + name + "!";
}
}

Creating XHTML page


<!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">
<h:head>
<title>JSF Hello World</title>
</h:head>
<h:body>
<h:form>
<h:outputLabel for="name">Enter your name: </h:outputLabel>
<h:inputText id="name" value="#{helloBean.name}" />
<br/>
<h:commandButton value="Say Hello" action="#{helloBean.getGreeting}" />
<br/>
<h:outputText value="#{helloBean.greeting}" rendered="#{not empty
helloBean.greeting}" />
</h:form>
</h:body>
</html>

Configuring 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_3_1.xsd"
version="3.1">
<display-name>SimpleJSFApp</display-name>
<welcome-file-list>
<welcome-file>faces/index.xhtml</welcome-file>
</welcome-file-list>
</web-app>

Output:
6. Write a program to implement Java Beans to set and get
values.

PersonBean.java
import java.io.Serializable;
public class PersonBean implements Serializable {
private String firstName;
private String lastName;
private int age;
public PersonBean() {
// Default constructor required for a JavaBean
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getAge() {
return age;
}

public void setAge(int age) {


this.age = age;
}
}
TestPersonBean.java
public class TestPersonBean {
public static void main(String[] args) {
PersonBean person = new PersonBean();
person.setFirstName("Parveen");
person.setLastName("Rikhari");
person.setAge(20);
System.out.println("First Name: " + person.getFirstName());
System.out.println("Last Name: " + person.getLastName());
System.out.println("Age: " + person.getAge());
}
}

Output:
7. Create a Java application to demonstrate Socket
Programming in Java.
ServerSocket.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class ServerSocketExample {
public static void main(String[] args) {
final int PORT = 8080;
try (ServerSocket serverSocket = new ServerSocket(PORT)) {
System.out.println("Server is listening on port " + PORT);
Socket clientSocket = serverSocket.accept();
System.out.println("Client connected: " +
clientSocket.getInetAddress().getHostAddress());
BufferedReader reader = new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
PrintWriter writer = new PrintWriter(clientSocket.getOutputStream(), true);
String clientMessage = reader.readLine();
System.out.println("Client says: " + clientMessage);
String response = "Hello, Client!";
writer.println(response);
System.out.println("Server responds: " + response);
} catch (IOException e) {
e.printStackTrace();
}
}
}

ClientSocket.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class ClientSocketExample {


public static void main(String[] args) {
final String SERVER_ADDRESS = "localhost";
final int PORT = 8080;
try (Socket socket = new Socket(SERVER_ADDRESS, PORT)) {
System.out.println("Connected to server: " + SERVER_ADDRESS + ":" +
PORT);
BufferedReader reader = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
String message = "Hello, Server!";
writer.println(message);
System.out.println("Client sends: " + message);
String serverResponse = reader.readLine();
System.out.println("Server says: " + serverResponse);

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

Output
8. Write a program to retrieve hostname using methods in
Inetaddress class.
GetHostname.java
import java.net.InetAddress;
import java.net.UnknownHostException;
public class GetHostname {
public static void main(String[] args) {
try {
InetAddress localHost = InetAddress.getLocalHost();
System.out.println("Local Hostname: " + localHost.getHostName());
String ipAddress = "8.8.8.8"; // Google's public DNS server IP
InetAddress googleDNS = InetAddress.getByName(ipAddress);
System.out.println("Hostname for " + ipAddress + ": " +
googleDNS.getHostName());
}
catch (UnknownHostException e) {
e.printStackTrace();
}
}
}

Output
9. Write a client-server program which displays the server
machine’s date and time on the client machine.
ServerDateTime.java
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;
public class ServerDateTime {
public static void main(String[] args) {
final int PORT = 12345;
try (ServerSocket serverSocket = new ServerSocket(PORT)) {
System.out.println("Server is listening on port " + PORT);
while (true) {
Socket clientSocket = serverSocket.accept();
System.out.println("Client connected: " +
clientSocket.getInetAddress().getHostAddress());
PrintWriter writer = new PrintWriter(clientSocket.getOutputStream(), true);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd
HH:mm:ss");
String dateTime = dateFormat.format(new Date());
writer.println(dateTime);
clientSocket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

ClientDateTime.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
public class ClientDateTime {
public static void main(String[] args) {
final String SERVER_ADDRESS = "localhost";
final int PORT = 12345;
try (Socket socket = new Socket(SERVER_ADDRESS, PORT)) {
System.out.println("Connected to server: " + SERVER_ADDRESS + ":" +
PORT);
BufferedReader reader = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
String serverDateTime = reader.readLine();
System.out.println("Server date and time: " + serverDateTime);
} catch (IOException e) {
e.printStackTrace();
}
}
}

Output
10. Create a table in the database containing the columns to
store book details like: name, authors, desc, price and url.
Using JSP and JDBC retrieve the details in the table and
display them on the webpage.
Book.java(java bean)
import java.io.Serializable;
public class Book implements Serializable {
private static final long serialVersionUID = 1L;
private int id;
private String name;
private String authors;
private String description;
private double price;
private String url;
public Book() {
// Default constructor
}
public Book(String name, String authors, String description, double price, String url)
{
this.name = name;
this.authors = authors;
this.description = description;
this.price = price;
this.url = url;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthors() {
return authors;
}
public void setAuthors(String authors) {
this.authors = authors;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
@Override
public String toString() {
return "Book{" +
"id=" + id +
", name='" + name + '\'' +
", authors='" + authors + '\'' +
", description='" + description + '\'' +
", price=" + price +
", url='" + url + '\'' +
'}';
}
}
DatabaseConnector.java
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class DatabaseConnector {
private static final String JDBC_URL = "jdbc:mysql://localhost:3306/bookstore";
private static final String USERNAME = "root";
private static final String PASSWORD = "root";
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(JDBC_URL, USERNAME, PASSWORD);
}
public static List<Book> getAllBooks() {
List<Book> books = new ArrayList<>();
try (Connection connection = getConnection();
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT * FROM books")) {
while (resultSet.next()) {
Book book = new Book();
book.setId(resultSet.getInt("id"));
book.setName(resultSet.getString("name"));
book.setAuthors(resultSet.getString("authors"));
book.setDescription(resultSet.getString("description"));
book.setPrice(resultSet.getDouble("price"));
book.setUrl(resultSet.getString("url"));
books.add(book);
}
} catch (SQLException e) {
e.printStackTrace();
}
return books;
}
}
DisplayBooks.jsp
<%@ page import="java.util.List" %>
<%@ page import="Book" %>
<%@ page import="DatabaseConnector" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Book Details</title>
</head>
<body>
<h2>Book Details</h2>
<table border="1">
<tr>
<th>ID</th>
<th>Name</th>
<th>Authors</th>
<th>Description</th>
<th>Price</th>
<th>URL</th>
</tr>
<% List<Book> books = DatabaseConnector.getAllBooks();
for (Book book : books) { %>
<tr>
<td><%= book.getId() %></td>
<td><%= book.getName() %></td>
<td><%= book.getAuthors() %></td>
<td><%= book.getDescription() %></td>
<td><%= book.getPrice() %></td>
<td><a href="<%= book.getUrl() %>">Link</a></td>
</tr>
<% } %>
</table>
</body>
</html>
Output
11. Write a program to create a login page using Java Beans.
Also validate the username and password from the
database.
UserAuthenticationBean.java
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class UserAuthenticationBean {
private String username;
private String password;
public UserAuthenticationBean() {
// Default constructor
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public boolean validateUser() {
try (Connection connection = DatabaseConnector.getConnection()) {
String sql = "SELECT * FROM users WHERE username = ? AND password = ?";
try (PreparedStatement preparedStatement =
connection.prepareStatement(sql)) {
preparedStatement.setString(1, username);
preparedStatement.setString(2, password);
try (ResultSet resultSet = preparedStatement.executeQuery()) {
return resultSet.next();
}
}
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}
}

Login.jsp
<%@ page import="UserAuthenticationBean" %>
<%@ page import="DatabaseConnector" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Login</title>
</head>
<body>
<h2>Login</h2>
<form method="post" action="login.jsp">
Username: <input type="text" name="username" required><br>
Password: <input type="password" name="password" required><br>
<input type="submit" value="Login">
</form>
<%
String username = request.getParameter("username");
String password = request.getParameter("password");
if (username != null && password != null) {
UserAuthenticationBean userBean = new UserAuthenticationBean();
userBean.setUsername(username);
userBean.setPassword(password);
if (userBean.validateUser()) {
out.println("<p>LoggedIn successfullly !!</p>");
} else {
out.println("<p>Invalid username or password. Please try again.</p>");
}
}
%>
</body>
</html>
DatabaseConnector.java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DatabaseConnector {
private static final String JDBC_URL = "jdbc:mysql://localhost:3306/userdb";
private static final String USERNAME = "root";
private static final String PASSWORD = "";
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(JDBC_URL, USERNAME, PASSWORD);
}
}

Output
12. Create a form for inputting text and uploading images
using struts.
ImageForm.java
package com.example.forms;
import org.apache.struts.action.ActionForm;
import org.apache.struts.upload.FormFile;
public class ImageForm extends ActionForm {
private String textData;
private FormFile imageFile;
public String getTextData() {
return textData;
}
public void setTextData(String textData) {
this.textData = textData;
}
public FormFile getImageFile() {
return imageFile;
}
public void setImageFile(FormFile imageFile) {
this.imageFile = imageFile;
}
}

struts-config.xml
<form-beans>
<form-bean name="imageForm" type="com.example.forms.ImageForm" />
</form-beans>
<action-mappings>
<action path="/upload" type="com.example.actions.UploadAction"
name="imageForm" scope="request">
<forward name="success" path="/success.jsp" />
<forward name="failure" path="/failure.jsp" />
</action>
</action-mappings>

UploadAction.java
package com.example.actions;
import org.apache.struts.action.*;
import javax.servlet.http.*;
import java.io.*;
public class UploadAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
try {
String textData = ((ImageForm) form).getTextData();
FormFile imageFile = ((ImageForm) form).getImageFile();
String fileName = imageFile.getFileName();
InputStream inputStream = imageFile.getInputStream();
String uploadDir = request.getServletContext().getRealPath("/") + "uploads/";
File fileSaveDir = new File(uploadDir);
if (!fileSaveDir.exists()) {
fileSaveDir.mkdirs();
}
String uniqueFileName = System.currentTimeMillis() + "_" + fileName;
String filePath = uploadDir + File.separator + uniqueFileName;
try (OutputStream outputStream = new FileOutputStream(filePath)) {
int bytesRead;
byte[] buffer = new byte[4096];
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
}
return mapping.findForward("success");
} catch (Exception e) {
e.printStackTrace();
return mapping.findForward("failure");
}
}
}

uploadForm.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
<html>
<head>
<title>Image Upload Form</title>
</head>
<body>
<html:form action="/upload" enctype="multipart/form-data">
<html:text property="textData" />
<html:file property="imageFile" />
<html:submit value="Upload" />
</html:form>
</body>
</html>

success.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<html>
<head>
<title>Upload Successful</title>
</head>
<body>
<h2>Upload Successful!</h2>
</body>
</html>

failure.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<html>
<body>
<h2>Upload Failed!</h2>
</body>
</html>

Output
13. Create a student registration form using Hibernate.
hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD
3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<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>
<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>
<property
name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<mapping class="com.example.Student"/>
</hibernate-configuration>

Student.java(Model)
package com.example;
import javax.persistence.*;
@Entity
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String firstName;
private String lastName;
private String email;
public Student() {
}
public Student(String firstName, String lastName, String email) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}

StudentDAO.java
package com.example.dao;
import com.example.Student;
import org.hibernate.*;
public class StudentDAO {
private static final SessionFactory sessionFactory;
static {
try {
Configuration configuration = new Configuration();
configuration.configure("hibernate.cfg.xml");
sessionFactory = configuration.buildSessionFactory();
} catch (Throwable ex) {
throw new ExceptionInInitializerError(ex);
}
}
public void saveStudent(Student student) {
Session session = sessionFactory.openSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
session.save(student);
transaction.commit();
} catch (Exception e) {
if (transaction != null) {
transaction.rollback();
}
e.printStackTrace();
} finally {
session.close();
}
}
}

StudentServlet.java
package com.example.servlet;
import com.example.Student;
import com.example.dao.StudentDAO;
import javax.servlet.*;
import java.io.IOException;
@WebServlet("/register")
public class StudentServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
String firstName = request.getParameter("firstName");
String lastName = request.getParameter("lastName");
String email = request.getParameter("email");
Student student = new Student(firstName, lastName, email);
StudentDAO studentDAO = new StudentDAO();
studentDAO.saveStudent(student);
response.sendRedirect(request.getContextPath() + "/success.jsp");
} catch (Exception e) {
e.printStackTrace();
request.setAttribute("errorMessage", "Registration failed. Please try again.");
request.getRequestDispatcher("/failure.jsp").forward(request, response);
}
}
}

Html form
<!-- registration-form.jsp -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Student Registration Form</title>
</head>
<body>
<form action="/your-web-app-context/register" method="post">
<label for="firstName">First Name:</label>
<input type="text" id="firstName" name="firstName" required><br>
<label for="lastName">Last Name:</label>
<input type="text" id="lastName" name="lastName" required><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required><br>
<input type="submit" value="Register">
</form>
</body>
</html>
OUTPUT:

You might also like