【问题标题】:delete from jsp view. can't get the table id while deleting it’s row从 jsp 视图中删除。删除行时无法获取表ID
【发布时间】:2014-09-06 17:31:46
【问题描述】:

我的任务:我必须从 jsp 视图中删除对表“testtable”每一行的操作。

我的问题:删除行时无法获取表 ID。

使用的应用技术: jsp作为视图,servlet作为控制器,setter和getter方法作为模型,jdbc代码进行数据库操作。

后端 mysql:=我有两个表,一个“userinfo”用于验证,另一个表“testtable”。

对于两个表连接,我在jsp中使用了隐藏字段输入,而不是使用外键关系。

在控制台打印中我们可以看到点击删除按钮后 com.mysql.jdbc.JDBC4PreparedStatement@1f4bcaf:从 id=0 和 email='myswagt@yahoo.com' 的测试表中删除 在家 servlet 用户 ID 为 0


请根据下面的jsp,servlet,model,jdbc post帮助我:


//费用模型

package com.intermediateDemo.home.dto;
public class ItemBean {
private  int id;
private  String email;
private String itemName;
private Double itemPrice;
private String transactionTime;
private  int userid;

public ItemBean() {
}
public ItemBean(int id, String email, String itemName, Double itemPrice, String    transactionTime) {
    this.id = id;
    this.itemName = itemName;
    this.itemPrice = itemPrice;
    this.transactionTime = transactionTime;
    this.email = email;
}
public String toString() {


    StringBuilder stringBuilder = new StringBuilder();
    stringBuilder.append("\n----------------------------------------------------------------------------------------------\n");
    stringBuilder.append("Id: " + id);
    //stringBuilder.append("\tName: " + firstName + ' ' + middleName + ' ' + lastName);
    stringBuilder.append("\titemname: " + itemName);
    stringBuilder.append("\titemprice: " + itemPrice);

    stringBuilder.append("\ttime: " + transactionTime);
       stringBuilder.append("\n----------------------------------------------------------------------------------------------\n");

    return stringBuilder.toString();

}

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}
public int getUserid() {
    return userid;
}

public void setUserid(int userid) {
    this.userid = userid;
}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getItemName() {
    return itemName;
}

public void setItemName(String itemName) {
    this.itemName = itemName;
}

public Double getItemPrice() {
    return itemPrice;
}

public void setItemPrice(Double itemPrice) {
    this.itemPrice = itemPrice;
}

public String getTransactionTime() {
    return transactionTime;
}

public void setTransactionTime(String transactionTime) {
    this.transactionTime = transactionTime;
}
}

//用户模型

package com.intermediateDemo.login.dto;
public class LoginBean {

private int userid;
private String email;
private String password;
public boolean valid;
private String lastName;
private String firstName;

public LoginBean() {
}

public LoginBean(String email, String lastname, String firstname) {
    this.email = email;
    this.firstName = firstname;
    this.lastName = lastname;

}

public int getUserid() {
    return userid;
}

public void setUserid(int userid) {
    this.userid = userid;
}

public String getPassword() {
    return password;
}

public void setPassword(String password) {
    this.password = password;
}

public boolean isValid() {
    return valid;
}

public void setValid(boolean valid) {
    this.valid = valid;
}

public void setFirstName(String firstName) {
    this.firstName = firstName;
}

public void setLastName(String lastName) {
    this.lastName = lastName;
}

public String getLastName() {
    return lastName;
}

public String getFirstName() {
    return firstName;
}

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}
}

//删除小服务程序

package com.intermediateDemo.home.controller;
import com.intermediateDemo.home.dao.ItemDao;
import com.intermediateDemo.home.dao.ItemDaoFactory;
import com.intermediateDemo.home.dto.ItemBean;
import com.intermediateDemo.login.dto.LoginBean;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;


public class DeleteExpense extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws NumberFormatException, ServletException, IOException {
ItemBean item = new ItemBean() ;


    try {
        ItemDao dao = ItemDaoFactory.getItemDao();
        HttpSession session = request.getSession(false);
        LoginBean user = (LoginBean) session.getAttribute("user");
        item.setId(Integer.parseInt(request.getParameter("id")));
        item.setEmail(user.getEmail());
        dao.deleteItem(item, user);
    } catch (Exception e) {
        e.printStackTrace();
    }
    finally {
        response.sendRedirect("homeservlet");
    }

}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    RequestDispatcher view;
    view = request.getRequestDispatcher("/home/home.jsp");
    view.forward(request,response);
}
}

