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

时间:2017-01-27 09:52:56

标签: java mysql jsp servlets dao

我正在使用Java EE,Servlets,JSP和MySQL开发一个简单的家庭库Web应用程序。我的创建,读取和删除工作正常,但更新无效。我没有使用任何形式的设计模式,只是servlet和POJO。我尝试学习的所有示例似乎都使用了MVC和DAO设计模式。有没有办法在不使用MVC和DAO 模式的情况下实现CRUD应用程序?这种简单应用的推荐和最佳实践是什么?

这里是代码: 的 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

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>

2 个答案:

答案 0 :(得分:0)

你在评论中说:

  

对于所有值,更新页面返回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()));

答案 1 :(得分:0)

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

将此内容插入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;
}