简体   繁体   English

带有 Servlet、JSP 和 MySQL 的 Java 中的 CRUD Web 应用程序,没有 DAO

[英]CRUD web application in Java with Servlet,JSP and MySQL without DAO

I am working on a simple home library web application using Java EE, Servlets, JSP, and MySQL.我正在使用 Java EE、Servlets、JSP 和 MySQL 开发一个简单的家庭图书馆 Web 应用程序。 My Create, Read, and Delete are working fine but Update is not working.我的创建、读取和删除工作正常,但更新不起作用。 I am not using any form of design patterns, just servlets and POJO.我没有使用任何形式的设计模式,只是使用 servlet 和 POJO。 All examples i try to learn from seem to have used MVC and DAO design patterns.我尝试学习的所有示例似乎都使用了 MVC 和 DAO 设计模式。 Is there any way to achieve the CRUD application without using MVC and DAO patterns?有没有什么方法可以在不使用MVC和DAO模式的情况下实现CRUD应用程序? What is the recommended and best practice for such a simple application?对于这样一个简单的应用程序,推荐的最佳实践是什么?

here is code: UpdateBook.jsp这是代码: UpdateBook.jsp

<%@ page language="java" contentType="text/html; charset=gbk"
    pageEncoding="gbk"%>
<%@ page import ="java.util.ArrayList"%>
<%@page import="book.Book"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gbk">
<link rel="stylesheet" type="text/css" href="../css/styles.css" />
<title>Updated Library Collection</title>
</head>
<body>
<div id="container">
<div id="header"><h1 align="center" style="color:blue">Edit Library Collection</h1></div>
  <div id="wrapper">
    <div id="content" align="center">
            <%  
                request.setCharacterEncoding("gbk");    
                String ISBN=request.getParameter("Isbn");
                String BookTitle=request.getParameter("Title"); 
                String BookAuthor=request.getParameter("Author");   
                String Category=request.getParameter("Category");   
                String Description=request.getParameter("Description");                 
            %>
        <table width="100%" border="0" cellspacing="0" cellpadding="4" align="center" >     
          <tr> 

             <td width="100%" bgcolor="#EAEAEA" colspan="2"> 

              <form name="bookUpdate"  action="/homelibrary/UpdateBookServlet" method="POST">
                <p>
                  <label for="Isbn">ISBN: </label>
                  <input type="text"readonly name="Isbn" id="Isbn" value=<%=ISBN%> >
                  <br><br>
                  <label for="Title">Title: </label>
                  <input type="text" name="Title" id="Title" value=<%=BookTitle%>>
                   <br><br>
                   <label for="Author">Author: </label>
                  <input type="text" name="Author" id="Author" value=<%=BookAuthor%>>
                   <br><br>
                   <label for="Category">Category: </label>
                  <input type="text" name="Category" id="Category" value=<%=Category%>>
                   <br><br>
                   <label for="Description">Description: </label>
                  <input type="text" name="Description" id="Description" value=<%=Description%>>
                   <br><br>               
                   <p> 
                  <input type="submit" name="Submit" value="Submit" onclick="goto">
                    <input type="button" name="Cancel" value="Cancel" onclick="javascript:history.go(-1);"> 
                </p>
             </form>        
          </td>     
          </tr>     
        </table>
    </div>
  </div>
   <div id="footer" align="center">
            <p>&copy; Home Library</p>
   </div>
</body>
</html>

UpdateBookServlet.java更新BookServlet.java

package book;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

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;

