创建CRUD插入问题

时间:2015-11-23 10:22:03

标签: mysql jsp java-ee servlets

我正在尝试从教程创建CRUD应用程序,但我陷入问题没有错误在AllPost.jsp它只显示没有数据的元素的标题,我检查了我的mysql数据库,它没有插入任何东西 这是我的代码

AllPost.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib  uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
        <title>JSP Page</title>
    </head>
    <body>
        <div style="width: 1200px; margin-left: auto; margin-right: auto">
            <table cellpadding="10">
                <tr>
                    <th>Id</th>
                    <th>Title</th>
                    <th>Description</th>
                    <th>Detail</th>
                    <th>Category</th>
                    <th>Date</th>
                    <th>Image</th>
                    <th></th>
                </tr>
                <c:forEach items="${AllPost}" var="p">
                    <tr>
                        <td>${p.id}</td>
                        <td>${p.title}</td>
                        <td>${p.description}</td>
                        <td>${p.detail}</td>
                        <td>${p.category}</td>
                        <td>${p.date}</td>
                        <td>${p.image}</td>
                        <td>
                            <a href="edit?id=${p.id}">Edit</a>
                            <a href="delete?id=${p.id}">Delete</a>
                        </td>

                    </tr>

                </c:forEach>
            </table>

        </div>
    </body>
</html>

AllPost.java

package servlet;

import dao.DataAccess;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
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(name="AllPost", urlPatterns={"/AllPost"})
public class AllPost extends HttpServlet {
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException, SQLException {
        request.setAttribute("AllPost", DataAccess.getAll());
        RequestDispatcher rd = request.getRequestDispatcher("AllPost.jsp");
        rd.forward(request, response);

    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        // processRequest(request, response);
        request.setAttribute("AllPost", DataAccess.getAll());
        RequestDispatcher rd = request.getRequestDispatcher("AllPost.jsp");
        rd.forward(request, response);

    }
}

的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"
         xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         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">
    <servlet>
        <servlet-name>AllPost</servlet-name>
        <jsp-file>/AllPost.jsp</jsp-file> 
    </servlet>
    <servlet-mapping>
        <servlet-name>AllPost</servlet-name>
        <url-pattern>/AllPost</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout> 
    </session-config>
    <welcome-file-list>
        <welcome-file>AddNew.html</welcome-file>
    </welcome-file-list>
</web-app>

DataAccess.java

package dao;

public class DataAccess {

    public void addNew(News n){    
        try {
            PreparedStatement ps = DButil.getPreparedStatement("insert into   news values(?,?,?,?,?,?)");
            ps.setString(1,n.getTitle());
            ps.setString(2,n.getDate());
            ps.setString(3,n.getDescription());
            ps.setString(4,n.getDetail());   
            ps.setString(5,n.getCategory());
            ps.setString(6,n.getImage());
            ps.executeUpdate();
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(DataAccess.class.getName()).log(Level.SEVERE, null, ex);   
        } catch (SQLException ex) {
            Logger.getLogger(DataAccess.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public static List<News> getAll()  {

        List<News> ls = new LinkedList<News>();
        try {
            ResultSet rs = DButil.getPreparedStat  ement("select * from news").executeQuery();

        } catch (ClassNotFoundException ex) {
            Logger.getLogger(DataAccess.class.getName()).log(Level.SEVERE,null,ex);
        }catch (SQLException ex){
            Logger.getLogger(DataAccess.class.getName()).log(Level.SEVERE,null,ex);
        }

        return ls;
    }
}

和DButil.java

package db;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
import java.sql.DriverManager;
import java.sql.SQLException;


public class DButil {
    public static PreparedStatement getPreparedStatement(String sql) throws   ClassCastException, ClassNotFoundException, SQLException{

        PreparedStatement ps=null;
        Class.forName("com.mysql.jdbc.Driver");
        String url="jdbc:mysql://localhost/crud";
        String user="root";
        String password="";
        Connection    con=   (Connection) DriverManager.getConnection (url,   user, password);
        ps=(PreparedStatement) con.prepareStatement(sql);
        return ps;
    }
}

ManagerAddNew.jsp


    <%@page import="dao.DataAccess"%>
    <%@page import="model.News"%>
    <%@page import="java.text.SimpleDateFormat"%>
    <%@page import="java.sql.Date"%>
    <%@page contentType="text/html" pageEncoding="UTF-8"%>
    <!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=UTF-8">
            <title>JSP Page</title>
        </head>
        <body>
            <%
                String title=request.getParameter("title");
                Date dateTmp = new Date(System.currentTimeMillis());
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
                String date = dateFormat.format(dateTmp.getTime());
                String description=request.getParameter("description");
                String detail=request.getParameter("detail");
                String category=request.getParameter("category");
                String image=request.getParameter("image");

                News n = new News(0, title, date, description, detail, category, image);
                DataAccess da = new DataAccess();
                da.addNew(n);
                response.sendRedirect("/CRUD_NEWS/AllPost");
          %>

        </body>
    </html>

1 个答案:

答案 0 :(得分:1)

首先,我建议/建议/建议您使用 JDBC API特定的接口类而不是仅使用MySQL的类。

而不是:

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;

使用

import java.sql.Connection;
import java.sql.PreparedStatement;

仅抛出 SQLException

其次,我在这篇SO Post中写了如何正确执行SQL语句(当然不包括事务)。

第三,我在帖子中没有看到调用DataAccess.addNew()方法的地方。

我收集的东西很少:

  1. 为什么要创建News对象作为第一个参数传递0
  2. getAll()方法的List<News>为空。您对其发出了请求但从不迭代ResultSet以创建News对象并将其添加到ls列表中。那是你的问题。