20 August 2016

Insert Update Delete Mysql Jsp & Servlet in Java NetBeans

Database mysql

http://localhost:8084/bai4/index.jsp
d1
http://localhost:8084/bai4/insert.jsp
d1
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 :
d1
http://localhost:8084/bai4/edit.jsp?masp=001
d1
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.example.giaima.SanPhamDAO"%>
<%@page import="com.example.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="2"><a href="insert.jsp">Insert New</a></th>
            </tr>
            <%
                for (SanPham sp : lst) {
                    String editURL = "edit.jsp?masp=" + sp.getMasp();
                    String deleteURL = "DeleteServlet?masp=" + sp.getMasp();
            %>
            <tr>
                <td><%=sp.getMasp()%></td>
                <td><%=sp.getTensp()%></td>
                <td><%=sp.getNhacc()%></td>
                <td><%=sp.getGiadv()%></td>
                <td><a href="<%=editURL%>">Edit</a></td>
                <td><a href="<%=deleteURL%>">Delete</a></td>
            </tr>
            <%
                }
            %>
        </table>
    </body>
</html>
Page: insert.jsp
Java 2016
<%-- 
    Document   : insert
    Created on : Aug 20, 2016, 10:21:14 AM
    Author     : Lonely
--%>
<%@ 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>Insert Product</title>
    </head>
    <body>
        <form action="InsertServlet">
            <h1>Insert New Product</h1>
            <table>
                <tr>
                    <td>Product's ID</td>
                    <td><input type="text" name="masp"></td>
                </tr>
                <tr>
                    <td>Product's Name</td>
                    <td><input type="text" name="tensp"></td>
                </tr>
                <tr>
                    <td>Provider</td>
                    <td><input type="text" name="nhacc"></td>
                </tr>
                <tr>
                    <td>Unit's Price</td>
                    <td><input type="text" name="giadv"></td>
                </tr>
                <tr>

                    <td colspan="2" align="right">
                        <button type="submit" name="insert">Insert</button>
                        <button type="reset" name="reset">Reset</button>
                    </td>
                </tr>
            </table>
        </form>
    </body>
</html>
Page: edit.jsp
Java 2016
<%-- 
    Document   : edit
    Created on : Aug 20, 2016, 10:21:56 AM
    Author     : Lonely
--%>

<%@page import="com.example.giaima.SanPhamDAO"%>
<%@page import="com.example.giaima.SanPham"%>
<%@ 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>Edit Product</title>
    </head>
    <body>
        <% SanPham sp = new SanPhamDAO().getProductByID(request.getParameter("masp"));%>
        <form action="UpdateServlet">
            <h1>Edit Product</h1>
            <table>
                <tr>
                    <td>Product's ID</td>
                    <td><input type="text" name="masp" value="<%=sp.getMasp()%>" readonly="readonly"></td>
                </tr>
                <tr>
                    <td>Product's Name</td>
                    <td><input type="text" name="tensp" value="<%=sp.getTensp()%>"></td>
                </tr>
                <tr>
                    <td>Provider</td>
                    <td><input type="text" name="nhacc" value="<%=sp.getNhacc()%>" /></td>
                </tr>
                <tr>
                    <td>Unit's Price</td>
                    <td><input type="text" name="giadv" value="<%=sp.getGiadv()%>" /></td>
                </tr>
                <tr>

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

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

public class ConnectDB {

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

    protected void hasDriver() throws Exception {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException ex) {
            throw new Exception("Invalid Driver!!Please check this drver....");
        }
    }

    protected Connection openConnect() throws Exception {
        if (connect == null) {
            hasDriver();
            String url = "jdbc:mysql://localhost/db_bai3";
            try {
                this.connect = DriverManager.getConnection(url, "root", "1234567");
            } catch (SQLException e) {
                throw new Exception(e.getMessage() + "Connect failed to database .... ");
            }
        }
        return connect;
    }

    protected Statement getStatement() throws SQLException, Exception {
        if (stmt == null) {
            stmt = openConnect().createStatement();
        }
        return stmt;
    }

    protected void closeConnet() throws SQLException {
        if (rs != null && !rs.isClosed()) {
            rs.close();
        }
        if (stmt != null) {
            stmt.close();
        }
        if (connect != null) {
            connect.close();
        }
    }

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

public class SanPham {

    private String masp;
    private String tensp;
    private String nhacc;
    private double giadv;

    public SanPham(String masp, String tensp, String nhacc, double giadv) {
        this.masp = masp;
        this.tensp = tensp;
        this.nhacc = nhacc;
        this.giadv = giadv;
    }

    public SanPham() {
    }

    public String getMasp() {
        return masp;
    }

    public void setMasp(String masp) {
        this.masp = masp;
    }

    public String getTensp() {
        return tensp;
    }

    public void setTensp(String tensp) {
        this.tensp = tensp;
    }

    public String getNhacc() {
        return nhacc;
    }

