Introduction:
This is a small mini project to get the basic understating of Hibernate with JSP & Servlet. Here, we just perform a CRUD operation. Name of the
Project name is Notetaker where we can save, update & delete our notes with Title & related content along with date & time.
Technology Used:
Hibernate, Servlet, JSP, Bootstrap 4.0, MySql
IDE: Eclipse
Image Credit : https://www.flaticon.com/
1: Create a database in mysql name notetaker
2: Create a Maven Project name
Go to File->New->Maven Project->Select your workspace (by default it will be selected as default workspace location which we can change) ->Click on Next->Select Internal from the drop down of Catalog->Choose Artifact Id maven-archetype-webapp
Put Group id (package name) & Artifact Id (Project Name)
create three packages as follows
com.entities com.helper com.servlet
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.hiber.notetaker</groupId>
<artifactId>NoteTaker</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>NoteTaker Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.6.6.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.30</version>
</dependency>
</dependencies>
<build>
<finalName>NoteTaker</finalName>
</build>
</project>
create hibernate.cfg.xml in src/main/resources
<?xml version = "1.0" encoding = "utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/notetaker</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<property name = "dialect">org.hibernate.dialect.MySQL5Dialect</property>
<property name="hbm2ddl.auto">update</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<mapping class="com.entities.Note"/>
</session-factory>
</hibernate-configuration>
Note.java
package com.entities;
import java.util.Date;
import java.util.Random;
import javax.persistence.Entity;
import javax.persistence.*;
import javax.persistence.Table;
@Entity
@Table(name="notes")
public class Note {
@Id
private int id;
private String title;
@Column(length = 5000)
private String content;
private Date addedDate;
public Note() {
super();
// TODO Auto-generated constructor stub
}
public Note(String title, String content, Date addedDate) {
super();
this.id = new Random().nextInt(10000);
this.title = title;
this.content = content;
this.addedDate = addedDate;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Date getAddedDate() {
return addedDate;
}
public void setAddedDate(Date addedDate) {
this.addedDate = addedDate;
}
}
FactoryProvider.java
package com.helper;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class FactoryProvider {
public static SessionFactory factory;
public static SessionFactory getSessionFactory() {
if(factory==null) {
factory=new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();
}
return factory;
}
public void closeFactory() {
if(factory.isOpen()) {
factory.close();
}
}
}
SaveNoteServlet.java
package com.servlets;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import com.entities.Note;
import com.helper.FactoryProvider;
public class SaveNoteServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
// fetch title & textarea contents here
String title=request.getParameter("title");
String content=request.getParameter("content");
System.out.println(title+""+content);
Note note=new Note(title,content,new Date());
// Hibernet Save
SessionFactory sessionFactory = FactoryProvider.getSessionFactory();
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
session.save(note);
tx.commit();
session.beginTransaction();
session.close();
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h1 style='text-align:center'>Note Added Successfully</h1>");
out.println("<h1 style='text-align:center'><a href='all_notes.jsp'>View All notes</a></h1>");
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
UpdateServlet.java
package com.servlets;
import java.io.IOException;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import com.entities.Note;
import com.helper.FactoryProvider;
public class UpdateServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public UpdateServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String title=(request.getParameter("title"));
String content=(request.getParameter("content"));
int note_id=Integer.parseInt(request.getParameter("note_id").trim());
Session session=FactoryProvider.getSessionFactory().openSession();
Transaction tx=session.beginTransaction();
Note note=session.get(Note.class, note_id);
note.setTitle(title);
note.setContent(content);
note.setAddedDate(new Date());
session.update(note);
tx.commit();
session.close();
response.sendRedirect("all_notes.jsp");
}
}
DeleteServlet.java
package com.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 org.hibernate.Session;
import org.hibernate.Transaction;
import com.entities.Note;
import com.helper.FactoryProvider;
/**
* Servlet implementation class DeleteServlet
*/
public class DeleteServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public DeleteServlet() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
try {
int note_id=Integer.parseInt(request.getParameter("note_id").trim());
Session session=FactoryProvider.getSessionFactory().openSession();
Transaction tx=session.beginTransaction();
Note note=session.get(Note.class, note_id);
session.delete(note);
tx.commit();
session.close();
response.sendRedirect("all_notes.jsp");
} catch (Exception e) {
// TODO: handle exception
}
}
}
style.css 👇
.purple{
background-color:#BA55D3;
}
web.xml 👇
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>SaveNoteServlet</servlet-name>
<display-name>SaveNoteServlet</display-name>
<description></description>
<servlet-class>com.servlets.SaveNoteServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>DeleteServlet</servlet-name>
<display-name>DeleteServlet</display-name>
<description></description>
<servlet-class>com.servlets.DeleteServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>UpdateServlet</servlet-name>
<display-name>UpdateServlet</display-name>
<description></description>
<servlet-class>com.servlets.UpdateServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SaveNoteServlet</servlet-name>
<url-pattern>/SaveNoteServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>DeleteServlet</servlet-name>
<url-pattern>/DeleteServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>UpdateServlet</servlet-name>
<url-pattern>/UpdateServlet</url-pattern>
</servlet-mapping>
</web-app>
index.jsp 👇
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport"
content="width=device-width, initial-scale=1, shrink-to-fit=no">
<%@include file="all_js_css.jsp"%>
<title>Note Taker: Home </title>
</head>
<body>
<div class="container text-center">
<%@include file="navbar.jsp"%>
<br>
<div class="card">
<img alt="imgnote" src="img/pencil.png" class="img-fluid mx-auto" style="max-width: 200px">
<h1 class="text-primary text-uppercase mt-3">Your Personal Notebook</h1>
<br>
<div class="container text-primary">
<button class="btn btn-outline-primary text-center mb-3"><a href="add_notes.jsp">Add Notes</a></button>
</div>
</div>
</div>
</body>
</html>
navbar.jsp
<nav class="navbar navbar-expand-lg navbar-dark purple">
<a class="navbar-brand " href="index.jsp"><img style="width: 30px" src="img/notebook.png"></a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse mx-auto"id="navbarSupportedContent" >
<ul class="navbar-nav mr-auto">
         
