📜 ⬆️ ⬇️

Hibernate + jsp with servlet support

Hello! In this article I will discuss how to associate a JSP with Hibernate using a servlet. I hope that you know how to work with Hibernate, but if not, I strongly recommend reading this article . I also hope that you are familiar with servlets and have run them at least once.

To ensure that you have the same database in MySQL, paste the following code there:

CREATE SCHEMA `hero` ; CREATE TABLE `hero`.`heroes` ( `idhero` INT NOT NULL AUTO_INCREMENT, `name` VARCHAR(45) NOT NULL, PRIMARY KEY (`idhero`)); 

Create a maven project and insert the following dependencies and not only:

 <packaging>war</packaging> <properties> <hibernate.version>4.3.5.Final</hibernate.version> </properties> <dependencies> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>3.0-alpha-1</version> <scope>provided</scope> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.2.2</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>${hibernate.version}</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>${hibernate.version}</version> </dependency> <dependency> <groupId>javaee</groupId> <artifactId>javaee-api</artifactId> <version>5</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.38</version> </dependency> <dependency> <groupId>javax</groupId> <artifactId>javaee-web-api</artifactId> <version>6.0</version> <scope>provided</scope> </dependency> <!— https://mvnrepository.com/artifact/org.apache.commons.. —> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.4</version> </dependency> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> </dependencies> 

Connect to the database. Again: if you do not know how this is done, then the article about this and not only above.
')
Then we connect the web module.

Go to the File, Project Structure modules tab. Beforehand, delete everything that is in the modules tab (if it is there) by clicking on - (red). Press on + (green)
and add a web module:



Then in the Artifacts tab, also delete all artifacts and add a new +, Web Application: Exploded, From modules, OK:



Next, we deploy Hibernate and in order to make it convenient, stick this model into the model folder, which is located in by, pointing this way when expanding Hibernate.

In the by folder, create the util folder, and in it the HibernateUtil class:

 package by.util; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class HibernateUtil { private static SessionFactory sessionFactory=buildSessionFactory(); private static SessionFactory buildSessionFactory() { try{ return new Configuration().configure().buildSessionFactory(); }catch (Exception e){ throw new ExceptionInInitializerError(e); } } public static SessionFactory getSessionFactory() { return sessionFactory; } } 

Thanks to HibernateUtil we can create a special SessionFactory for our project.
In the by folder we create the DAO folder, in it the DAOImple class (we do not create the DAO interface, as the example is small):

 package by.DAO; import by.model.HeroesEntity; import by.util.HibernateUtil; import org.hibernate.Query; import org.hibernate.Session; import java.util.List; public class DAOImple { public void saveHero(HeroesEntity heroesEntity){ Session session= HibernateUtil.getSessionFactory().openSession(); session.beginTransaction(); session.save(heroesEntity); session.getTransaction().commit(); session.close(); } public List<HeroesEntity> getAll(){ Session session=HibernateUtil.getSessionFactory().openSession(); session.beginTransaction(); List<HeroesEntity> list=session.createQuery("from HeroesEntity").list(); session.getTransaction().commit(); session.close(); return list; } public void update(HeroesEntity heroesEntity){ Session session=HibernateUtil.getSessionFactory().openSession(); session.beginTransaction(); session.update(heroesEntity); session.getTransaction().commit(); session.close(); } public HeroesEntity getHeroById(int id){ Session session=HibernateUtil.getSessionFactory().openSession(); session.beginTransaction(); Query query= session.createQuery("from HeroesEntity where idhero=:id"); query.setInteger("id",id); HeroesEntity heroesEntity= (HeroesEntity) query.uniqueResult(); session.getTransaction().commit(); session.close(); return heroesEntity; } public void deleteHeroes(int id){ Session session=HibernateUtil.getSessionFactory().openSession(); session.beginTransaction(); Query query=session.createQuery("from HeroesEntity where idhero=:id"); query.setInteger("id",id); HeroesEntity heroesEntity= (HeroesEntity) query.uniqueResult(); session.delete(heroesEntity); session.getTransaction().commit(); session.close(); } } 

