12 September 2016

Assignment JSP Bassic Java NetBeans Login, Insert, Update, Delete template JDBC


Ở bài này: 
-Login chưa validate
-Upload image chỉ là String đường dẫn đến 1 folder đã có ảnh sãn
-Pagination chỉ là bản dựng.
-Các chức năng chỉ là bassic chưa hoàn chỉnh
-Giúp các bạn có cái nhìn đầu tiên về jsp java web



==========Assignment JSP Java web========
Phần hiển thị web
index.jsp
Java 2016
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <link rel="stylesheet" href="css/style.css" />
        <link rel="stylesheet" href="css/nivo-slider.css" type="text/css" media="screen" />
        <link rel="stylesheet" href="css/default/default.css" type="text/css" media="screen" />
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
        <script src="js/jquery.nivo.slider.pack.js" type="text/javascript"></script>
        <title>GT Auto Concepts</title>
    </head>

    <body id="home">
        <div id="wrapper">
            <jsp:include page="header.jsp"></jsp:include>
            <jsp:include page="slide.jsp"></jsp:include>
            <jsp:include page="content.jsp"></jsp:include>
            <jsp:include page="footer.jsp"></jsp:include>
        </div>
    </body>
</html>
header.jsp
Java 2016
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Header</title>
    </head>
    <body>
        <header>
            <div id="acount"><a href="login.jsp" >Login</a></div>
            <div id="logo">
                <h1>Auto Concepts<span id="iisrt"><span id="ii">II</span>  <span id="srt">GT</span></span></h1>
                <div id="tagline">
                    <h2>Show Auto Car</h2>
                </div>
            </div>
            <nav>
                <ul>
                    <li><a href="index.jsp" id="homenav">Home</a></li>
                    <li><a href="#" id="blognav">Blog</a></li>
                    <li><a href="#" id="fullwidthnav">Full width</a></li>
                    <li><a href="#">Contact</a></li>
                    <li><a href="#">About</a></li>
                </ul>
            </nav>
        </header>

    </body>
</html>
slide.jsp
Java 2016
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Slide</title>
    </head>
    <body>
        <!--__--__--__--__--  T H E    S L I D E R --__--__--__--___--__--__--__-->
        <div class="slider-wrapper theme-default">
            <div id="slider" class="nivoSlider">
                <img src="images/slide1.jpg" alt="" />
                <a href="http://geeksband.com"><img src="images/slide2.jpg" alt="" title="Audi A4 Black" /></a>
                <img src="images/slide3.jpg" alt="" title="2017 Ford Mustang Sports Car" />
                <img src="images/slide4.jpg" alt="" />
            </div>
        </div>
        <script type="text/javascript">
            $(window).load(function () {
                $('#slider').nivoSlider({pauseTime: 6000, });
            });
        </script>

    </body>
</html>
content.jsp
Java 2016
<%@page import="dao.CarDAO"%>
<%@page import="java.util.ArrayList"%>
<%@page import="model.Car"%>
<%@page import="model.Car"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Content</title>
        <link href="css/style_product.css" rel="stylesheet" type="text/css"/>
    </head>
    <body>
        <!--Phan trang-->
        <%
            int first = 0, last = 0, pages = 1;
            if (request.getParameter("pages") != null) {
                pages = (int) Integer.parseInt(request.getParameter("pages"));
            }
            int total = new CarDAO().getNumberProduct();
            if (total <= 3) {
                first = 0;
                last = total;
                //SELECT * FROM product.car limit 0,3
            } else {
                first = (pages - 1) * 3;
                last = 3;
            }
            //SELECT * FROM product.car limit 3,3
            ArrayList<Car> list = new CarDAO().getAllCar(first, last);
        %>
        <section>

            <div id="line">
                <div class="dline"></div>
                <h1>Luxury</h1>
                <div class="dline"></div>
            </div>
            <div id="ourserv">
                <%
                    for (Car c : list) {
                %>
                <article>
                    <h1><%=c.getNameCar()%></h1>
                    <img src="<%=c.getImageCar()%>" alt="" />
                    <p><%=c.getDetailCar()%></p>
                    <a href="" class="rm">Read More</a>
                </article>
                <%}%>
            </div>
            <div id="pages"><!--Phan trang-->
                <ul id="pagination-flickr">
                    <a href="index.jsp?pages=<%=total/3 %>">«Previous</a>
                    <%for (int i = 1; i < (total / 3) + 2; i++) {
                            if (pages == i) {%>
                    <a id="cool" href="index.jsp?pages=<%=i%>"><%=i%></a>
                    <%} else {%>
                    <a href="index.jsp?pages=<%=i%>"><%=i%></a>   
                    <%}
                        }%>
                        <a href="index.jsp?pages=<%=total/3+1 %>">Next »</a>
                </ul>
            </div>
        </section>  
    </body>
