[Go to site: main page, start]

0% found this document useful (0 votes)
3 views60 pages

Java Server Pages

Java Server Pages (JSP) is a server-side technology that enables the creation of dynamic web pages by embedding Java code into HTML, commonly used in Java EE applications. It includes a lifecycle with phases such as translation, compilation, initialization, execution, and destruction, along with directives, scripting elements, implicit objects, and standard actions for enhanced functionality. JSP also supports error handling, JDBC for database interactions, and follows MVC architecture for better code organization.

Uploaded by

jw8018248
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)
3 views60 pages

Java Server Pages

Java Server Pages (JSP) is a server-side technology that enables the creation of dynamic web pages by embedding Java code into HTML, commonly used in Java EE applications. It includes a lifecycle with phases such as translation, compilation, initialization, execution, and destruction, along with directives, scripting elements, implicit objects, and standard actions for enhanced functionality. JSP also supports error handling, JDBC for database interactions, and follows MVC architecture for better code organization.

Uploaded by

jw8018248
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

Java Server Pages (JSP) - Detailed Explanation

JSP is a server-side technology that allows developers to create dynamic web pages by embedding
Java code into HTML. It is widely used in Java EE (Jakarta EE) web applications for handling UI
rendering while keeping the business logic in Servlets.

1. JSP Life Cycle

A JSP page goes through the following phases in its lifecycle:

1. Translation Phase → The JSP file is converted into a Servlet.

2. Compilation Phase → The generated Servlet is compiled into a .class file.

3. Initialization Phase → jspInit() is called (like init() in Servlets).

4. Execution Phase → jspService(request, response) is called for every request.

5. Destruction Phase → jspDestroy() is called when the JSP is removed from memory.

Lifecycle Example

java

CopyEdit

<%! public void jspInit() {

[Link]("JSP Initialized");

} %>

<% [Link]("JSP Service Called"); %>

<%! public void jspDestroy() {

[Link]("JSP Destroyed");

} %>

Execution Flow:

1. First request → jspInit() is called.

2. Every request → jspService() is executed.

3. When the server stops or the JSP is removed → jspDestroy() is executed.


2. JSP Directives

JSP directives provide global settings for the JSP page. These are defined using <%@ directive %>.

Types of JSP Directives

1. Page Directive

o Defines page-level settings like scripting language, error handling, and import
statements.

o Syntax:

jsp

CopyEdit

<%@ page language="java" contentType="text/html" %>

<%@ page import="[Link].*, [Link].*" %>

<%@ page errorPage="[Link]" %>

2. Include Directive

o Includes static content from another file at translation time.

o Syntax:

jsp

CopyEdit

<%@ include file="[Link]" %>

o Example:

 [Link] contains:

html

CopyEdit

<h1>Welcome to My Website</h1>

 [Link] includes it using:

jsp

CopyEdit

<%@ include file="[Link]" %>

<p>This is the home page.</p>


3. Taglib Directive

o Used for importing custom tag libraries (JSTL, custom tags).

o Example for JSTL (Java Standard Tag Library):

jsp

CopyEdit

<%@ taglib uri="[Link] prefix="c" %>

3. JSP Scripting Elements

JSP allows embedding Java code using scripting elements.

1. Declarations (<%! ... %>)

o Used to declare variables and methods.

jsp

CopyEdit

<%! int count = 0; %>

<%! public int getValue() { return count++; } %>

2. Scriptlets (<% ... %>)

o Used to write Java code inside JSP.

jsp

CopyEdit

<% count++; %>

<p>Count: <%= count %></p>

3. Expressions (<%= ... %>)

o Used to output values directly in HTML.

jsp

CopyEdit

<p>Current Value: <%= getValue() %></p>

4. Comments (<%-- ... --%>)

o Used for JSP comments (not visible in the generated HTML).


jsp

CopyEdit

<%-- This is a comment --%>

4. JSP Implicit Objects

JSP provides nine built-in objects that can be used without declaring them.

Object Description

request Represents the HTTP request (from HttpServletRequest).

response Represents the HTTP response (from HttpServletResponse).

session Represents the user session (HttpSession).

application Represents application-wide data (ServletContext).

out Writes output to the response (JspWriter).

config Represents the Servlet configuration (ServletConfig).

pageContext Provides context information for the page.

page Refers to the current JSP page (similar to this).

exception Captures exceptions (only in error pages).

Example Using Implicit Objects

jsp

CopyEdit

<p>Session ID: <%= [Link]() %></p>

<p>Application Name: <%= [Link]() %></p>

<p>Client IP: <%= [Link]() %></p>

5. JSP Standard Actions

JSP actions are XML-style tags that perform specific tasks like including files, forwarding requests,
and managing JavaBeans.
Action Purpose Syntax

<jsp:include> Includes another JSP file dynamically. <jsp:include page="[Link]"/>

<jsp:forward
<jsp:forward> Forwards the request to another page.
page="[Link]"/>

<jsp:useBean id="user"
<jsp:useBean> Creates a JavaBean. class="[Link]"
scope="session"/>

