25 September 2016

Upload images JPA JSP Servlet Java Web Entity Database

insert-shop.jsp
Java Web  2016
<%@page import="java.io.File"%>
<%--<%@page contentType="text/html" pageEncoding="UTF-8"%>--%>
<%@page contentType="text/html;charset=UTF-8" language="java" import="java.sql.*"%> 
<%response.setContentType("text/html; charset=UTF-8");%> 
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <meta name="description" content="Admin MOS Template">
        <meta name="keywords" content="Admin Page">
        <meta name="author" content="Ari Rusmanto">

        <title>Wellcome Admin</title>
        <link rel="shortcut icon" href="stylesheet/img/devil-icon.png"> <!--Pemanggilan gambar favicon-->
        <link rel="stylesheet" type="text/css" href="../mos-css/mos-style.css"> <!--pemanggilan file css-->


        <script>
            var loadFile = function (event) {
                var reader = new FileReader();
                reader.onload = function () {
                    var output = document.getElementById('output');
                    output.src = reader.result;
                };
                reader.readAsDataURL(event.target.files[0]);
            };// code display image upload
        </script>
        <style>
            #imageOut{
                margin: auto;
                float: right;
                width: 250px;
                height: 300px;
                padding: 80px 50px 0 0;
            }
            #output{

            }
            textArea{
                height: 120px;
            }
        </style>
    </script>
</head>
<body>
    <div id="wrapper">
        <jsp:include page="header.jsp"></jsp:include>
        <jsp:include page="asider.jsp"></jsp:include>
            <div id="rightContent">
                <div id="imageOut"><img id="output"/></div>
                <form action="<%=request.getContextPath()%>/ShopAddServlet" method="POST" enctype="multipart/form-data">
                <table border="1">
                    <tr class="data">
                        <th class="data">infomation</th>
                        <th class="data">Chosse input</th>
                    </tr>
                    <tr>
                        <td>ID Product</td>
                        <td><input type="text" name="id" placeholder="Nhập mã sản phẩm" /><br/></td>
                    </tr>
                    <tr>
                        <td>Product Name</td>
                        <td><input type="text" name="name" placeholder="Nhập tên sản phẩm"/><br/></td>
                    </tr>
                    <tr>
                        <td>Detail Product</td>
                        <td><textarea name="detail" placeholder="Nhập chi tiết sản phẩm"></textarea><br/></td>
                    </tr>
                    <tr>
                        <td>Price Product</td>
                        <td><input type="text" name="price" placeholder="Nhập giá sản phẩm"/><br/></td>
                    </tr>
                    <tr>
                        <td>Choose a image :</td>
                         //accept="image/*" cho phép up ảnh với tất cả các đuôi
                        <td><input type="file" name="photo" accept="image/*" onchange="loadFile(event)"><br/></td>
                    </tr>
                    <td> <input type="submit" value="Insert" /></td>
                </table>
            </form>

        </div>
        <div class="clear"></div>
        <jsp:include page="footer.jsp"></jsp:include>
    </div>
</body>
</html>
ShopAddServlet.java
Java Web  2016
package controller;

import Entty.Shop;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import jpaDAO.ShopJpaController;

//Fix lỗi form có chứa enctype="multipart/form-data"
@MultipartConfig(
        fileSizeThreshold = 1024 * 1024 * 10,
        maxFileSize = 1024 * 1024 * 50,
        maxRequestSize = 1024 * 1024 * 100
)

public class ShopAddServlet extends HttpServlet {