//jdbc代码

 public void deleteItem(ItemBean item, LoginBean user) throws Exception {

   try {
        JdbcConnection connection =   new JdbcConnection();
        String query = "delete from testtable where id=? and email=?";
        Connection con = connection.getConnection();
        PreparedStatement pstm = con.prepareStatement(query);
        pstm.setInt(1, item.getId());
        pstm.setString(2, user.getEmail());
        System.out.println(pstm);
        pstm.executeUpdate();

    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    }
}

//jsp视图

<%--
Created by IntelliJ IDEA.
User: Dell
Date: 3/13/14
Time: 8:12 PM
To change this template use File | Settings | File Templates.
--%>
<%@ page import="com.intermediateDemo.home.dto.ItemBean" %>
<%@ page import="java.util.List" %>
<%@ page import="com.intermediateDemo.login.dto.LoginBean" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>

<title>home</title>
<link rel="stylesheet" type="text/css" href="style_css/mystylesheet.css">
<link rel=”stylesheet” href=”resource/css/bootstrap.css”  type=”text/css”/>
</head>
<body>
<jsp:include page="../includes/header.jsp"/>
<div id="content" style="margin-left: 330px;margin-bottom: 10px">
Welcome <%=session.getAttribute("email")%>

your id is  <%=session.getAttribute("userid")%>
your firstname is  <%=session.getAttribute("firstname")%>
<h2>Your Financial Management</h2>
    <form action="homeservlet" method="post">



        <!--start display-->
        <legend>

            <h2>Expense list</h2>

        </legend>
        <div>
            <table class="table table-bordered table-striped" style="padding-   left:200px;border:2px;border-bottom-color: limegreen">
                <thead>
                <tr style="background: limegreen">


                    <th >Expense title</th>
                    <th>Expense amount</th>
                    <th>Expense Date</th>
                </tr>
                </thead>
                <tbody>



                <c:forEach var="item"  items="${requestScope.itemList}" >
                    <tr style="background:#808080;color:#ffffff">

                        <td><c:out value="${item.getItemName()}"> </c:out></td>
                        <td><c:out value="${item.getItemPrice()}"> </c:out></td>
                        <td><c:out value="${item.getTransactionTime()}"> </c:out></td>
                        <td>
                        <form method="post" action="/deleteexpense">
                            <input type="hidden" name="id" value="${item.id}">
                            <input class="btn btn-mini btn-danger " type="submit" value="Delete"/>
                        <a class="btn btn-mini " href="edit?id=${item.id}">Edit</a>
                         </form>
                        </td>
                    </tr>
                </c:forEach>


                </tbody>
            </table>
        </div>            

    </form>
</div>

<jsp:include page="../includes/footer.jsp"/>
</body>
</html>