</html>
footer.jsp
Java 2016
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Footer</title>
    </head>
    <body>
        <!--__--__--__--__--  T H E    F O O T E R --__--__--__--___--__--__--__-->
        <footer>
            <p>Copyright &copy 2016 GT Auto Concepts</p>
        </footer>
    </body>
</html>
Phần đăng nhập quản lý insert update delete
login.jsp
Java 2016
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="en">

    <head>
        <meta charset="utf-8">
        <title>Sign In</title>
        <link href='https://fonts.googleapis.com/css?family=Roboto+Slab:400,100,300,700|Lato:400,100,300,700,900' rel='stylesheet' type='text/css'>
        <link rel="stylesheet" href="css/login_animate.css">
        <link rel="stylesheet" href="css/login_style.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
    </head>

    <body>
        <div class="container">
            <div class="top">
                <h1 id="title" class="hidden"><span id="logo">GT Auto Concepts</span></h1>
            </div>
            <div class="login-box animated fadeInUp">
                <div class="box-header">
                    <h2>Log In</h2>
                </div>
                <form action="LoginServlet" method="POST">
                <label for="username" >Username</label>
                <br/>
                <input type="text" name="username" id="username">
                <br/>
                <label for="password" >Password</label>
                <br/>
                <input type="password" name="password" id="password">
                <br/>
                <button type="submit">Sign In</button>
                <br/>
                </form>
                <a href="#"><p class="small">Forgot your password?</p></a>
            </div>
        </div>
    </body>

    <script>
        $(document).ready(function () {
            $('#logo').addClass('animated fadeInDown');
            $("input:text:visible:first").focus();
        });
        $('#username').focus(function () {
            $('label[for="username"]').addClass('selected');
        });
        $('#username').blur(function () {
            $('label[for="username"]').removeClass('selected');
        });
        $('#password').focus(function () {
            $('label[for="password"]').addClass('selected');
        });
        $('#password').blur(function () {
            $('label[for="password"]').removeClass('selected');
        });
    </script>

</html>
manager.jsp
Java 2016
<%@page import="java.util.ArrayList"%>
<%@page import="dao.CarDAO"%>
<%@page import="model.Car"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>.:: Manager ::.</title>
        <link rel="stylesheet" href="css/style.css" />
        <link rel="stylesheet" href="css/nivo-slider.css" type="text/css" media="screen" />
        <link rel="stylesheet" href="css/default/default.css" type="text/css" media="screen" />
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
        <script src="js/jquery.nivo.slider.pack.js" type="text/javascript"></script>
        <style>
            table{
                width: 80%;
                margin: auto;
                background: #202020;
            }
            td,th{
                padding:  5px 15px 5px 15px;
            }
            tr{
                border-top:1px solid green;
                border-bottom:1px solid #99CC33;
            }
            tr:hover{
                background-color: #000;
                background-size: 100%;
            }
            td{
                border-top: 1px solid #99CC33;
                border-bottom: 0px solid #99CC33;

                line-height: 16px;
                color:#99CC33;
            }
            #title_table{
                background-color: #D08206;
                font-size: large;
                font-family: cursive;
            }
        </style>
    </head>

    <body id="home">
        <div id="wrapper">
            <jsp:include page="header.jsp"></jsp:include>
                <table>
                    <tr id="title_table">
                        <th>ID</th>
                        <th>Name</th>
                        <th>Detail</th>
                        <th>Images</th>
                        <th colspan="2"><a href="insert.jsp" >Insert</th>
                    </tr>
                <%
                    ArrayList<Car> list = new CarDAO().getAllCar();
                    for (Car c : list) {
                        String updateURL = "update.jsp?id_car=" + c.getIdCar();
                        String deleteURL = "DeleteServlet?id_car=" + c.getIdCar();
                %>
                <tr>
                    <td><%=c.getIdCar()%></td>
                    <td><%=c.getNameCar()%></td>
                    <td><%=c.getDetailCar()%></td>
                    <td><img src='<%=c.getImageCar()%>'></td>
                    <td><a href="<%=updateURL%>">Update</a></td>
                    <td><a href="<%=deleteURL%>">Delete</a></td>
                </tr>
                <%}%>
            </table>

            <jsp:include page="footer.jsp"></jsp:include>
        </div>
    </body>