    //Tên folder dẫn ảnh vào
    private static final String UPLOAD_DIR = "images";

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //Fix lỗi tiếng việt
        response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding("utf-8");
        try {
            //Thêm value vào Entity Shop
            Shop shop = new Shop();
            shop.setId(request.getParameter("id"));
            shop.setName(request.getParameter("name"));
            shop.setDetail(request.getParameter("detail"));
            shop.setPrice(Double.parseDouble(request.getParameter("price")));
            shop.setImage(uploadFile(request));

            //Tạo mới Jpa và gọi hàm Insert của nó
            ShopJpaController sdao = new ShopJpaController();
            sdao.create(shop);

            //Kết thúc phiên đưa đến trang cần hiển thị
            response.sendRedirect(request.getContextPath() + "/admin/product.jsp");

        } catch (Exception ex) {
            Logger.getLogger(ShopAddServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private String uploadFile(HttpServletRequest request) throws IOException, ServletException {
        String fileName = "";
        try {
            Part filePart = request.getPart("photo");

            //fileName: picture-001.jpg
            fileName = (String) getFileName(filePart);

            //applicationPath: C:\Users\Lonely\Documents\NetBeansProjects\Shop_Bonfire\build\web
            String applicationPath = request.getServletContext().getRealPath("");

            //File.separator: \ 
            String basePath = applicationPath + File.separator + UPLOAD_DIR + File.separator;

            InputStream inputStream = null;
            OutputStream outputStream = null;
            try {
                File outputFilePath = new File(basePath + fileName);
                inputStream = filePart.getInputStream();
                outputStream = new FileOutputStream(outputFilePath);
                int read = 0;
                final byte[] bytes = new byte[1024];
                while ((read = inputStream.read(bytes)) != -1) {
                    outputStream.write(bytes, 0, read);
                }
            } catch (Exception e) {
                e.printStackTrace();
                fileName = "";
            } finally {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
            }
        } catch (Exception e) {
            fileName = "";
        }
        return fileName;
    }

    private String getFileName(Part part) {
        final String partHeader = part.getHeader("content-disposition");
        System.out.println("*****partHeader :" + partHeader);
        for (String content : part.getHeader("content-disposition").split(";")) {
            if (content.trim().startsWith("filename")) {
                return content.substring(content.indexOf('=') + 1).trim().replace("\"", "");
            }
        }
        return null;
    }
}
ShopJpaController.java
Java Web  2016
package jpaDAO;

import Entty.Shop;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.Persistence;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import jpaDAO.exceptions.NonexistentEntityException;
import jpaDAO.exceptions.PreexistingEntityException;
import jpaDAO.exceptions.RollbackFailureException;


public class ShopJpaController implements Serializable {

    private EntityManagerFactory emf = null;
    private EntityManager em = null;

    public ShopJpaController() throws Exception {
        emf = Persistence.createEntityManagerFactory("Shop_BonfirePU");
    }

    public void create(Shop shop) throws PreexistingEntityException, RollbackFailureException, Exception {
        em = emf.createEntityManager();
        try {
            em.getTransaction().begin();
            em.persist(shop);
            em.getTransaction().commit();
        } catch (Exception ex) {
            try {
                em.getTransaction().rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            if (findShop(shop.getId()) != null) {
                throw new PreexistingEntityException("Shop " + shop + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Shop shop) throws NonexistentEntityException, RollbackFailureException, Exception {
        em = emf.createEntityManager();
        try {
            em.getTransaction().begin();
            shop = em.merge(shop);
            em.getTransaction().commit();
        } catch (Exception ex) {
            try {
                em.getTransaction().rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                String id = shop.getId();
                if (findShop(id) == null) {
                    throw new NonexistentEntityException("The shop with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(String id) throws NonexistentEntityException, RollbackFailureException, Exception {
        em = emf.createEntityManager();
        try {
            em.getTransaction().begin();
            Shop shop;
            try {
                shop = em.getReference(Shop.class, id);
                shop.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The shop with id " + id + " no longer exists.", enfe);
            }
            em.remove(shop);
            em.getTransaction().commit();
        } catch (Exception ex) {
            try {
                em.getTransaction().rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Shop> findShopEntities() {
        return findShopEntities(true, -1, -1);
    }

    public List<Shop> findShopEntities(int maxResults, int firstResult) {
        return findShopEntities(false, maxResults, firstResult);
    }

    private List<Shop> findShopEntities(boolean all, int maxResults, int firstResult) {
        em = emf.createEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Shop.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Shop findShop(String id) {
        em = emf.createEntityManager();
        try {
            return em.find(Shop.class, id);
        } finally {
            em.close();
        }
    }

    public int getShopCount() {
        em = emf.createEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Shop> rt = cq.from(Shop.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
product.jsp
Java Web  2016
<%@page import="java.text.DecimalFormat"%>
<%@page import="java.text.NumberFormat"%>
<%@page import="java.util.Locale"%>
<%@page import="java.util.List"%>
<%@page import="java.util.List"%>
<%@page import="jpaDAO.ShopJpaController"%>
<%@page import="Entty.Shop"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%> 

<!DOCTYPE html>
<html>
    <head>
        <title>Wellcome Admin</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <link rel="stylesheet" type="text/css" href="../mos-css/mos-style.css">
        <style>
            .img-danhmuc{
                width:  50px;
                height: 30px;
            }
            .add{
                display: block;
                background: #a6d050;
                line-height: 15px;
                width: 102px;
                border-radius: 5px;
                padding: 5px;
                color: white;
                font-weight: bold;
            }
            ul.pagination {
                display: inline-block;
                padding-left: 36%;
                margin: 0;
            }

            ul.pagination li {display: inline;}

            ul.pagination li a {
                color: black;
                float: left;
                padding: 8px 16px;
                text-decoration: none;
                transition: background-color .3s;
                border: 1px solid #ddd;
                font-size: 12px;
            }

            ul.pagination li a.active {
                background-color: #4CAF50;
                color: white;
                border: 1px solid #4CAF50;
            }


            ul.pagination li a:hover:not(.active) {background-color: #ddd;}
            #btDelete{
                float: left;
                background-color: #a6d050;
                color: white;
                font-weight: bold;
                padding: 3px 10px 6px 10px;
                margin-bottom: 2px;
                border-radius: 5px;                
            }
            #btDelete:hover{
                color: #000;
            }
            .add{
                float: left;
                margin-left: 4px;
            }
        </style>
        <script>
            function toggle(source) {
                checkboxes = document.getElementsByName('product');
                for (var i = 0, n = checkboxes.length; i < n; i++) {
                    checkboxes[i].checked = source.checked;
                }
            }
        </script>


    </head>
    <body>
        <div id="wrapper">
            <jsp:include page="header.jsp"></jsp:include>
            <jsp:include page="asider.jsp"></jsp:include>

                <div id="rightContent">   
                    <h3>Quản Lý Danh Mục</h3>

                    <form method="POST" action="${pageContext.request.contextPath}/DeleteAllProduct?action=delete">
                    <input type="submit" value="Delete" id="btDelete" onclick="return confirm('Are you sure delete?')"/>
                    <a href="insert-shop.jsp" class="add">Thêm Danh Mục</a>
                    <table class="data">
                        <tr class="data">
                            <th class="data"><input type="checkbox" id="checkBoxAll" onClick="toggle(this)" /></th>
                            <th class="data">Mã Danh Mục</th>
                            <th class="data">Tên Danh Mục</th>
                            <th class="data">Thông Tin Chi Tiết</th>
                            <th class="data">Ảnh</th>
                            <th class="data">Giá Tiền</th>
                            <th colspan="2" class="data">Tùy Chọn</th>
                        </tr>

                        <%
                            ShopJpaController sdao = new ShopJpaController();
                            int first = 0, last = 0, pages = 1;
                            //Neu "index.jsp?pages=" pages ko co bo nho hoac rong thi lay ra pages 
                            if (request.getParameter("pages") != null) {
                                pages = (int) Integer.parseInt(request.getParameter("pages"));
                            }
                            //Lay number total bang query select count(id) from name_table
                            int total = sdao.getShopCount();
                            //Neu number total = 3 
                            if (total <= 6) {
                                first = 0; //first =0
                                last = total; //last =3
                            } else {
                                first = (pages - 1) * 6;
                                last = 6;
                            }
                            List<Shop> list = sdao.findShopEntities(last, first);
                            DecimalFormat formatter = new DecimalFormat("###,###,###");
                            for (Shop item : list) {
                        %>
                        <tr>
                            <td class="data"><input type="checkbox" name="product" value="<%=item.getId()%>"/></td>
                            <td class="data" id="id"><%=item.getId()%></td>
                            <td class="data"><%=item.getName()%></td>
                            <td class="data"><%=item.getDetail()%></td>
                            <td class="data"><img class="img-danhmuc" src="<%=request.getContextPath()%>/images/<%=item.getImage()%>"/></td>
                            <td class="data" style="width: 120px;"><%=formatter.format(item.getPrice())%> VNĐ</td>
                            <td class="data" style="width: 80px;"><a href="update-shop.jsp?id=<%=item.getId()%>">
                                    <img src="../mos-css/img/Text-Edit-icon.png"/></a> 
                                <a href="<%=request.getContextPath()%>/ShopDeleteServlet?id=<%=item.getId()%>" onclick="return confirm('Are you sure delete?')">
                                    <img src="../mos-css/img/delete-file-icon.png"/></a></td>

                        </tr>
                        <%}%>
                    </table>
                </form>

                <ul class="pagination">
                    <%
                        //Button Previous
                        int back = 0;
                        if (pages == 0 || pages == 1) {
                            back = 1;//Luon la page 1
                        } else {
                            back = pages - 1;//Neu pages tu 2 tro len thi back tru 1
                        }
                    %>
                    <li><a href="product.jsp?pages=<%=back%>">«</a></li>
                        <%
                            int loop = 0, num = 0;
                            if ((total / 6) % 2 == 0) {
                                num = total / 6;
                            } else {
                                num = (total + 1) / 6;
                            }
                            //Nếu total lẻ thêm 1
                            if (total % 2 != 0) {
                                loop = (total / 6) + 1;

                            } else {
                                //Nếu total chẵn nhỏ hơn fullpage và # fullPage thì thêm 1
                                if (total < (num * 6) + 6 && total != num * 6) {
                                    loop = (total / 6) + 1;
                                } else {
                                    //Nếu bằng fullPage thì không thêm
                                    loop = (total / 6);
                                }
                            }
                            //Lap so pages
                            for (int i = 1; i <= loop; i++) {%>
                        <% if (pages == i) {%> 
                    <li><a class="active" href="product.jsp?pages=<%=i%>"><%=i%></a></li>
                        <%} else {%>
                    <li><a href="product.jsp?pages=<%=i%>"><%=i%></a> </li>
                        <%}
                            }%>
                        <%
                            //Button Next
                            int next = 0;
                            if (total % 2 != 0) {
                                if (pages == (total / 6) + 1) {
                                    next = pages;//Khong next
                                } else {
                                    next = pages + 1;//Co next
                                }
                            } else {
                                //Nếu total chẵn nhỏ hơn fullpage
                                //Và không fullPage thì thêm 1
                                if (total < (num * 6) + 6 && total != num * 6) {
                                    if (pages == (total / 6) + 1) {
                                        next = pages;//Khong next
                                    } else {
                                        next = pages + 1;//Co next
                                    }
                                } else {
                                    //Nếu fullPage đến trang cuối dừng
                                    //Chưa tới trang cuối thì được next
                                    if (pages == (total / 6)) {
                                        next = pages;//Khong next
                                    } else {
                                        next = pages + 1;//Co next
                                    }
                                }
                            }
                        %>
                    <li><a href="product.jsp?pages=<%=next%>">»</a></li>
                </ul>
            </div>
            <div class="clear"></div>

            <jsp:include page="footer.jsp"></jsp:include>
        </div>
    </body>
</html>
Upload file thành công ảnh sẽ vào images project 

0 nhận xét:

Post a Comment

 

BACK TO TOP

Xuống cuối trang