Implemented a simple directory of books on a JSP page, whose data is drawn from an OracleSQL database using Hibernate. On the same page there is a form with fields ( input ) "name" , "author" , "year" and a submit button for adding to the database. Opposite each entry in the directory there are buttons update , delete . Add and delete data from the database is obtained without problems, but the update does not work.

The problem is that on the servlet in the doPost method the if condition does not work (through the debag found out,), namely the line else if (action.equals("update")) ..... I’ll say that the correct book ID picks up the correct one , there are no problems with it, do not break your head (debazhil).

I admit that I may be trying to perform a completely naive operation, but help me figure out how to still implement data output from the database and editing on the same JSP page. So far, it turns out to delete and add. I ask to poke a finger where you need to add or change. Thanks in advance to everyone for the detailed answers. For practical advice from me two bottles of beer on your wallet)

I will give all the pages of the code, but first of all the servlet itself ( Servletclass.class ) and the JSP class ( BookStore.jsp ).

  package ru.home.echo; import ru.home.echo.control.ControlClass; import ru.home.echo.entity.Books; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class ServletClass extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ControlClass controlClass= new ControlClass(); RequestDispatcher rd = null; resp.setContentType("text/html"); if (req.getParameter("action" )!=null) { if (req.getParameter("action").equals("delete")) { int id = Integer.parseInt(req.getParameter("id")); Books books = new Books(); books.setId(id); controlClass.deleteBook(books); List<Books> book = controlClass.getAllData(); req.setAttribute("Books", book); rd = req.getRequestDispatcher("BookStore.jsp"); } else if (req.getParameter("action").equals("update")){ int id = Integer.parseInt(req.getParameter("id").toString()); Books book = controlClass.getBooksById(id); req.setAttribute("booking", book); req.setAttribute("action", "update"); List<Books> books = controlClass.getAllData(); req.setAttribute("Books", books); rd = req.getRequestDispatcher("BookStore.jsp"); } } else { List<Books> books = controlClass.getAllData(); req.setAttribute("Books", books); rd = req.getRequestDispatcher("BookStore.jsp"); } rd.forward(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String action = req.getParameter("action").toString(); resp.setContentType("text/html"); RequestDispatcher rd=null; if(action.equals("new")) { Books books = new Books(); ControlClass controlClass = new ControlClass(); req.setAttribute("booking", books); books.setName(req.getParameter("bookname").toString()); books.setAuthor(req.getParameter("bookauthor").toString()); books.setYear(Integer.parseInt(req.getParameter("bookyear"))); controlClass.saveBook(books); List<Books> booksList = controlClass.getAllData(); req.setAttribute("Books", booksList); rd = req.getRequestDispatcher("BookStore.jsp"); } else if(action.equals("update")){ Books book= new Books(); book.setName(req.getParameter("bookname").toString()); book.setAuthor(req.getParameter("bookauthor").toString()); book.setYear(Integer.parseInt(req.getParameter("bookyear"))); book.setId(Integer.parseInt(req.getParameter("bookingid").toString())); ControlClass controlClass= new ControlClass(); controlClass.updateBook(book); List<Books>booksList= controlClass.getAllData(); req.setAttribute("Books",booksList); rd=req.getRequestDispatcher("BookStore.jsp"); } rd.forward(req,resp); } } 

BookStore.jsp page:

 <%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <html> <head> <meta charset="UTF-8"> <title>BooksStore</title> <style type="text/css"> .tdser {background: #cccccc;} td { font-family: Arial, sans-serif; font-size: 14px; padding: 10px 5px; border-style: solid; border-width: 1px; overflow: hidden; word-break: normal; border-color: black; color: #333; background-color: #fff; } table { border-collapse: collapse; border-spacing: 0; border-color: #ccc;} </style> </head> <body> <table > <tr id="toptr"> <td class="tdser">ID</td> <td class="tdser">NAME</td> <td class="tdser">AUTHOR</td> <td class="tdser">YEAR</td> </tr> <c:forEach items="${Books}" var="book"> <tr id="downtr"> <td>${book.id}</td> <td>${book.name}</td> <td>${book.author}</td> <td>${book.year}</td> <td><a href="/books?action=delete&id=${book.id}">delete</a></td> <td><a href="/books?action=update&id=${book.id}">update</a></td> </tr> </c:forEach> </table> <br> <br> <form action="/books" method="post"> Book name:<input type="text" name="bookname" value="${booking.name}"><br><br> Book author:<input type="text" name="bookauthor" value="${booking.author}"><br><br> Book year:<input type="text" name="bookyear" value="${booking.year}"><br><br> <input type="hidden" value="new" name="action"> <input type="hidden" value="${booking.id}" name="bookingid"> <input type="submit" value="submit"> </form> </body> </html> 

Class Books.class (entity):

 package ru.home.echo.entity; import javax.persistence.*; @Entity @Table(name = "BOOKS") public class Books { @Id @GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "bookIdGen") @SequenceGenerator(name = "bookIdGen", sequenceName = "BOOK_SEQ",allocationSize = 1) long id; @Column(name = "NAME") String name; @Column(name = "AUTHOR") String author; @Column(name = "YEAR") int year; public Books() { } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public int getYear() { return year; } public void setYear(int year) { this.year = year; } @Override public String toString() { return "Entity{" + "id=" + id + ", name='" + name + '\'' + ", author='" + author + '\'' + ", year=" + year + '}'; } } 