</html>
insert.jsp
Java 2016
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Insert</title>
        <link rel="stylesheet" href="css/style.css" />
        <link rel="stylesheet" href="css/nivo-slider.css" type="text/css" media="screen" />
        <link rel="stylesheet" href="css/default/default.css" type="text/css" media="screen" />
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
        <script src="js/jquery.nivo.slider.pack.js" type="text/javascript"></script>
        <style>
            #box-in{
                width: 65%;
                margin: auto;
                margin-left: 28%;
            }
            #text{
                width: 50%;
                height:25px; 
            }
            #textarea{
                width: 70%;
                height: 120px;
            }
            #bu{
                width: 120px;
                height: 34px;
                display: block;
                font-weight: bold;
            }
        </style>
    </head>
    <body id="home">
        <div id="wrapper">
            <jsp:include page="header.jsp"></jsp:include>
                <div id="box-in">
                    <form action="InsertServlet" method="POST">
                        ID Car:<br><input type="text" name="id" value="" id="text" placeholder="Id">
                        <br>Name Car:<br><input type="text" name="name" value="" id="text" placeholder="Car name"/>
                        <br>Detail Car:<br><textarea name="detail" rows="4" cols="20" id="textarea" placeholder="Detail"></textarea>
                        <br>Get URL Image Car:<br><input type="file" name="image" value="" width="100px" placeholder="Url image" /><br>
                        <input type="submit" value="Insert" id="bu" />
                        <input type="reset" value="Reset" id="bu"/>
                    </form>
                </div>
            <jsp:include page="footer.jsp"></jsp:include>
        </div>
    </body>
</html>
update.jsp
Java 2016
<%@page import="dao.UpdateDAO"%>
<%@page import="model.Car"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Update</title>
        <link rel="stylesheet" href="css/style.css" />
        <link rel="stylesheet" href="css/nivo-slider.css" type="text/css" media="screen" />
        <link rel="stylesheet" href="css/default/default.css" type="text/css" media="screen" />
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
        <script src="js/jquery.nivo.slider.pack.js" type="text/javascript"></script>
        <style>
            #box-in{
                width: 65%;
                margin: auto;
                margin-left: 28%;
            }
            #text{
                width: 50%;
                height:25px; 
            }
            #textarea{
                width: 70%;
                height: 120px;
            }
            #bu{
                width: 120px;
                height: 34px;
                display: block;
                font-weight: bold;
            }
            h3{
                margin: 0;
                padding: 0;
            }
        </style>
    </head>
    <body id="home">
        <div id="wrapper">
            <jsp:include page="header.jsp"></jsp:include>
                <div id="box-in">
                    <form action="UpdateServlet" method="POST">
                        <%
                            int id = Integer.parseInt(request.getParameter("id_car")); 
                            Car c =new UpdateDAO().getCarID(id);
                        %>
                        ID Car:<br><input type="text" name="id" value="<%=c.getIdCar()%>" id="text"/>
                        <br>Name Car:<br><input type="text" name="name" value="<%=c.getNameCar()%>" id="text"/>
                        <br>Detail Car:<br><textarea name="detail"  id="textarea"><%=c.getDetailCar()%></textarea>
                        <br>Get URL Image Car:<br><input type="file" name="image" value="<%=c.getImageCar()%>" width="100px" /><br>
                        <input type="submit" value="Update" id="bu" />
                        <input type="reset" value="Reset" id="bu"/>
                    </form>
                </div>
            <jsp:include page="footer.jsp"></jsp:include>
        </div>
    </body>