//我在DAO里面获取ItemBean的数据

    public List<ItemBean> getItemFromdb(LoginBean user) throws SQLException {
    List<ItemBean> itemList = new ArrayList<ItemBean>();
    JdbcConnection connecton = new JdbcConnection();
    //String query = "select * from testtable where userid = ?";
     String query = "select  * from testtable where  email = ?";
    ResultSet rs;
    try {
        Connection con = connecton.getConnection();
        PreparedStatement pstm = con.prepareStatement(query);
       // pstm.setInt(1, user.getUserid());
        pstm.setString(1,user.getEmail());
        rs = pstm.executeQuery();
        while (rs.next()) {
            ItemBean item = new ItemBean();
            item.setItemName(rs.getString("itemname"));
            item.setItemPrice(rs.getDouble("itemprice"));
            item.setTransactionTime(rs.getString("transactiontime"));
           // item.setUserid(rs.getInt("userid"));
            item.setEmail(rs.getString("email"));
            itemList.add(item); 


        }

        System.out.println("at jdbc code");
        for (ItemBean item1 : itemList) {
            System.out.println(item1.getItemName());
            System.out.println(item1.getItemPrice());
            System.out.println(item1.getTransactionTime());
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return itemList;
}

//项目插入、检索和删除类似操作的jdbc代码在一个页面是

package com.intermediateDemo.home.dao.mysql;
import com.intermediateDemo.common.JdbcConnection;
import com.intermediateDemo.home.dto.ItemBean;
import com.intermediateDemo.login.dto.LoginBean;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;


public class JdbcItemMysql {
public void itemtodb(ItemBean item, LoginBean user) throws Exception {
    JdbcConnection connection = new JdbcConnection();
    //String query = "insert into testtable    (itemname,itemprice,transactiontime,userid) values (?,?,?,?)";
   String query = "insert into testtable (itemname,itemprice,transactiontime,email) values (?,?,?,?)";
    try {
        Connection con = connection.getConnection();
        PreparedStatement pstm = con.prepareStatement(query);
        pstm.setString(1, item.getItemName());
        pstm.setDouble(2, Double.parseDouble(String.valueOf(item.getItemPrice())));
        pstm.setString(3, item.getTransactionTime());
        pstm.setString(4, user.getEmail());
       // pstm.setInt(4,user.getId());
        pstm.executeUpdate();
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    }
}

public List<ItemBean> getItemFromdb(LoginBean user) throws SQLException {
    List<ItemBean> itemList = new ArrayList<ItemBean>();
    JdbcConnection connecton = new JdbcConnection();
    //String query = "select * from testtable where userid = ?";
     String query = "select  * from testtable where  email = ?";
    ResultSet rs;
    try {
        Connection con = connecton.getConnection();
        PreparedStatement pstm = con.prepareStatement(query);
       // pstm.setInt(1, user.getUserid());
        pstm.setString(1,user.getEmail());
        rs = pstm.executeQuery();
        while (rs.next()) {
            ItemBean item = new ItemBean();
            item.setItemName(rs.getString("itemname"));
            item.setItemPrice(rs.getDouble("itemprice"));
            item.setTransactionTime(rs.getString("transactiontime"));
           // item.setUserid(rs.getInt("userid"));
            item.setEmail(rs.getString("email"));
            itemList.add(item); 


        }

        System.out.println("at jdbc code");
        for (ItemBean item1 : itemList) {
            System.out.println(item1.getItemName());
            System.out.println(item1.getItemPrice());
            System.out.println(item1.getTransactionTime());
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return itemList;
}






public void deleteItem(ItemBean item, LoginBean user) throws Exception {

   try {
        JdbcConnection connection =   new JdbcConnection();
        String query = "delete from testtable where id=? and email=?";
        Connection con = connection.getConnection();
        PreparedStatement pstm = con.prepareStatement(query);
        pstm.setInt(1, item.getId());
        pstm.setString(2, user.getEmail());
        System.out.println(pstm);
        pstm.executeUpdate();

    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    }
}

【问题讨论】:

  • 所有方法看起来都很好。将ItemBean 作为请求属性加载时可能存在问题。请提供从您的 DAO 中检索ItemBean 数据的方法。
  • 请尽快帮助我
  • 我没有看到项目记录的 ID 被保存到您的 getItemFromdb() 中的 ItemBean 对象中
  • 好的,让我看看@PrasadKhode
  • 哦,项目的 id 是自动递增的......所以我该怎么办-@PrasadKhode

标签: java mysql jsp servlets


【解决方案1】:

您没有将记录 id 从您的方法传递到 jsp 页面。你的 getItemFromdb() 应该是这样的

public List<ItemBean> getItemFromdb(LoginBean user) throws SQLException {

    //  whatever you are doing comes here
    while (rs.next()) {
        ItemBean item = new ItemBean();
        item.setId(rs.getInt("id");  //  you need to have this, here id is the the primary key of the table
        item.setItemName(rs.getString("itemname"));
        item.setItemPrice(rs.getDouble("itemprice"));
        item.setTransactionTime(rs.getString("transactiontime"));
     // item.setUserid(rs.getInt("userid"));
        item.setEmail(rs.getString("email"));
        itemList.add(item); 
    }

    //  rest of the code
}

这样在jsp页面中就可以使用这个id来标识记录做任何你想做的操作

【讨论】:

  • 我不想在 jsp 视图中显示项目 ID,但我只想删除表格行。而且我无法传递项目ID,但能够在jdbc void deleteItem(ItemBean item, LoginBean user)的方法中传递用户emailid
  • 在控制台打印中显示登录用户的 emailid 已通过让我们说 emailid=myswagat@yahoo.com 但项目行 id = 0 总是......从 id=0 和 email='myswagt@yahoo.com' 的 testtable 中删除
  • 是的,因为您在 jsp 页面中没有 id 值。由于您模型中的 id 是 int 类型,因此其值始终为“0”。在 DeleteExpense: doPost() 中,您正在从请求中读取“id”。只需尝试在您正在显示的表格中显示记录的 ID,我想您就会明白我想要传达的内容
  • 你可以在jsp页面看到&lt;input type="hidden" name="id" value="${item.id}"&gt;
  • 请告诉我,如果我在 mysql 数据库中使用 item id 是自动递增的,那么为什么我需要将 item id 放在 jsp 中。但是我使用 &lt;input type="hidden" name="id" value="${item.id}"&gt; 删除 jsp 的形式,你可以在上面看到
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-29
  • 1970-01-01
  • 2016-11-06
  • 1970-01-01
  • 2021-09-20
相关资源
最近更新 更多