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>
многабукыфquestions in the question, then this does not mean that the question is formulated correctly .. - Drakonoved