21 August 2016

Add update delete với Mysql JSP & Servlet trong Java NetBeans

Database mysql
http://localhost:8084/baiTest1/index.jsp
http://localhost:8084/baiTest1/insert.jsp
Khi ta nhấn insert button sẻ hiển thị trở lại trang index.jsp với sản phẩm vửa được nhập :
http://localhost:8084/baiTest1/update.jsp?id=001
Tương tự khi update xong chúng ta củng hiển thị lại List các sản phẩm . và sản phẩm được cập nhật. Tương ứng khi ta nhận delete thì sản phẩm sẻ bị xóa đi, và cập nhật lại table của chúng ta. OK bài này như sau :
Để kết nối mysql chúng ta cần driver : mysql_connector-java-5.x.x-bin.jar. hoặc nếu dùng mysql workbench thì C:\Program Files\MySQL\Connector.J 5.1 hoặc các bạn có thể search ở google. và down load về bỏ vào thư mục lib bên dưới thư mục Webcontent/Web-inf/lib.
Hình ảnh toàn bộ Project của NetBeans như sau :
Page: index.jsp
Java 2016
<%-- 
    Document   : index
    Created on : Aug 20, 2016, 10:06:12 AM
    Author     : Lonely
--%>

<%@page import="com.examp.giaima.SanPhamDAO"%>
<%@page import="com.examp.giaima.SanPham"%>
<%@page import="java.util.ArrayList"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
         pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
        <title>Product Information</title>
    </head>
    <body>
        <% ArrayList<SanPham> lst = new SanPhamDAO().getAllProducts(); %>
       
        <h1 align="center">List Product</h1>
        <table border="1" width="80%" align="center">
            <tr>
                <th>Product's ID</th>
                <th>Product's Name</th>
                <th>Provider</th>
                <th>Unit's Price</th>
                <th colspan="3">Menu</th>
            </tr>
            <%
                for (SanPham sp : lst) {
                    String editURL = "update.jsp?id=" + sp.getID();
                    String deleteURL = "DeleteServlet?id=" + sp.getID();
            %>
            <tr>
                <td><%= sp.getID() %></td>
                <td><%=sp.getName()%></td>
                <td><%=sp.getCompany()%></td>
                <td><%=sp.getPrice()%></td>
                <td><a href="insert.jsp">Insert</a></td>
                <td><a href="<%=editURL%>">Update</a></td>
                <td><a href="<%=deleteURL%>">Delete</a></td>
            </tr>
            <%
                }
            %>
        </table>
    </body>
</html>
Page: insert.jsp
Java 2016
<%-- 
    Document   : insert
    Created on : Aug 21, 2016, 12:57:47 PM
    Author     : Lonely
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Insert Product</title>
    </head>
    <body>
        <form action="InsertServlet" method="POST">
            <h1>Insert New Product</h1>
            <table>
                <tr>
                    <td>Product's ID</td>
                    <td><input type="text" name="id"></td>
                </tr>
                <tr>
                    <td>Product's Name</td>
                    <td><input type="text" name="name"></td>
                </tr>
                <tr>
                    <td>Company</td>
                    <td><input type="text" name="company"></td>
                </tr>
                <tr>
                    <td>Price</td>
                    <td><input type="text" name="price"></td>
                </tr>
                <tr>

                    <td colspan="2" align="right">
                        <button type="submit" name="insert">Insert</button>
                        <button type="reset" name="reset">Reset</button>
                    </td>
                </tr>
        </form>
</body>
</html>
Page: update.jsp
Java 2016
<%-- 
    Document   : update
    Created on : Aug 21, 2016, 8:22:59 PM
    Author     : Lonely
--%>
<%@page import="com.examp.giaima.SanPhamDAO"%>
<%@page import="com.examp.giaima.SanPham"%>
<%@page import="java.util.ArrayList"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Update JSP</title>
    </head>
    <body>
        <%
            String id = request.getParameter("id");
            SanPham sp = new SanPhamDAO().getSanPhamID(id);
        %>
        <form action="UpdateServlet" method="POST">
            <h1>Update New Product</h1>
            <table>
                <tr>
                    <td>Product's ID</td>
                    <td><input type="text" name="id" value="<%=sp.getID()%>"></td>
                </tr>
                <tr>
                    <td>Product's Name</td>
                    <td><input type="text" name="name" value="<%=sp.getName()%>"></td>
                </tr>
                <tr>
                    <td>Company</td>
                    <td><input type="text" name="company" value="<%=sp.getCompany()%>"></td>
                </tr>
                <tr>
                    <td>Price</td>
                    <td><input type="text" name="price" value="<%=sp.getPrice()%>"></td>
                </tr>
                <tr>

                    <td colspan="2" align="right">
                        <button type="submit" name="Update">Update</button>
                        <button type="reset" name="reset">Reset</button>
                    </td>
                </tr>
        </form>
    </body>
</html>
Class ConnectDB.java
Java 2016
package com.examp.giaima;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 *
 * @author Lonely
 */
public class ConnectDB {

    private Connection conn = null;
    private Statement stmt = null;
    private ResultSet rs = null;

    protected void hasDriver() {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (Exception e) {
            System.out.println("Invalid Driver!! Please check this driver...");
        }

    }
    protected Connection openConnect() {
        try {
            if (conn == null) {
                hasDriver();
                String url = "jdbc:mysql://localhost/db_bai3";
                conn = DriverManager.getConnection(url, "root", "1234567");
            }
        } catch (Exception e) {
            System.out.println("Error Connecton! Please check url or username and password of mysql!");
        }
        return conn;
    }