    public void setNhacc(String nhacc) {
        this.nhacc = nhacc;
    }

    public double getGiadv() {
        return giadv;
    }

    public void setGiadv(double giadv) {
        this.giadv = giadv;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((masp == null) ? 0 : masp.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        SanPham other = (SanPham) obj;
        if (masp == null) {
            if (other.masp != null) {
                return false;
            }
        } else if (!masp.equals(other.masp)) {
            return false;
        }
        return true;
    }

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

import com.example.giaima.SanPham;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
/**
 *
 * @author Lonely
 */
public class SanPhamDAO {

    private Connection connect = null;
    private Statement stmt = null;
    private ResultSet rs = null;
    private ConnectDB connectdb;

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

    public ArrayList<SanPham> getAllProducts() throws Exception {
        ArrayList<SanPham> lst = new ArrayList<SanPham>();
        String strSQL = "select * from SanPham";
        try {
            rs = connectdb.getStatement().executeQuery(strSQL);
            while (rs.next()) {
                String ms = rs.getString("masp");
                String ten = rs.getString("tensp");
                String ncc = rs.getString("nhacc");
                double gia = Double.parseDouble(rs.getString("giadv"));
                SanPham sp = new SanPham(ms, ten, ncc, gia);
                lst.add(sp);
            }
        } catch (Exception e) {
            throw new Exception(e.getMessage() + " Error at : " + strSQL);
        }
        connectdb.closeConnet();
        return lst;
    }

    public boolean insertNew(SanPham sp) throws Exception {
        String sql = "insert into SanPham values(?,?,?,?)";
        PreparedStatement pst = connectdb.openConnect().prepareStatement(sql);
        pst.setString(1, sp.getMasp());
        pst.setString(2, sp.getTensp());
        pst.setString(3, sp.getNhacc());
        pst.setDouble(4, sp.getGiadv());

        return pst.executeUpdate() > 0;

    }

    public boolean deleteProduct(String masp) throws Exception {
        String sql = "delete from SanPham where masp=?";
        PreparedStatement pst = connectdb.openConnect().prepareStatement(sql);
        pst.setString(1, masp);
        return pst.executeUpdate() > 0;
    }

    public int executeUpdate(String strSQL) throws Exception {
        int result = 0;
        try {
            result = connectdb.getStatement().executeUpdate(strSQL);
        } catch (Exception ex) {
            throw new Exception(ex.getMessage() + " Error at: " + strSQL);
        } finally {
            connectdb.closeConnet();
        }
        return result;
    }

    public SanPham getProductByID(String masp) throws Exception {
        String sql = "select * from SanPham where masp=?";
        PreparedStatement pst = connectdb.openConnect().prepareStatement(sql);
        pst.setString(1, masp);
        ResultSet rs = pst.executeQuery();
        SanPham sp = null;
        if (rs.next()) {
            String ms = rs.getString("masp");
            String ten = rs.getString("tensp");
            String ncc = rs.getString("nhacc");
            double gia = Double.parseDouble(rs.getString("giadv"));
            sp = new SanPham(ms, ten, ncc, gia);
        }
        return sp;
    }

    public boolean UpdateProduct(String masp, SanPham newsp) throws Exception {
        String sql = "update SanPham set tensp=?, nhacc=?, giadv=? where masp=?";
        PreparedStatement pst = connectdb.openConnect().prepareStatement(sql);
        pst.setString(1, newsp.getTensp());
        pst.setString(2, newsp.getNhacc());
        pst.setDouble(3, newsp.getGiadv());
        pst.setString(4, newsp.getMasp());
        return pst.executeUpdate() > 0;
    }

}
"New > Servlet.."   Add infomation to deployment descriptor (web.xml)
Page Servlet InsertServlet.java
Java 2016
package com.example.giaima;

import com.example.giaima.SanPhamDAO;
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 doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String masp = request.getParameter("masp");
        String tensp = request.getParameter("tensp");
        String nhacc = request.getParameter("nhacc");
        double giadv = Double.parseDouble(request.getParameter("giadv"));

        SanPham sp = new SanPham(masp, tensp, nhacc, giadv);
        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.example.giaima;

import com.example.giaima.SanPhamDAO;
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 UpdateServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String masp = request.getParameter("masp");
        String tensp = request.getParameter("tensp");
        String nhacc = request.getParameter("nhacc");
        double giadv = Double.parseDouble(request.getParameter("giadv"));

        SanPham sp = new SanPham(masp, tensp, nhacc, giadv);
        SanPhamDAO spdao = new SanPhamDAO();
        try {
            if (spdao.UpdateProduct(masp, sp)) {
                response.sendRedirect("index.jsp");
            } else {
                response.sendRedirect("error.jsp");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

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

import com.example.giaima.SanPhamDAO;
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 DeleteServlet extends HttpServlet {

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

    }

}

0 nhận xét:

Post a Comment

 

BACK TO TOP

Xuống cuối trang