ControlClass class (controller):

 package ru.home.echo.control; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.Transaction; import ru.home.echo.DAO.GetSession; import ru.home.echo.entity.Books; import java.util.ArrayList; import java.util.List; public class ControlClass { public List<Books> getAllData(){ GetSession getSession= new GetSession(); Session session= getSession.getSessionFactory().openSession(); List<Books>book=new ArrayList<>(); Query query=session.createQuery("from Books book"); book= query.list(); return book; } public void saveBook(Books book) { GetSession getSession= new GetSession(); Session session= getSession.getSessionFactory().openSession(); Transaction t = session.beginTransaction(); session.save(book); t.commit(); System.out.println("inserted......."); } public void deleteBook(Books book) { GetSession getSession= new GetSession(); Session session= getSession.getSessionFactory().openSession(); Transaction t = session.beginTransaction(); session.delete(book); t.commit(); } public void updateBook(Books book) { GetSession getSession= new GetSession(); Session session= getSession.getSessionFactory().openSession(); Transaction t = session.beginTransaction(); session.update(book); t.commit(); } public Books getBooksById(int id){ String query = "from Books book where book.id="+id; GetSession getSession= new GetSession(); Session session= getSession.getSessionFactory().openSession(); Query query2 = session.createQuery(query); Books book= (Books) query2.list().get(0); return book; } } 

Class for getting SessionFactory:

 package ru.home.echo.DAO; import org.hibernate.SessionFactory; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; import java.util.Locale; public class GetSession { private static SessionFactory sessionFactory=createSessionFactory(); private static ServiceRegistry serviceRegistry; public static SessionFactory createSessionFactory() { try { Locale.setDefault(Locale.ENGLISH); Configuration configuration = new Configuration(); configuration.configure(); ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings( configuration.getProperties()).build(); sessionFactory = configuration.buildSessionFactory(serviceRegistry); return sessionFactory; } catch (Throwable ex) { throw new ExceptionInInitializerError(ex); } } public static SessionFactory getSessionFactory() { return sessionFactory; } public static void shutdown() { getSessionFactory().close(); } } 

Finally, WEB.xml :

 <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>HibernateExampleWithServlets</display-name> <servlet> <servlet-name>BooksServlet</servlet-name> <servlet-class>ru.home.echo.ServletClass</servlet-class> </servlet> <servlet-mapping> <servlet-name>BooksServlet</servlet-name> <url-pattern>/books</url-pattern> </servlet-mapping> </web-app> 
  • Add a template. That writes? - Drakonoved
  • The error does not throw, just does not work correctly. Namely - let's say there is an entry in the database name = "Gorec", author = "Ivan", year = "1988". When you click "update" opposite the record, the system throws on the form for editing with filled fields. Suppose I have a year from 1988 to 2000, then when you click the submit button, it simply adds a new entry Gorec, Ivan, 2000 (that is, the condition action = new for the place action = update. - Vaagn Akopyan
  • Reformulate the question correctly .. Please .. - Drakonoved
  • I answered your question. What exactly to reformulate? The question is how to make it so that using the same form and one submit button you can both add entries to the database and edit. I just know how to do it with two different pages (separate pages for adding and editing), but I’m wondering how to implement everything on one page. - Vaagn Akopyan
  • If there is a многабукыф questions in the question, then this does not mean that the question is formulated correctly .. - Drakonoved

2 answers 2

You need to change the name of the action, for example, how to make it with EL

 <input type="hidden" value="${booking.id == null?'new':'update'}" name="action"> 

If you do not want to do this in JSP, then you can look at the id parameter in the controller or where the levels are deeper. But the principle remains the same. You can even use one share for this in POST . on the other hand, if you already use id for editing, there is no point in checking it in JSP. Hibernate has a method that checks the id while saving and it is called saveOrUpdate as far as my memory is saveOrUpdate .

When you use saveOrUpdate() , Hibernate checks whether the object is transient (it does not have an identifier property), and if so, it will make it saved by generating its identifier and assigning it to the session. If the object has an identifier, it will update() .

From the documentation:

saveOrUpdate() performs the following actions:

  • if the object is already saved in this session, does nothing
  • if another object associated with the session has the same identifier, it generates an exception
  • if the object has no identifier, then it will save()
  • if the object identifier has the value assigned to the newly created object, then executes save()
  • if the object has a version, or the value of the version property is the same value assigned to the newly created object, it executes save() , otherwise it executes the update() object.
  • Worked with the first option. Thank you so much Roman for the hint, but still how to implement the option in my code without changing jsp. I will thank) - Vaagn Akopyan
  • if (String.isEmpty(req.getParameter("booking.id")) )//call action "new()" else //call action "update()" - Roman C
  • email me at v.hakobjan@gmail.com where to send you beer)) - Vaagn Akopyan

In the ServletClass , after checking for null , add System.out.println( req.getParameter("action") ) , and see which parameters come in when pressing a button.

And two clarifications on the code, what caught my eye. :)

The Books class creates an instance of one book, so it’s better to call it Book .

In ControlClass#getAllData() , an ArrayList returned, so here it is better to rename book to books .

It is better to immediately get used to call a single instance in the singular, plural - in the plural.