</html>
Phần Source Java 
Controller
DBUtil.java
Java 2016
package Util;

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

public class DBUtil {

    private static Connection connection = null;

    public static Connection getConnection() {
        if (connection != null) {
            return connection;
        } else {
            try {
                Class.forName("com.mysql.jdbc.Driver");
                connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/product", "root", "1234567");
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            return connection;
        }
    }
    //Test connection
//    public static void main(String[] args) {
//        System.out.println(getConnection());
//    }

}
InsertServlet.java
Java 2016
package controller;

import dao.InsertDAO;
import java.io.IOException;
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.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.Car;

public class InsertServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        int idCar = Integer.parseInt(request.getParameter("id"));
        String nameCar = request.getParameter("name");
        String detailCar = request.getParameter("detail");
        String URLimageCar = request.getParameter("image");
       
        Car c = new Car(idCar, nameCar, detailCar, "images/"+URLimageCar);
        InsertDAO insertDAO = new InsertDAO();
        
        try {
            if (insertDAO.insertCar(c)) {
                RequestDispatcher rd = request.getRequestDispatcher("manager.jsp");
                rd.forward(request, response);
            } else {
                RequestDispatcher rd = request.getRequestDispatcher("error.jsp");
                rd.forward(request, response);
            }
        } catch (SQLException ex) {
            Logger.getLogger(InsertServlet.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

}
UpdateServlet.java
Java 2016
package controller;

import dao.UpdateDAO;
import java.io.IOException;
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.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.Car;

public class UpdateServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        int id = Integer.parseInt(request.getParameter("id"));
        String name = request.getParameter("name");
        String detail = request.getParameter("detail");
        String urlImage = request.getParameter("image");
        Car c = new Car(name, detail, "images/"+urlImage);
        UpdateDAO u = new UpdateDAO();
        try {
            if (u.update(c, id)) {
               RequestDispatcher rd = request.getRequestDispatcher("manager.jsp");
                rd.forward(request, response);
            } else {
                RequestDispatcher rd = request.getRequestDispatcher("error.jsp");
                rd.forward(request, response);
            }
        } catch (SQLException ex) {
            Logger.getLogger(InsertServlet.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

}
DeleteServlet.java
Java 2016
package controller;

import dao.DeleteDAO;
import java.io.IOException;
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.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DeleteServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        int idCar = Integer.parseInt(request.getParameter("id_car"));

        DeleteDAO d = new DeleteDAO();
        try {
            if (d.deleteCar(idCar)) {
                RequestDispatcher rd = request.getRequestDispatcher("manager.jsp");
                rd.forward(request, response);
            } else {
                RequestDispatcher rd = request.getRequestDispatcher("error.jsp");
                rd.forward(request, response);
            }
        } catch (SQLException ex) {
            Logger.getLogger(DeleteServlet.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

}
LoginServlet.java
Java 2016
package controller;

import dao.UserDAO;
import java.io.IOException;
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.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String user = request.getParameter("username");
        String pass = request.getParameter("password");
        
        UserDAO u = new UserDAO();
        try {
            if(u.checkLogin(user, pass)){
                RequestDispatcher rd = request.getRequestDispatcher("manager.jsp");
                rd.forward(request, response);
            }else{
                RequestDispatcher rd = request.getRequestDispatcher("error.jsp");
                rd.forward(request, response);
            }
            
        } catch (SQLException ex) {
            Logger.getLogger(LoginServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}
Dao
CarDAO.java
Java 2016
package dao;

import Util.DBUtil;
import java.util.ArrayList;
import model.Car;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class CarDAO {
    //Show all car ở page Manager
   public ArrayList<Car> getAllCar() {
        ArrayList<Car> list = new ArrayList();
        Connection conn = DBUtil.getConnection();
        try {
            PreparedStatement stmt = conn.prepareStatement("SELECT * FROM product.car");
            ResultSet rs = stmt.executeQuery();
            while (rs.next()) {
                int id = rs.getInt("id_car");
                String name = rs.getString("name_car");
                String detail = rs.getString("detail_car");
                String image = rs.getString("image_car");
                Car c = new Car(id, name, detail, image);
                list.add(c);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }
    
    //Show all by first last ở page index
    public ArrayList<Car> getAllCar(int first, int last) {
        ArrayList<Car> list = new ArrayList();
        Connection conn = DBUtil.getConnection();
        try {
            PreparedStatement stmt = conn.prepareStatement("SELECT * FROM product.car Limit ?,?");
            stmt.setInt(1, first);
            stmt.setInt(2, last);
            ResultSet rs = stmt.executeQuery();
            while (rs.next()) {
                int id = rs.getInt("id_car");
                String name = rs.getString("name_car");
                String detail = rs.getString("detail_car");
                String image = rs.getString("image_car");
                Car c = new Car(id, name, detail, image);
                list.add(c);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }

    //Test getAllCar
//    public static void main(String[] args) {
//        CarDAO c = new CarDAO();
//        System.out.println(c.getAllCar());
//    }
    //Get car by id
    public Car getCarID(int id) {
        Connection conn = DBUtil.getConnection();
        Car c = null;
        try {
            PreparedStatement stmt = conn.prepareStatement("SELECT * FROM product.car Where id_car='" + id + "'");
            ResultSet rs = stmt.executeQuery();
            while (rs.next()) {
                String name = rs.getString("name_car");
                String detail = rs.getString("detail_car");
                String image = rs.getString("image_car");
                c = new Car(id, name, detail, image);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return c;
    }

    //Count product
    public int getNumberProduct() {
        Connection conn = DBUtil.getConnection();
        int count = 0;
        try {
            PreparedStatement stmt = conn.prepareStatement("SELECT count(id_car) FROM product.car");
            ResultSet rs = stmt.executeQuery();
            while (rs.next()) {
                count = rs.getInt(1);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return count;
    }
    //Test getNumberProduct
//    public static void main(String[] args) {
//        CarDAO c = new CarDAO();
//        System.out.println(c.getNumberProduct());
//
//    }
    
}
UserDAO.java
Java 2016
package dao;

import Util.DBUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import model.User;

public class UserDAO {

    public boolean checkLogin(String user, String pass) throws SQLException {
        ArrayList<User> list = new ArrayList();
        Connection conn = DBUtil.getConnection();
        PreparedStatement stmt = conn.prepareStatement("SELECT * FROM product.user Where user='"+user+"' and pass='"+pass+"'");
        ResultSet rs = stmt.executeQuery();
        int count = 0;
        while (rs.next()) {
            count++;
        }
        if (count == 1) {
            return true;
        }
        return false;
    }
    //Test checkLogin
//    public static void main(String[] args) throws SQLException {
//        UserDAO u = new UserDAO();
//        System.out.println(u.checkLogin("tony","12345"));
//    }
}
InsertDAO.java
Java 2016
package dao;

import Util.DBUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import model.Car;

public class InsertDAO {
    public boolean insertCar(Car c) throws SQLException{
        Connection conn = DBUtil.getConnection();
            PreparedStatement stmt = conn.prepareStatement("INSERT INTO `product`.`car` (`id_car`, `name_car`, `detail_car`, `image_car`) VALUES (?, ?, ?, ?);");
            stmt.setInt(1, c.getIdCar());
            stmt.setString(2, c.getNameCar());
            stmt.setString(3, c.getDetailCar());
            stmt.setString(4, c.getImageCar());
        
        return stmt.executeUpdate()>0;
    }
    //Test method insertCar
//    public static void main(String[] args) throws SQLException {
//        InsertDAO i = new InsertDAO();
//        Car c = new Car(4,"A","B","C");
//        System.out.println(i.insertCar(c));
//    }
}
UpdateDAO.java
Java 2016
package dao;

import Util.DBUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import model.Car;

public class UpdateDAO {

    public boolean update(Car c, int id) throws SQLException {
        Connection conn = DBUtil.getConnection();
        PreparedStatement stmt = conn.prepareStatement("UPDATE `product`.`car` SET `name_car`=?, `detail_car`=?, `image_car`=? WHERE `id_car`='" + id + "'");
        stmt.setString(1, c.getNameCar());
        stmt.setString(2, c.getDetailCar());
        stmt.setString(3, c.getImageCar());
        return stmt.executeUpdate() > 0;
    }

    //Test Update

    public static void main(String[] args) throws SQLException {
        UpdateDAO u = new UpdateDAO();
        System.out.println(u.update(new Car(0, "A", "B", "C"), 2));
    }

    public Car getCarID(int id) throws SQLException {
        Connection conn = DBUtil.getConnection();
        PreparedStatement stmt = conn.prepareStatement("Select * From product.car Where id_car='" + id + "'");
        ResultSet rs = stmt.executeQuery();
        Car c = null;
        while (rs.next()) {
            c = new Car(id, rs.getString("name_car"), rs.getString("detail_car"), rs.getString("image_car"));
        }
        return c;

    }
        //Test getCar by ID
//    public static void main(String[] args) throws SQLException {
//    UpdateDAO u = new UpdateDAO();
//        System.out.println(u.getCarID(2));
//    }
}
DeleteDAO.java
Java 2016
package dao;

import Util.DBUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class DeleteDAO {
    public boolean deleteCar(int id) throws SQLException{
        Connection conn = DBUtil.getConnection();
        PreparedStatement stmt = conn.prepareStatement("DELETE FROM `product`.`car` WHERE `id_car`='"+id+"'");
        return stmt.executeUpdate() >0;
    }
    //Test deleteCar
//    public static void main(String[] args) throws SQLException {
//        DeleteDAO d = new DeleteDAO();
//        System.out.println(d.deleteCar(4));
//    }
}
Model
Car.java
Java 2016
package model;

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

    private int idCar;
    private String nameCar;
    private String detailCar;
    private String imageCar;

    public Car(String nameCar, String detailCar, String imageCar) {
        this.nameCar = nameCar;
        this.detailCar = detailCar;
        this.imageCar = imageCar;
    }

    public Car(int idCar, String nameCar, String detailCar, String imageCar) {
        this.idCar = idCar;
        this.nameCar = nameCar;
        this.detailCar = detailCar;
        this.imageCar = imageCar;
    }

    public int getIdCar() {
        return idCar;
    }

    public void setIdCar(int idCar) {
        this.idCar = idCar;
    }

    public String getNameCar() {
        return nameCar;
    }

    public void setNameCar(String nameCar) {
        this.nameCar = nameCar;
    }

    public String getDetailCar() {
        return detailCar;
    }

    public void setDetailCar(String detailCar) {
        this.detailCar = detailCar;
    }

    public String getImageCar() {
        return imageCar;
    }

    public void setImageCar(String imageCar) {
        this.imageCar = imageCar;
    }

}
User.java
Java 2016
package model;

/**
 *
 * @author Lonely
 */
public class User {
    private String id;
    private String user;
    private String pass;

    public String getId() {
        return id;
    }

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

    public String getUser() {
        return user;
    }

    public void setUser(String user) {
        this.user = user;
    }

    public String getPass() {
        return pass;
    }

    public void setPass(String pass) {
        this.pass = pass;
    }

    public User(String id, String user, String pass) {
        this.id = id;
        this.user = user;
        this.pass = pass;
    }
    
}

0 nhận xét:

Post a Comment

 

BACK TO TOP

Xuống cuối trang