<jsp:setProperty name="user"
<jsp:setProperty> Sets a property in a JavaBean.
property="name" value="John"/>

<jsp:getProperty name="user"
<jsp:getProperty> Retrieves a property from a JavaBean.
property="name"/>

6. JSP Exception Handling

JSP allows error handling using the errorPage and isErrorPage attributes.

Example

1. Main Page ([Link])

<%@ page errorPage="[Link]" %>

<%

int num = 10 / 0; // This will cause an error

%>

2. Error Page ([Link])

<%@ page isErrorPage="true" %>

<h2>An error occurred: <%= [Link]() %></h2>

7. JSP with JDBC (Database Connection Example)

JSP can interact with databases using JDBC.

Example: Fetching Data from MySQL


<%@ page import="[Link].*" %>

<%

Connection conn = null;

Statement stmt = null;

ResultSet rs = null;

try {

[Link]("[Link]");

conn = [Link]("jdbc:mysql://localhost:3306/testdb", "root",


"password");

stmt = [Link]();

rs = [Link]("SELECT * FROM users");

while ([Link]()) {

[Link]("<p>User: " + [Link]("name") + "</p>");

} catch (Exception e) {

[Link]("Error: " + [Link]());

} finally {

if (rs != null) [Link]();

if (stmt != null) [Link]();

if (conn != null) [Link]();

%>

Conclusion

 JSP is used for dynamic web content and is an extension of Servlets.

 It provides scripting elements, implicit objects, actions, and error handling.


 JSP works well with JDBC for database connections and JSTL for reusable tags.

 It is often combined with Servlets in MVC architecture.

1. JSP Life Cycle Example with Output

Example: Tracking JSP Lifecycle

This example logs messages when the JSP is initialized, executed, and destroyed.

Code: [Link]

jsp

CopyEdit

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

<html>

<head><title>JSP Lifecycle Example</title></head>

<body>

<h2>JSP Lifecycle Example</h2>

<%!

// Runs only once when JSP is initialized

public void jspInit() {

[Link]("JSP Initialized");

%>

<%

// Runs every time the page is requested

[Link]("JSP Service Executed");

%>

<%!
// Runs when JSP is removed from memory

public void jspDestroy() {

[Link]("JSP Destroyed");

%>

</body>

</html>

Expected Output (Browser View)

JSP Lifecycle Example


(No visible change, but logs will appear in the server console)

Console Output

pgsql

CopyEdit

JSP Initialized

JSP Service Executed

JSP Service Executed (on each request)

JSP Destroyed (when the server stops)

2. JSP Scripting Example

Example: Using Scriptlets, Declarations, and Expressions

This example demonstrates the use of JSP scripting elements.

Code: [Link]

jsp

CopyEdit

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

<html>

<head><title>JSP Scripting Example</title></head>


<body>

<h2>JSP Scripting Example</h2>

<%! int count = 0; %> <!-- Declaration -->

<% count++; %> <!-- Scriptlet -->

<p>Page accessed <%= count %> times.</p> <!-- Expression -->

</body>

</html>

Expected Output (Browser View)

Each time you refresh the page, the count will increase.

JSP Scripting Example


Page accessed 1 times.
(Refresh...)
Page accessed 2 times.

3. JSP Implicit Objects Example

Example: Displaying Request & Session Data

This example demonstrates how to use JSP implicit objects.

Code: implicit_objects.jsp

jsp

CopyEdit

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

<html>

<head><title>JSP Implicit Objects Example</title></head>

<body>

<h2>JSP Implicit Objects Example</h2>


<p>Client IP: <%= [Link]() %></p>

<p>Session ID: <%= [Link]() %></p>

<p>Server Info: <%= [Link]() %></p>

</body>

</html>

Expected Output (Browser View)

JSP Implicit Objects Example


Client IP: [Link]
Session ID: A1B2C3D4E5F6G7H8
Server Info: Apache Tomcat/9.0

4. JSP Form Handling Example

Example: Processing User Input

This example captures user input from a form and displays it on another JSP page.

Code: [Link] (Input Page)

jsp

CopyEdit

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

<html>

<head><title>JSP Form Example</title></head>

<body>

<h2>Enter Your Details</h2>

<form action="[Link]" method="post">

Name: <input type="text" name="username"><br>

Age: <input type="number" name="age"><br>

<input type="submit" value="Submit">

</form>
</body>

</html>

Code: [Link] (Processing Page)

jsp

CopyEdit

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

<html>

<head><title>Form Processing</title></head>

<body>

<h2>Form Submission Result</h2>

<p>Name: <%= [Link]("username") %></p>

<p>Age: <%= [Link]("age") %></p>

</body>

</html>

Expected Output (User Interaction)

1. User enters details:

o Name: John

o Age: 25

o Clicks Submit

2. Browser displays:

Form Submission Result


Name: John
Age: 25

5. JSP and Database (JDBC) Example

Example: Fetching Data from MySQL

This example connects JSP with MySQL to retrieve user data.


Database Table (users)

ID Name Email

1 Alice alice@[Link]

2 Bob bob@[Link]

Code: [Link]

<%@ page import="[Link].*" %>

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

<html>

<head><title>JSP Database Example</title></head>

<body>

<h2>User List</h2>

<%

Connection conn = null;

Statement stmt = null;

ResultSet rs = null;

try {

[Link]("[Link]");

conn = [Link]("jdbc:mysql://localhost:3306/testdb", "root",


"password");

stmt = [Link]();

rs = [Link]("SELECT * FROM users");

while ([Link]()) {

[Link]("<p>" + [Link]("id") + " - " + [Link]("name") + " (" +


[Link]("email") + ")</p>");

}
} catch (Exception e) {

[Link]("Error: " + [Link]());

} finally {

if (rs != null) [Link]();

if (stmt != null) [Link]();

if (conn != null) [Link]();

%>

</body>

</html>

Expected Output (Browser View)

User List
1 - Alice (alice@[Link])
2 - Bob (bob@[Link])

6. JSP Forwarding Example

Example: Redirecting Requests

This example forwards the request to another page.

Code: [Link]

jsp

CopyEdit

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

<jsp:forward page="[Link]" />

Code: [Link]

jsp

CopyEdit

<html>

<head><title>Forwarded Page</title></head>
<body>

<h2>You have been forwarded here!</h2>

</body>

</html>

Expected Behavior

Accessing [Link] will automatically redirect to [Link].

1. JSP Execution Flow (With Image)

Before diving into advanced topics, let’s visualize how JSP works behind the scenes.

JSP Execution Flow Diagram

I'll generate an image to illustrate the JSP request processing cycle.

Image created
Rate this image

Here is the JSP execution flow diagram. Now, let's move on to advanced JSP examples like JSTL,
MVC, and Session Management.

2. JSP with JSTL (JavaServer Pages Standard Tag Library)

JSTL helps in writing cleaner and more readable JSP pages without scriptlets.

Example: Iterating Over a List Using JSTL

We will display a list of names dynamically using JSTL.

Code: jstl_example.jsp

jsp

CopyEdit

<%@ taglib uri="[Link] prefix="c" %>

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

<html>

<head><title>JSTL Example</title></head>

<body>

<h2>JSTL Iteration Example</h2>

<%

String[] names = {"Alice", "Bob", "Charlie"};

[Link]("nameList", names);

%>

<ul>

<c:forEach var="name" items="${nameList}">

<li>${name}</li>

</c:forEach>

</ul>
</body>

</html>

Expected Output (Browser View)

JSTL Iteration Example

 Alice

 Bob

 Charlie

JSTL simplifies JSP by eliminating Java code from JSP files.

3. JSP MVC Architecture

JSP follows MVC (Model-View-Controller) architecture for better code organization.

Example: MVC Structure

 [Link] → View (User Input)

 [Link] → Controller (Processes Logic)

 [Link] → View (Displays Data)

Code: [Link] (View - Input Form)

jsp

CopyEdit

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

<html>

<head><title>MVC Example</title></head>

<body>

<h2>Enter Your Name</h2>

<form action="ControllerServlet" method="post">

<input type="text" name="username">

<input type="submit" value="Submit">

</form>
</body>

</html>

Code: [Link] (Controller - Handles Logic)

java

CopyEdit

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

@WebServlet("/ControllerServlet")

public class ControllerServlet extends HttpServlet {

protected void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

String name = [Link]("username");

[Link]("name", name);

[Link]("[Link]").forward(request, response);

Code: [Link] (View - Output)

jsp

CopyEdit

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

<html>

<head><title>Display Page</title></head>

<body>
<h2>Welcome, <%= [Link]("name") %>!</h2>

</body>

</html>

Expected Output

1. User enters "John" in [Link]

2. Submits form → [Link] processes it

3. Browser displays:

Welcome, John!

4. JSP Session Management

Session management helps store user-specific data across multiple pages.

Example: Storing and Retrieving Session Data

Code: session_set.jsp (Store Data)

jsp

CopyEdit

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

<%

[Link]("user", "John");

%>

<p>Session data set. <a href="session_get.jsp">Go to next page</a></p>

Code: session_get.jsp (Retrieve Data)

jsp

CopyEdit

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

<p>Welcome, <%= [Link]("user") %>!</p>

Expected Output

1. Visit session_set.jsp → Session stores John

2. Go to session_get.jsp → Displays:
Welcome, John!

Next Steps

Do you want:

1. More advanced JSP topics (like JSP Filters, Custom Tags)?

2. JPA-Hibernate Examples (as per your original request)?

Let me know how you'd like to continue!

You said:

ChatGPT said:

Now, let’s move on to JPA-Hibernate (ORM Framework). We’ll cover:

1. Introduction to JPA and Hibernate

2. Setting up Hibernate with MySQL

3. CRUD Operations (Create, Read, Update, Delete)

4. Session Management in Hibernate

5. ID Generation Strategies

1. Introduction to JPA and Hibernate

What is JPA?

JPA (Java Persistence API) is a specification for managing relational data in Java applications.

What is Hibernate?

Hibernate is an ORM (Object-Relational Mapping) framework that implements JPA and simplifies
database interactions using Java objects.

Why Use Hibernate?

✅ Eliminates JDBC boilerplate code


✅ Supports automatic table creation
✅ Provides HQL (Hibernate Query Language)
✅ Uses caching for performance
2. Setting Up Hibernate with MySQL

Steps:

✅ Add Hibernate Dependencies (Maven)


✅ Create Hibernate Configuration File ([Link])
✅ Define an Entity Class
✅ Perform CRUD Operations

Step 1: Add Hibernate Dependencies (Maven)

If you are using Maven, add the following dependencies in [Link]:

xml

CopyEdit

<dependencies>

<!-- Hibernate Core -->

<dependency>

<groupId>[Link]</groupId>

<artifactId>hibernate-core</artifactId>

<version>[Link]</version>

</dependency>

<!-- MySQL Connector -->

<dependency>

<groupId>mysql</groupId>

<artifactId>mysql-connector-java</artifactId>

<version>8.0.33</version>

</dependency>

</dependencies>

Step 2: Configure Hibernate ([Link])

Create [Link] in src/main/resources:


xml

CopyEdit

<hibernate-configuration>

<session-factory>

<property name="[Link].driver_class">[Link]</property>

<property
name="[Link]">jdbc:mysql://localhost:3306/mydatabase</property>

<property name="[Link]">root</property>

<property name="[Link]">password</property>

<property name="[Link]">[Link].MySQL8Dialect</property>

<!-- Hibernate Settings -->

<property name="hibernate.show_sql">true</property>

<property name="[Link]">update</property>

</session-factory>

</hibernate-configuration>

� [Link]

 update → Automatically updates schema

 create → Creates a new table every run

 validate → Verifies schema but doesn’t change

Step 3: Define an Entity Class

We will create a User class that maps to a database table.

Code: [Link]

java

CopyEdit

import [Link].*;
@Entity

@Table(name = "users")

public class User {

@Id

@GeneratedValue(strategy = [Link])

private int id;

@Column(name = "name")

private String name;

@Column(name = "email")

private String email;

// Constructors

public User() {}

public User(String name, String email) {

[Link] = name;

[Link] = email;

// Getters and Setters

public int getId() { return id; }

public void setId(int id) { [Link] = id; }

public String getName() { return name; }

public void setName(String name) { [Link] = name; }

public String getEmail() { return email; }

public void setEmail(String email) { [Link] = email; }

}
3. CRUD Operations in Hibernate

Now, we will implement Create, Read, Update, and Delete (CRUD) operations in Hibernate.

Step 1: Create a Hibernate Utility Class

Code: [Link]

java

CopyEdit

import [Link];

import [Link];

public class HibernateUtil {

private static final SessionFactory sessionFactory = buildSessionFactory();

private static SessionFactory buildSessionFactory() {

try {

return new Configuration().configure().buildSessionFactory();

} catch (Throwable ex) {

throw new ExceptionInInitializerError(ex);

public static SessionFactory getSessionFactory() {

return sessionFactory;

public static void shutdown() {

getSessionFactory().close();

}
}

Step 2: Create a User (INSERT)

Code: [Link]

java

CopyEdit

import [Link];

import [Link];

public class UserDAO {

public void saveUser(User user) {

Transaction transaction = null;

try (Session session = [Link]().openSession()) {

transaction = [Link]();

[Link](user);

[Link]();

} catch (Exception e) {

if (transaction != null) [Link]();

[Link]();

Code: [Link]

java

CopyEdit

public class Main {

public static void main(String[] args) {

UserDAO userDAO = new UserDAO();


User user = new User("Alice", "alice@[Link]");

[Link](user);

[Link]("User saved successfully!");

Expected Output:

pgsql

CopyEdit

Hibernate: insert into users (name, email) values (?, ?)

User saved successfully!

Step 3: Read User Data (SELECT)

java

CopyEdit

public User getUser(int id) {

try (Session session = [Link]().openSession()) {

return [Link]([Link], id);

Calling the method:

java

CopyEdit

User user = [Link](1);

[Link]("User Name: " + [Link]());

Step 4: Update User Data (UPDATE)

java

CopyEdit
public void updateUser(User user) {

Transaction transaction = null;

try (Session session = [Link]().openSession()) {

transaction = [Link]();

[Link](user);

[Link]();

Calling the method:

java

CopyEdit

User user = [Link](1);

[Link]("alice_new@[Link]");

[Link](user);

Expected Output:

bash

CopyEdit

Hibernate: update users set email=? where id=?

Step 5: Delete User Data (DELETE)

java

CopyEdit

public void deleteUser(int id) {

Transaction transaction = null;

try (Session session = [Link]().openSession()) {

transaction = [Link]();

User user = [Link]([Link], id);

if (user != null) {
[Link](user);

[Link]();

Calling the method:

java

CopyEdit

[Link](1);

Expected Output:

bash

CopyEdit

Hibernate: delete from users where id=?

4. Hibernate ID Generation Strategies

Hibernate provides different ID generation strategies:

Strategy Description

AUTO Let Hibernate decide (default)

IDENTITY Uses database auto-increment

SEQUENCE Uses database sequence (for PostgreSQL, Oracle)

TABLE Uses a separate table for ID generation

Example Usage:

java

CopyEdit

@Id

@GeneratedValue(strategy = [Link])

private int id;


Next Steps

Would you like:

1. More advanced Hibernate features (like One-to-Many, Many-to-Many relations)?

2. JSP + Hibernate integration (for web applications)?

Let me know how you'd like to proceed!

4o

You said:

yes

ChatGPT said:

Let’s proceed with JSP + Hibernate integration to build a simple web application that performs
CRUD operations.

Project Overview: JSP + Hibernate (CRUD Web App)

Technologies Used

✅ JSP (Java Server Pages) → Frontend (View Layer)


✅ Servlet → Handles User Requests
✅ Hibernate → ORM (Database Operations)
✅ MySQL → Database

Project Structure

pgsql

CopyEdit

JSP-Hibernate-CRUD/

│── src/

│ ├── main/

│ │ ├── java/

│ │ │ ├── model/ ([Link])

│ │ │ ├── dao/ ([Link])


│ │ │ ├── util/ ([Link])

│ │ │ ├── servlet/ ([Link])

│ ├── webapp/

│ │ ├── [Link] (Home Page - List Users)

│ │ ├── [Link] (Add User Form)

│ │ ├── [Link] (Edit User Form)

│ │ ├── [Link] (Delete Confirmation)

│── [Link] (Maven Dependencies)

│── [Link] (Hibernate Config)

1. Maven Dependencies

Add these dependencies in [Link]:

xml

CopyEdit

<dependencies>

<!-- Hibernate Core -->

<dependency>

<groupId>[Link]</groupId>

<artifactId>hibernate-core</artifactId>

<version>[Link]</version>

</dependency>

<!-- MySQL Connector -->

<dependency>

<groupId>mysql</groupId>

<artifactId>mysql-connector-java</artifactId>

<version>8.0.33</version>

</dependency>
<!-- Servlet API -->

<dependency>

<groupId>[Link]</groupId>

<artifactId>[Link]-api</artifactId>

<version>4.0.1</version>

<scope>provided</scope>

</dependency>

</dependencies>

2. Hibernate Configuration ([Link])

Create a file [Link] in src/main/resources/:

xml

CopyEdit

<hibernate-configuration>

<session-factory>

<property name="[Link].driver_class">[Link]</property>

<property
name="[Link]">jdbc:mysql://localhost:3306/mydatabase</property>

<property name="[Link]">root</property>

<property name="[Link]">password</property>

<property name="[Link]">[Link].MySQL8Dialect</property>

<!-- Hibernate Properties -->

<property name="hibernate.show_sql">true</property>

<property name="[Link]">update</property>

</session-factory>

</hibernate-configuration>
3. Model Class ([Link])

Create [Link] inside model package:

java

CopyEdit

package model;

import [Link].*;

@Entity

@Table(name = "users")

public class User {

@Id

@GeneratedValue(strategy = [Link])

private int id;

@Column(name = "name")

private String name;

@Column(name = "email")

private String email;

public User() {}

public User(String name, String email) {

[Link] = name;

[Link] = email;

}
public int getId() { return id; }

public void setId(int id) { [Link] = id; }

public String getName() { return name; }

public void setName(String name) { [Link] = name; }

public String getEmail() { return email; }

public void setEmail(String email) { [Link] = email; }

4. Hibernate Utility ([Link])

java

CopyEdit

package util;

import [Link];

import [Link];

public class HibernateUtil {

private static final SessionFactory sessionFactory = buildSessionFactory();

private static SessionFactory buildSessionFactory() {

try {

return new Configuration().configure().buildSessionFactory();

} catch (Throwable ex) {

throw new ExceptionInInitializerError(ex);

}
public static SessionFactory getSessionFactory() {

return sessionFactory;

5. DAO Class ([Link])

java

CopyEdit

package dao;

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

public class UserDAO {

public void saveUser(User user) {

Transaction transaction = null;

try (Session session = [Link]().openSession()) {

transaction = [Link]();

[Link](user);

[Link]();

public List<User> getAllUsers() {

try (Session session = [Link]().openSession()) {


return [Link]("from User", [Link]).list();

6. Servlet ([Link])

java

CopyEdit

package servlet;

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

@WebServlet("/UserServlet")

public class UserServlet extends HttpServlet {

private UserDAO userDAO = new UserDAO();

protected void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

String name = [Link]("name");

String email = [Link]("email");


[Link](new User(name, email));

[Link]("[Link]");

protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

List<User> userList = [Link]();

[Link]("userList", userList);

[Link]("[Link]").forward(request, response);

7. JSP Pages

Home Page ([Link])

jsp

CopyEdit

<%@ page import="[Link], [Link]" %>

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

<html>

<head><title>User List</title></head>

<body>

<h2>User List</h2>

<a href="[Link]">Add User</a>

<table border="1">

<tr><th>ID</th><th>Name</th><th>Email</th></tr>

<%

List<User> userList = (List<User>) [Link]("userList");

if (userList != null) {
for (User user : userList) {

%>

<tr>

<td><%= [Link]() %></td>

<td><%= [Link]() %></td>

<td><%= [Link]() %></td>

</tr>

<%

%>

</table>

</body>

</html>

Add User Page ([Link])

jsp

CopyEdit

<html>

<head><title>Add User</title></head>

<body>

<h2>Add User</h2>

<form action="UserServlet" method="post">

Name: <input type="text" name="name"><br>

Email: <input type="text" name="email"><br>

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

</form>

</body>
</html>

8. Running the Project

1. Start MySQL Server

2. Run the application using Tomcat

3. Visit: [Link]

4. Add Users and View List

Updating the Project: Edit & Delete Users

What We Will Do

✅ Edit User – Modify an existing user's details


✅ Delete User – Remove a user from the database
✅ Update DAO, Servlet, and JSP Pages

1. Update [Link] for Edit & Delete

Modify [Link] to include updateUser() and deleteUser() methods.

java

CopyEdit

package dao;

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

public class UserDAO {

public void saveUser(User user) {

Transaction transaction = null;


try (Session session = [Link]().openSession()) {

transaction = [Link]();

[Link](user);

[Link]();

public List<User> getAllUsers() {

try (Session session = [Link]().openSession()) {

return [Link]("from User", [Link]).list();

public User getUserById(int id) {

try (Session session = [Link]().openSession()) {

return [Link]([Link], id);

public void updateUser(User user) {

Transaction transaction = null;

try (Session session = [Link]().openSession()) {

transaction = [Link]();

[Link](user);

[Link]();

}
public void deleteUser(int id) {

Transaction transaction = null;

try (Session session = [Link]().openSession()) {

transaction = [Link]();

User user = [Link]([Link], id);

if (user != null) {

[Link](user);

[Link]();

2. Update [Link] for Edit & Delete

Modify [Link] to handle edit and delete requests.

java

CopyEdit

package servlet;

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];
@WebServlet("/UserServlet")

public class UserServlet extends HttpServlet {

private UserDAO userDAO = new UserDAO();

protected void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

String action = [Link]("action");

if ("edit".equals(action)) {

int id = [Link]([Link]("id"));

String name = [Link]("name");

String email = [Link]("email");

User user = new User(name, email);

[Link](id);

[Link](user);

} else {

String name = [Link]("name");

String email = [Link]("email");

[Link](new User(name, email));

[Link]("UserServlet");

protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

String action = [Link]("action");


if ("delete".equals(action)) {

int id = [Link]([Link]("id"));

[Link](id);

[Link]("UserServlet");

} else if ("edit".equals(action)) {

int id = [Link]([Link]("id"));

User user = [Link](id);

[Link]("user", user);

[Link]("[Link]").forward(request, response);

} else {

List<User> userList = [Link]();

[Link]("userList", userList);

[Link]("[Link]").forward(request, response);

3. Update [Link] (User List)

Modify [Link] to include Edit and Delete links.

jsp

CopyEdit

<%@ page import="[Link], [Link]" %>

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

<html>

<head><title>User List</title></head>

<body>

<h2>User List</h2>

<a href="[Link]">Add User</a>


<table border="1">

<tr><th>ID</th><th>Name</th><th>Email</th><th>Actions</th></tr>

<%

List<User> userList = (List<User>) [Link]("userList");

if (userList != null) {

for (User user : userList) {

%>

<tr>

<td><%= [Link]() %></td>

<td><%= [Link]() %></td>

<td><%= [Link]() %></td>

<td>

<a href="UserServlet?action=edit&id=<%= [Link]() %>">Edit</a> |

<a href="UserServlet?action=delete&id=<%= [Link]() %>"

confirm('Are you sure?')">Delete</a>

</td>

</tr>

<%

%>

</table>

</body>

</html>

4. Create [Link] (Edit User Page)

Create a new JSP file for updating user details.

jsp
CopyEdit

<%@ page import="[Link]" %>

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

<html>

<head><title>Edit User</title></head>

<body>

<h2>Edit User</h2>

<%

User user = (User) [Link]("user");

%>

<form action="UserServlet" method="post">

<input type="hidden" name="action" value="edit">

<input type="hidden" name="id" value="<%= [Link]() %>">

Name: <input type="text" name="name" value="<%= [Link]() %>"><br>

Email: <input type="text" name="email" value="<%= [Link]() %>"><br>

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

</form>

</body>

</html>

5. Running the Project

Steps

1. Start MySQL Server

2. Run the application using Tomcat

3. Visit:

o [Link] → View Users

o [Link] → Add a User

o Click Edit or Delete for actions


Expected Output

User List Page ([Link])

ID Name Email Actions

1 Alice alice@[Link] Edit

2 Bob bob@[Link] Edit

✅ Click "Edit" → Takes you to the edit page.


✅ Click "Delete" → Removes the user after confirmation.

1⃣ Advanced Hibernate Features (One-to-Many, Many-to-Many Relationships)

We will create:

 A One-to-Many relationship (One User has many Posts).

 A Many-to-Many relationship (Users can belong to multiple Groups, and Groups can
have multiple Users).

� One-to-Many Relationship (User & Posts)

A User can have multiple Posts.

Step 1: Update [Link]

java

CopyEdit

package model;

import [Link].*;

import [Link];

@Entity

@Table(name = "users")

public class User {

@Id
@GeneratedValue(strategy = [Link])

private int id;

private String name;

private String email;

@OneToMany(mappedBy = "user", cascade = [Link])

private List<Post> posts;

// Getters and Setters

Step 2: Create [Link]

java

CopyEdit

package model;

import [Link].*;

@Entity

@Table(name = "posts")

public class Post {

@Id

@GeneratedValue(strategy = [Link])

private int id;

private String content;

@ManyToOne

@JoinColumn(name = "user_id")
private User user;

// Getters and Setters

Step 3: Save User with Posts

java

CopyEdit

User user = new User();

[Link]("Alice");

[Link]("alice@[Link]");

Post post1 = new Post();

[Link]("First post!");

[Link](user);

Post post2 = new Post();

[Link]("Second post!");

[Link](user);

[Link]([Link](post1, post2));

Session session = [Link]().openSession();

Transaction tx = [Link]();

[Link](user);

[Link]();

2⃣ File Upload & Image Handling in JSP


We will implement image upload using JSP & Servlet.

Step 1: Add Multipart Config in [Link]

xml

CopyEdit

<servlet>

<servlet-name>FileUploadServlet</servlet-name>

<servlet-class>[Link]</servlet-class>

<multipart-config>

<max-file-size>5242880</max-file-size> <!-- 5MB -->

</multipart-config>

</servlet>

Step 2: Create JSP Upload Form ([Link])

jsp

CopyEdit

<form action="FileUploadServlet" method="post" enctype="multipart/form-data">

<input type="file" name="file">

<input type="submit" value="Upload">

</form>

Step 3: Create [Link]

java

CopyEdit

package servlet;

import [Link];

import [Link];

import [Link];
import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

@MultipartConfig

public class FileUploadServlet extends HttpServlet {

protected void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

Part filePart = [Link]("file");

String fileName = [Link]();

String uploadPath = getServletContext().getRealPath("") + [Link] + "uploads";

File uploadDir = new File(uploadPath);

if (![Link]()) [Link]();

[Link](uploadPath + [Link] + fileName);

[Link]().println("File uploaded: " + fileName);

✅ Now you can upload images!

3⃣ User Authentication (Login/Logout with JSP + Hibernate)

We will create a login system where users can register, login, and logout.

Step 1: Update [Link] with Password

java

CopyEdit
private String password; // Add this field

Step 2: Create [Link]

jsp

CopyEdit

<form action="AuthServlet" method="post">

<input type="hidden" name="action" value="register">

Name: <input type="text" name="name"><br>

Email: <input type="email" name="email"><br>

Password: <input type="password" name="password"><br>

<input type="submit" value="Register">

</form>

Step 3: Create [Link]

java

CopyEdit

package servlet;

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];
@WebServlet("/AuthServlet")

public class AuthServlet extends HttpServlet {

private UserDAO userDAO = new UserDAO();

protected void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

String action = [Link]("action");

if ("register".equals(action)) {

String name = [Link]("name");

String email = [Link]("email");

String password = [Link]("password");

User user = new User(name, email, password);

[Link](user);

[Link]("[Link]");

} else if ("login".equals(action)) {

String email = [Link]("email");

String password = [Link]("password");

User user = [Link](email);

if (user != null && [Link]().equals(password)) {

HttpSession session = [Link]();

[Link]("user", user);

[Link]("[Link]");

} else {

[Link]().println("Invalid credentials!");

} else if ("logout".equals(action)) {
[Link]().invalidate();

[Link]("[Link]");

Step 4: Create [Link]

jsp

CopyEdit

<form action="AuthServlet" method="post">

<input type="hidden" name="action" value="login">

Email: <input type="email" name="email"><br>

Password: <input type="password" name="password"><br>

<input type="submit" value="Login">

</form>

Step 5: Create [Link]

jsp

CopyEdit

<%@ page import="[Link]" %>

<%

User user = (User) [Link]("user");

if (user == null) {

[Link]("[Link]");

return;

%>

<h2>Welcome, <%= [Link]() %>!</h2>


<a href="AuthServlet?action=logout">Logout</a>

✅ Now you have a working login system!

1⃣ Role-Based Authentication (Admin/User Access Control)

We’ll add roles (ADMIN and USER) and restrict access accordingly.

Step 1: Update [Link] to Include Roles

Modify your User model to include a role field.

java

CopyEdit

@Entity

@Table(name = "users")

public class User {

@Id

@GeneratedValue(strategy = [Link])

private int id;

private String name;

private String email;

private String password;

private String role; // "ADMIN" or "USER"

public User() {}

public User(String name, String email, String password, String role) {

[Link] = name;

[Link] = email;

[Link] = password;

[Link] = role;

}
// Getters and Setters

Step 2: Update Registration ([Link])

When a new user registers, we assign them the "USER" role by default.

java

CopyEdit

if ("register".equals(action)) {

String name = [Link]("name");

String email = [Link]("email");

String password = [Link]("password");

User user = new User(name, email, [Link](password, [Link]()), "USER");

[Link](user);

[Link]("[Link]");

� Admin accounts should be added manually in the database for security reasons.

Step 3: Restrict Access in [Link]

jsp

CopyEdit

<%@ page import="[Link]" %>

<%

User user = (User) [Link]("user");

if (user == null) {

[Link]("[Link]");

return;

}
%>

<h2>Welcome, <%= [Link]() %>!</h2>

<p>Role: <%= [Link]() %></p>

<% if ("ADMIN".equals([Link]())) { %>

<h3>Admin Dashboard</h3>

<a href="[Link]">Manage Users</a>

<% } else { %>

<h3>User Dashboard</h3>

<p>You have limited access.</p>

<% } %>

<a href="AuthServlet?action=logout">Logout</a>

✅ Now, Admin users can access extra features!

2⃣ Email Verification (Before Login)

We’ll send a verification email and require users to confirm before logging in.

Step 1: Add a verified Field in [Link]

java

CopyEdit

private boolean verified = false;

Step 2: Configure JavaMail for Sending Emails

Add JavaMail API dependency in [Link] (for Maven users).

xml

CopyEdit

<dependency>
<groupId>[Link]</groupId>

<artifactId>mail</artifactId>

<version>1.4.7</version>

</dependency>

Step 3: Create [Link]

This class sends a verification email.

java

CopyEdit

import [Link].*;

import [Link].*;

import [Link];

public class EmailService {

public static void sendVerificationEmail(String toEmail, String token) {

final String fromEmail = "your-email@[Link]";

final String password = "your-email-password";

Properties properties = new Properties();

[Link]("[Link]", "[Link]");

[Link]("[Link]", "587");

[Link]("[Link]", "true");

[Link]("[Link]", "true");

Session session = [Link](properties, new Authenticator() {

protected PasswordAuthentication getPasswordAuthentication() {

return new PasswordAuthentication(fromEmail, password);

}
});

try {

Message message = new MimeMessage(session);

[Link](new InternetAddress(fromEmail));

[Link]([Link], [Link](toEmail));

[Link]("Verify Your Email");

[Link]("Click the link to verify your account: [Link] +


token);

[Link](message);

} catch (MessagingException e) {

[Link]();

� Replace your-email@[Link] and password with your email credentials.

Step 4: Modify [Link] to Send Verification Emails

java

CopyEdit

if ("register".equals(action)) {

String name = [Link]("name");

String email = [Link]("email");

String password = [Link]([Link]("password"), [Link]());

String token = [Link]().toString();

User user = new User(name, email, password, "USER");

[Link](false);
[Link](token);

[Link](user);

[Link](email, token);

[Link]().println("Check your email for verification!");

Step 5: Create [Link] for Verification

java

CopyEdit

@WebServlet("/verify")

public class VerifyServlet extends HttpServlet {

private UserDAO userDAO = new UserDAO();

protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

String token = [Link]("token");

User user = [Link](token);

if (user != null) {

[Link](true);

[Link](user);

[Link]().println("Email verified! You can now <a href='[Link]'>Login</a>.");

} else {

[Link]().println("Invalid verification link.");

}
}

✅ Now, users must verify their email before logging in!

3⃣ Password Hashing (Using BCrypt for Security)

We'll store hashed passwords in the database using BCrypt.

Step 1: Add BCrypt Dependency ([Link])

xml

CopyEdit

<dependency>

<groupId>[Link]</groupId>

<artifactId>jbcrypt</artifactId>

<version>0.4</version>

</dependency>

Step 2: Modify [Link] to Hash Passwords

When users register, we hash the password.

java

CopyEdit

String hashedPassword = [Link](password, [Link]());

User user = new User(name, email, hashedPassword, "USER");

Step 3: Verify Password in [Link]

When users login, we compare the stored hash with the entered password.

java

CopyEdit

User user = [Link](email);

if (user != null && [Link](password, [Link]())) {

HttpSession session = [Link]();


[Link]("user", user);

[Link]("[Link]");

} else {

[Link]().println("Invalid credentials!");

✅ Now passwords are securely hashed and verified!

� Summary

� Role-Based Access Control → Admins have extra privileges.


� Email Verification → Users must verify their email before logging in.
� BCrypt Password Hashing → Ensures passwords are securely stored.

You might also like