We need the DAOImple class in order to work with the information that is in the database.
In the by folder, create the servlets folder, and in it create a servlet (not a class!) SaveServlet (comments in the code):



 package by.servlets; import by.DAO.DAOImple; import by.model.HeroesEntity; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class SaveServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { DAOImple daoImple=new DAOImple(); //////////////////////////////////////// //INDEX.JSP //////////////////////////////////////// if(request.getParameter("add")!=null){//    add HeroesEntity heroesEntity=new HeroesEntity();//      heroesEntity.setIdhero(Integer.parseInt(request.getParameter("id")));//  id    c  id heroesEntity.setName(request.getParameter("name"));//    daoImple.saveHero(heroesEntity);//      request.setAttribute("list",daoImple.getAll());//            RequestDispatcher requestDispatcher=request.getRequestDispatcher("list.jsp");//  list.jsp requestDispatcher.forward(request,response); } if(request.getParameter("showAll")!=null){//    showALL request.setAttribute("list",daoImple.getAll());//            RequestDispatcher requestDispatcher=request.getRequestDispatcher("list.jsp");//  list.jsp requestDispatcher.forward(request,response); } /////////////////////////////////////////////////// //LIST.JSP /////////////////////////////////////////////////// String action=request.getParameter("action");// action         if(action.equalsIgnoreCase("update")){// action   update request.setAttribute("hero",daoImple.getHeroById(Integer.parseInt(request.getParameter("idhero"))));//    id   HeroesEntity RequestDispatcher requestDispatcher=request.getRequestDispatcher("update.jsp");////  update.jsp requestDispatcher.forward(request,response); } if(action.equalsIgnoreCase("delete")){// action   update daoImple.deleteHeroes(Integer.parseInt(request.getParameter("idhero")));//  id request.setAttribute("list",daoImple.getAll());//            RequestDispatcher requestDispatcher=request.getRequestDispatcher("list.jsp");//  list.jsp requestDispatcher.forward(request,response); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { DAOImple daoImple = new DAOImple(); ////////////////////////////////// // UPDATE.JSP ////////////////////////////////// if (request.getParameter("update") != null) {//    update HeroesEntity heroesEntity = new HeroesEntity();//   heroesEntity.setIdhero(Integer.parseInt(request.getParameter("idhero")));// id   idhero heroesEntity.setName(request.getParameter("name"));// name   name daoImple.update(heroesEntity);// request.setAttribute("list", daoImple.getAll());//            RequestDispatcher requestDispatcher = request.getRequestDispatcher("list.jsp");//  list.jsp requestDispatcher.forward(request, response); } } } 

Register servlet in 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"> <servlet> <servlet-name>SaveServlet</servlet-name> <servlet-class>by.servlets.SaveServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>SaveServlet</servlet-name> <url-pattern>/save</url-pattern> </servlet-mapping> </web-app> 

In the web folder, create the index.jsp start page:

 <%-- Created by IntelliJ IDEA. User:  Date: 29.05.2017 Time: 18:18 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <form method="get" action="/save"> <input type="text" name="id"> <input type="text" name="name"> <input type="submit" name="add" value="add"> <input type="submit" name="showAll" value="showAll"> </form> </body> </html> 

as well as list.jsp:

 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <table> <tr> <td>id</td> <td>name</td> </tr> <c:forEach items="${list}" var="list"> <tr> <th>${list.idhero}</th> <th>${list.name}</th> <th><a href="/save?action=update&idhero=<c:out value="${list.idhero}"/>">update</a> </th> <th><a href="/save?action=delete&idhero=${list.idhero}">delete</a> </th> </tr> </c:forEach> </table> </body> </html> 

and update.jsp:

 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <form method="post" action="/save"> <input type="text" name="idhero" readonly="readonly" value="<c:out value="${hero.idhero}"/>"> <input type="text" name="name" value="<c:out value="${hero.name}"/>"> <input type="submit" value="ok" name="update"> </form> </body> </html> 

Further we configure TomCat:




We give him an artifact (you can simply click on the button below with a red light bulb and the name Fix):



I hope that you managed to run this example. This example is on github: here .

Good luck!

Source: https://habr.com/ru/post/329924/


All Articles