@WebServlet("/UpdateBookServlet")
public class UpdateBookServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;        
    public UpdateBookServlet(){
        super();        
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //String forward="";
        String action = request.getParameter("action");

        if (action == ("edit")){

            String Isbn = request.getParameter("Isbn");  
            Book book = null;
            try {
                book = this.getBookByIsbn(Isbn);
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }   

            request.setAttribute("book", book);        
        }

        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/Book/UpdateBook.jsp"); 
        dispatcher.forward(request,response);
    }



    //@SuppressWarnings("unused")
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Book book = new Book();
        response.setContentType("text/html");
        request.setCharacterEncoding("gbk");
        //Get data from form data
        String ISBN = request.getParameter("Isbn");
        String BookTitle = request.getParameter("Title");
        String BookAuthor = request.getParameter("Author");
        String Category = request.getParameter("Category");
        String Description = request.getParameter("Description");


        //@SuppressWarnings("unused")
        //PreparedStatement preStmt = null;
        //Connection cn =null;
        try {

            //Create a java MySQL database connection
            Class.forName("com.mysql.jdbc.Driver");
            String url = "jdbc:mysql://localhost:3306/ebookstore";
            Connection cn = DriverManager.getConnection(url, "admin", "admin");
            PreparedStatement prepStmt= null;
            if(ISBN != null)
            // create the java MySQL update PreparedStatement
            prepStmt = cn.prepareStatement("UPDATE book SET Title=?,Author=?,Category=?,Description=? "+" where Isbn=?");
            //String update = "UPDATE book SET Title=?,Author=?,Category=?,Description=? "+" where Isbn=1111";
            //prepStmt = cn.prepareStatement(update); 
            prepStmt.setString(1, book.getTitle());
            prepStmt.setString(2, book.getAuthor());
            prepStmt.setString(3, book.getCategory());
            prepStmt.setString(4, book.getDescription());
            prepStmt.setInt(5, Integer.parseInt(book.getISBN())); 

            //execute the java preparedStatment
            prepStmt.executeUpdate();
            cn.close(); 
            prepStmt.close();

        } catch (Exception e) {
            System.err.println("Got an exception! ");
            System.err.println(e.getMessage());
        }   

        //forwarding from Servlet to a JSP
        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/Book/QueryBook.jsp"); 
        dispatcher.forward(request,response);

    }

    public Book getBookByIsbn(String isbn) throws ClassNotFoundException {
        Book book = new Book();
        try {           
            //Create a java MySQL database connection
            Class.forName("com.mysql.jdbc.Driver");
            String url = "jdbc:mysql://localhost:3306/homelib";
            Connection cn = DriverManager.getConnection(url, "root", "admin");
            PreparedStatement preparedStatement = cn.
                    prepareStatement("SELECT * FROM book where Isbn=?");
            preparedStatement.setString(1, isbn);
            ResultSet rs = preparedStatement.executeQuery();
            if (rs.next()) {
                book.setISBN(rs.getString("Isbn"));
                book.setTitle(rs.getString("Title"));
                book.setAuthor(rs.getString("Author"));
                book.setCategory(rs.getString("Category"));
                book.setDescription(rs.getString("Description"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return book;
    }       
}

Button in QueryBook.jsp QueryBook.jsp 中的按钮

<td><a href="/homelibrary/UpdateBookServlet?action=edit&Isbn=<c:out value="${book.Isbn}"/>">Update</a></td>

You said in your comment:你在评论中说:

The update page return with null for all the values.更新页面为所有值返回 null。

That is, because you intantiate the Book object In UpdateBookServlet.java也就是说,因为您在 UpdateBookServlet.java 中定义了 Book 对象

    Book book = new Book();

but you set the request parameters into separate string objects:但是您将请求参数设置为单独的字符串对象:

    String ISBN = request.getParameter("Isbn");
    String BookTitle = request.getParameter("Title");
    String BookAuthor = request.getParameter("Author");
    String Category = request.getParameter("Category");
    String Description = request.getParameter("Description");

But never use them.但永远不要使用它们。 Instead you add data from the empty Book object:相反,您从空的 Book 对象添加数据:

        prepStmt.setString(1, book.getTitle());
        prepStmt.setString(2, book.getAuthor());
        prepStmt.setString(3, book.getCategory());
        prepStmt.setString(4, book.getDescription());
        prepStmt.setInt(5, Integer.parseInt(book.getISBN()));

This example is for updating a book's information when a user is logged in on the session此示例用于在用户登录会话时更新书籍信息

Insert this at the top of your JSP to identify the user on the session将其插入 JSP 的顶部以标识会话中的用户

if (session!=null && request.getSession().getAttribute("loggedin") != null) {
    if (request.getSession().getAttribute("role").equals("Student")) {
        response.sendRedirect("index.jsp");
        return;
    } 
} else {
    response.sendRedirect("index.jsp");
    return;
} %>

<% if (request.getSession().getAttribute("loggedin") == null) {
    response.sendRedirect("index.jsp");
    return;
}
BookDTO dto = (BookDTO) request.getSession().getAttribute("book");

Then insert this code below in the JSP to post new data to the servlet然后在 JSP 下面插入这段代码,将新数据发布到 servlet

<form method="POST" action="EditBookServlet">
   <div class="form-submit">
   My Information
   <div class="submit">
      <div class="form-row">
         <div class="x">
            <label>Name</label>
            <input type="text" class="form" value="<%= dto.getName()%>" name="name">
         </div>
         <div class="x">
            <label>Author</label>
            <input type="author" class="form" value="<%= dto.getAuthor()%>" name="author">
         </div>
         <div class="form x">
            <button class="btn" type="submit">Save Changes</button>
         </div>
      </div>
   </div>
</form>

In the EditBookServlet, insert this code在 EditBookServlet 中,插入此代码

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {

    try {
        BookDB db = new BookDB();
        BookDTO dto = db.getBookByID(((BookDTO) 
        request.getSession().getAttribute("book")).getId());

        dto.setName(request.getParameter("name"));
        dto.setAuthor(request.getParameter("author"));

        db.updateBook(dto);
        request.getSession().setAttribute("book", dto);

In the StudentDB java file insert this to find the book by Id and then to update the book sql file在StudentDB java文件中插入这个以通过Id查找书籍然后更新书籍sql文件

public BookDTO getBookByID(int id) {

    BookDTO obj = null;
    String query = "Select * from book where id=?";
    PreparedStatement pst = null;
    ResultSet rs = null;

    try {
        pst = conn.prepareStatement(query);
        pst.setInt(1,id);
        rs = pst.executeQuery();
        if (rs != null) {
            if (rs.next()) {
                obj = new BookDTO();
                obj.setId(rs.getInt(1));
                obj.setName(rs.getString(2));
                obj.setAuthor(rs.getAuthor(3));

        } catch (SQLException ex) {
               Logger.getLogger(BookDB.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
             if (rs != null) {
                try {
                     rs.close();
                } catch (SQLException ex) {
                     Logger.getLogger(BookDB.class.getName()).log(Level.SEVERE, null, ex);
             }
        }

 public boolean updateBook(BookDTO obj) {
     int affectedRows = 0;
     String query = "update `book` set name=? , author=lower(?)   where id=?";
     PreparedStatement pst = null;
     try {
         pst = conn.prepareStatement(query);
         pst.setString(1,obj.getName());
         pst.setString(2,obj.getAuthor());
         pst.setInt(10, obj.getId());
         System.out.println(pst);

         affectedRows = pst.executeUpdate();
    } catch (SQLException ex) {
         Logger.getLogger(Book.class.getName()).log(Level.SEVERE, null, ex);
    }
    return affectedRows > 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM