【问题标题】:creating CRUD inserting issue创建 CRUD 插入问题
【发布时间】:2015-11-23 10:22:02
【问题描述】:

我正在尝试从教程创建 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>

【问题讨论】:

  • 为什么要抓ClassNotFoundException
  • netbeans 强迫我这样做
  • 那是因为你把它扔进DBUtil类。

标签: mysql jsp jakarta-ee servlets


【解决方案1】:

首先,我建议/推荐/建议您使用only 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&lt;News&gt;。您对其进行了请求,但您从不迭代 ResultSet 以创建 News 对象并将其添加到 ls 列表中。那是你的问题。

【讨论】:

  • 我在新的jsp页面中创建并调用了它,但我无法在这里编写代码
猜你喜欢
  • 1970-01-01
  • 2017-10-15
  • 1970-01-01
  • 2016-07-14
  • 1970-01-01
  • 1970-01-01
  • 2020-12-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多