从jsp视图中删除。删除它的行时无法获取表ID

时间:2014-09-06 17:31:46

标签: java mysql jsp servlets

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

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

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

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

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

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


请根据jsp,servlet,model,jdbc帖子帮助我:


//费用模型

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

//删除servlet

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

1 个答案:

答案 0 :(得分:0)

您没有从您的方法将记录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来识别记录做你想做的任何操作