    protected Statement getStatement() {
        try {
            if (stmt == null) {
                stmt = openConnect().createStatement();
            }
        } catch (Exception e) {
            System.out.println("Please check statement");
        }
        return stmt;
    }

    protected void closeConnect() {
        try {
            if (conn != null) {
                conn.close();
            }
            if (rs != null & !rs.isClosed()) {
                rs.close();
            }
            if (stmt != null) {
                stmt.close();
            }
        } catch (Exception e) {
            System.out.println("Please check close connect, stmt, resutlset");
        }

    }

}
Class SanPham.java
Java 2016
package com.examp.giaima;

/**
 *
 * @author Lonely
 */
public class SanPham {

    private String ID;
    private String name;
    private String company;
    private double price;

    public SanPham(String ID, String name, String company, double price) {
        this.ID = ID;
        this.name = name;
        this.company = company;
        this.price = price;
    }

    public String getID() {
        return ID;
    }

    public void setID(String ID) {
        this.ID = ID;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getCompany() {
        return company;
    }

    public void setCompany(String company) {
        this.company = company;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

}
Class SanPhamDAO.java
Java 2016
package com.examp.giaima;

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

/**
 *
 * @author Lonely
 */
public class SanPhamDAO {

    private Connection conn = null;
    private PreparedStatement stmt = null;
    private ResultSet rs = null;
    private ConnectDB connectdb;

    public SanPhamDAO() {
        connectdb = new ConnectDB();
    }

    public ArrayList<SanPham> getAllProducts() {
        ArrayList<SanPham> list = new ArrayList();
        String sql = "SELECT * FROM db_bai3.sanpham";
        try {
            rs = connectdb.getStatement().executeQuery(sql);
            while (rs.next()) {
                String id = rs.getString("id");
                String name = rs.getString("name");
                String company = rs.getString("company");
                double price = rs.getDouble("price");
                SanPham sp = new SanPham(id, name, company, price);
                list.add(sp);
            }
        } catch (Exception e) {
            System.out.println("Please check getAllProduct index.jsp in SanPhamDAO");
        }
        connectdb.closeConnect();
        return list;
    }

    public boolean insertNew(SanPham sp) throws SQLException {
        String sql = "INSERT INTO `db_bai3`.`sanpham` (`id`, `name`, `company`, `price`) VALUES (?, ?, ?, ?);";
        stmt = connectdb.openConnect().prepareStatement(sql);
        stmt.setString(1, sp.getID());
        stmt.setString(2, sp.getName());
        stmt.setString(3, sp.getCompany());
        stmt.setDouble(4, sp.getPrice());
        return stmt.executeUpdate() > 0;
    }

    public boolean updateOld(SanPham sp) throws SQLException {
        String sql = "UPDATE `db_bai3`.`sanpham` SET `name`=?, `company`=?, `price`=? WHERE `id`=?;";
        stmt = connectdb.openConnect().prepareStatement(sql);
        stmt.setString(1, sp.getName());
        stmt.setString(2, sp.getCompany());
        stmt.setDouble(3, sp.getPrice());
        stmt.setString(4, sp.getID());
        return stmt.executeUpdate() > 0;
    }

    public boolean delete(String id) throws SQLException {
        String sql = "DELETE FROM `db_bai3`.`sanpham` WHERE `id`=?";
        stmt = connectdb.openConnect().prepareStatement(sql);
        stmt.setString(1, id);
        return stmt.executeUpdate() > 0;
    }

    public SanPham getSanPhamID(String id) throws SQLException {
        String sql = "SELECT * FROM SanPham WHERE id=?";
        stmt = connectdb.openConnect().prepareStatement(sql);
        stmt.setString(1, id);
        rs = stmt.executeQuery();
        SanPham sp = null;
        while (rs.next()) {
            String idsp = rs.getString("id");
            String name = rs.getString("name");
            String company = rs.getString("company");
            double price = rs.getDouble("price");
            sp = new SanPham(idsp, name, company, price);
        }
        return sp;
    }
}
"New > Servlet.."   Add infomation to deployment descriptor (web.xml)
Page Servlet InsertServlet.java
Java 2016
package com.examp.giaima;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Lonely
 */
public class InsertServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id = request.getParameter("id");
        String name = request.getParameter("name");
        String company = request.getParameter("company");
        double price = Double.parseDouble(request.getParameter("price"));

        SanPham sp = new SanPham(id, name, company, price);
        SanPhamDAO spdao = new SanPhamDAO();
        try {
            if (spdao.insertNew(sp)) {
                response.sendRedirect("index.jsp");
            } else {
                response.sendRedirect("error.jsp");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
Page Servlet UpdateServlet.java
Java 2016
package com.examp.giaima;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Lonely
 */
public class UpdateServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String id = request.getParameter("id");
        String name = request.getParameter("name");
        String company = request.getParameter("company");
        double price = Double.parseDouble(request.getParameter("price"));

        SanPham sp = new SanPham(id, name, company, price);
        SanPhamDAO spdao = new SanPhamDAO();
        try {
            if (spdao.updateOld(sp)) {
                response.sendRedirect("index.jsp");
            } else {
                response.sendRedirect("error.jsp");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
Page servlet DeleteServlet.java
Java 2016
package com.examp.giaima;

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.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.examp.giaima.SanPhamDAO;

/**
 *
 * @author Lonely
 */
public class DeleteServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
         String masp = request.getParameter("id");
        SanPhamDAO spdao = new SanPhamDAO();
        try {
            if (spdao.delete(masp)) {
                response.sendRedirect("index.jsp");
            } else {
                response.sendRedirect("error.jsp");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    

}

1 nhận xét:

 

BACK TO TOP

Xuống cuối trang