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

Posted

技术标签:

【中文标题】带有 Servlet、JSP 和 MySQL 的 Java 中的 CRUD Web 应用程序,没有 DAO【英文标题】:CRUD web application in Java with Servlet,JSP and MySQL without DAO 【发布时间】:2017-06-12 23:11:14 【问题描述】:

我正在使用 Java EE、Servlet、JSP 和 mysql 开发一个简单的家庭图书馆 Web 应用程序。我的创建、读取和删除工作正常,但更新不工作。我没有使用任何形式的设计模式,只是使用了 servlet 和 POJO。我尝试学习的所有示例似乎都使用了 MVC 和 DAO 设计模式。有什么方法可以实现 CRUD 应用程序不使用 MVC 和 DAO 模式?对于这样一个简单的应用程序,推荐和最佳做法是什么?

代码如下: 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  border="0" cellspacing="0" cellpadding="4" align="center" >     
          <tr> 

             <td  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

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;
           

QueryBook.jsp中的按钮

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

【问题讨论】:

推荐的做法是使用适当的设计模式。也就是说,是否使用设计模式本身并不影响数据库更新是否有效。如果您需要这方面的帮助,您必须提供 minimal reproducible example。 有我的servlet和jsp页面。更新页面的所有值都返回 null。 【参考方案1】:

你在评论中说:

更新页面的所有值都返回 null。

也就是说,因为您在 UpdateBookServlet.java 中实例化了 Book 对象

    Book book = new Book();

但是您将请求参数设置为单独的字符串对象:

    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");

但永远不要使用它们。相反,您从空 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()));

【讨论】:

【参考方案2】:

此示例用于在用户登录会话时更新图书信息

在你的 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");

然后在下面的 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>

在 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);

在 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;

【讨论】:

以上是关于带有 Servlet、JSP 和 MySQL 的 Java 中的 CRUD Web 应用程序,没有 DAO的主要内容,如果未能解决你的问题,请参考以下文章

带有 JSP/Servlet 和 Ajax 的简单计算器

使用jsp,servlet,mysql搜索和更新相应的数据

jsp+servlet+MySQL

jsp+servlet+mysql简单实现用户登陆注册

jsp+servlet+MySQL

jsp和servlet操作mysql中文乱码问题的解决办法