<li class="nav-item">
<a class="nav-link" href="add_notes.jsp"><b style="color: white"><img src="img/addnote.png" style="width:30px" class="padding-left:10px"/>Add Note</b></a>
</li>
         
<li class="nav-item">
<a class="nav-link" href="all_notes.jsp"><b style="color: white"> <img src="img/eye.png" style="width:30px"/>View All Notes </b></a>
</li>
</ul>
<form class="form-inline my-2 my-lg-0">
<input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-lights my-2 my-sm-0" type="submit">Search</button>
</form>
</div>
</nav>
all_js_css.jsp 👇
<!-- Bootstrap CSS -->
<link rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css"
integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"
crossorigin="anonymous">
<link rel="stylesheet" href="css/style.css">
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"
integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN"
crossorigin="anonymous"></script>
<script
src="https://cdn.jsdelivr.net/npm/popper.js@1.12.9/dist/umd/popper.min.js"
integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
crossorigin="anonymous"></script>
<script
src="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/js/bootstrap.min.js"
integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
crossorigin="anonymous"></script>
add_notes.jsp 👇
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<%@include file="all_js_css.jsp"%>
<title>Add Notes</title>
</head>
<body>
<%@include file="navbar.jsp"%>
<br>
<div class="container text-center">
<h2 style="color:green"><img style="width: 30px" src="img/addnote.png"> Add Note</h2>
</div>
<br>
<div class="container">
<form action="SaveNoteServlet" method="post">
<div class="form-group">
<label for="title">Note Title</label>
<input type="text"
class="form-control" id="title"
name="title"
aria-describedby="emailHelp" placeholder="Enter Title here" required="required">
</div>
<br>
<br>
<div class="form-group">
<label for="content">Note Content</label><br>
<textarea id="content" placeholder="Enter Content Here"
name="content"
class="form-control" style="height: 200px" required="required"></textarea>
</div>
<div class="form-check">
</div>
<div class="container text-center">
<button type="submit" class="btn btn-primary">Add</button>
</div>
</form>
</div>
</body>
</html>
all_notes.jsp
<%@page import="org.hibernate.Query"%>
<%@page import="com.helper.FactoryProvider"%>
<%@page import="org.hibernate.Session"%>
<%@page import="java.util.List"%>
<%@page import="com.entities.Note"%>
<%@page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<%@include file="all_js_css.jsp"%>
<title>All Notes</title>
</head>
<body>
<div class="container">
<%@include file="navbar.jsp"%>
<br>
<h3> All Notes</h3>
</div>
<div class="container">
<%
Session s=FactoryProvider.getSessionFactory().openSession();
Query query=s.createQuery("from Note");
List<Note> list= query.list();
for(Note note:list){
%>
<div class="card mt-3">
<div class="card-body px-5">
<img class="card-img-top m-4 mx-auto" src="img/pencil.png" style="max-width: 40px" alt="Card image cap">
<h5 class="card-title"><%= note.getTitle() %></h5>
<p class="card-text"><%= note.getContent() %></p>
<p class="card-text"><b class="text-primary"><%= note.getAddedDate() %></b></p>
<div class="container text-center mt-2">
<a href="DeleteServlet?note_id=<%=note.getId() %>" class="btn btn-danger">Delete</a>
<a href="edit_note.jsp?note_id=<%=note.getId() %> " class="btn btn-primary">Update</a>
</div>
</div>
</div>
<%
}
s.close();
%>
</div>
</body>
</html>
edit_note.jsp 👇
<%@page import="com.helper.FactoryProvider"%>
<%@page import="org.hibernate.Session"%>
<%@page import="com.entities.Note"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<%@include file="all_js_css.jsp"%>
<title>Edit Notes</title>
</head>
<body>
<div class="container">
<%@include file="navbar.jsp"%>
<br>
<h3><img style="width: 30px" src="img/edit.png"> Edit your note </h3>
<%
int note_id=Integer.parseInt(request.getParameter("note_id").trim());
Session s=FactoryProvider.getSessionFactory().openSession();
Note note=s.get(Note.class, note_id);
s.close();
%>
<div class="container">
<form action="UpdateServlet" method="post">
<input value="<%=note.getId()%>" type="hidden" name="note_id"/>
<div class="form-group">
<label for="title">Note Title</label>
<input type="text"
class="form-control" id="title"
name="title"
value="<%=note.getTitle()%>"
aria-describedby="emailHelp" placeholder="Enter Title here" required="required">
</div>
<br>
<br>
<div class="form-group">
<label for="content">Note Content</label><br>
<textarea id="content" placeholder="Enter Content Here"
name="content"
class="form-control" style="height: 200px" required="required"><%=note.getContent()%></textarea>
</div>
<div class="form-check">
</div>
<div class="container text-center">
<button type="submit" class="btn btn-primary">Update</button>
</div>
</form>
</div>
</div>
</body>
</html>