Skip to content
This repository has been archived by the owner on May 31, 2024. It is now read-only.

Commit

Permalink
Merge pull request #125 from hardingadonis/chuong-add-product
Browse files Browse the repository at this point in the history
Chuong add product finished
  • Loading branch information
hardingadonis authored Feb 25, 2024
2 parents 83c326e + b746195 commit 1bb4676
Show file tree
Hide file tree
Showing 7 changed files with 122 additions and 58 deletions.
5 changes: 5 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,11 @@
<artifactId>jakarta.mail</artifactId>
<version>2.0.1</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.5</version>
</dependency>
</dependencies>
<build>
<plugins>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,21 +6,19 @@
import jakarta.servlet.*;
import jakarta.servlet.annotation.*;
import jakarta.servlet.http.*;
import java.nio.file.*;
import java.util.*;

import io.hardingadonis.saledock.model.Category;
import io.hardingadonis.saledock.model.Product;
import io.hardingadonis.saledock.utils.Singleton;
import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

@WebServlet(name = "AddProductServlet", urlPatterns = {"/add-product"})
@MultipartConfig
public class AddProductServlet extends HttpServlet {

public static final String UPLOAD_PRODUCT_IMG_DIRECTORY = "product_img";

public static final int MEMORY_THRESHOLD = 1024 * 1024 * 3;
public static final int MAX_FILE_SIZE = 1024 * 1024 * 3;
public static final int MAX_REQUEST_SIZE = 1024 * 1024 * 5;

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Expand All @@ -41,38 +39,35 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response)
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String codePro = request.getParameter("codeP");
String namePro = request.getParameter("nameP");
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");

String namePro = request.getParameter("nameP");
int catPro = Integer.parseInt(request.getParameter("categoryP"));
Optional<Category> cat = Singleton.categoryDAO.getByID(catPro);

double pricePro = Double.parseDouble(request.getParameter("priceP"));
String desPro = request.getParameter("descriptionP");

// try {
// List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
// for (FileItem item : items) {
// if (!item.isFormField() && item.getFieldName().equals("imageUpload")) {
// // item is the file (and not a field)
// InputStream fileContent = item.getInputStream();
// // assuming you have a connection (conn) to your database
// PreparedStatement stmt = conn.prepareStatement("INSERT INTO images (content) VALUES (?)");
// stmt.setBlob(1, fileContent);
// stmt.executeUpdate();
// break; // we only process one image, so break the loop after the first file
// }
// }
// } catch (Exception e) {
// throw new ServletException("Cannot parse multipart request.", e);
// }
Product p = new Product();
p.setCode(codePro.toUpperCase());
p.setName(namePro);
p.setCategory(cat.get());
p.setPrice(pricePro);
p.setDescription(desPro);
Singleton.productDAO.save(p);
Part part = request.getPart("imageUpload");
String imgURL = null;
if (part.getSize() > 0) {
String realPath = request.getServletContext().getRealPath("/product_img");
String fileName = Paths.get(part.getSubmittedFileName()).getFileName().toString();
imgURL = "product_img/" + fileName;
if (!Files.exists(Paths.get(realPath))) {
Files.createDirectories(Paths.get(realPath));
}

part.write(realPath + "/" + fileName);
}

Product pro = new Product();
pro.setName(namePro);
pro.setCategory(cat.get());
pro.setPrice(pricePro);
pro.setImageURL(imgURL);
pro.setDescription(desPro);
Singleton.productDAO.save(pro);

response.sendRedirect("product");
}
Expand Down
5 changes: 4 additions & 1 deletion src/main/java/io/hardingadonis/saledock/dao/IProductDAO.java
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
package io.hardingadonis.saledock.dao;

import io.hardingadonis.saledock.model.*;
import java.util.Optional;

public interface IProductDAO extends IDAO<Product>, IPagination<Product> {

public String getTop10(Integer duration);
public String getTop10(Integer duration);

public Optional<Product> getByCode(String code);
}
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,14 @@ public Optional<Product> getByID(Integer ID) {
}
}

@Override
public Optional<Product> getByCode(String code) {
try (Session session = sessionFactory.openSession()) {
String hql = "FROM Product WHERE code = :code";
return Optional.ofNullable(session.createQuery(hql, Product.class).setParameter("code", code).uniqueResult());
}
}

@Override
public List<Product> getAll() {
try (Session session = sessionFactory.openSession()) {
Expand Down Expand Up @@ -114,4 +122,5 @@ public List<Product> pagination(Integer offset, Integer limit) {
public Integer totalPages(Integer limit) {
return (int) Math.ceil((double) this.count() / limit);
}

}
16 changes: 16 additions & 0 deletions src/main/java/io/hardingadonis/saledock/model/Product.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package io.hardingadonis.saledock.model;

import io.hardingadonis.saledock.utils.Singleton;
import jakarta.persistence.*;
import java.time.*;
import java.util.*;
import lombok.*;

@Entity(name = "Product")
Expand Down Expand Up @@ -46,10 +48,24 @@ public class Product {
@PrePersist
protected void onCreate() {
this.createdAt = LocalDateTime.now(ZoneId.of("Asia/Ho_Chi_Minh"));
this.code = generateUniqueOrderCode();
}

@PreUpdate
protected void onUpdate() {
this.updatedAt = LocalDateTime.now(ZoneId.of("Asia/Ho_Chi_Minh"));
}

private static String generateUniqueOrderCode() {
Random random = new Random();
String orderCode;

do {
char letter = (char) ('A' + random.nextInt(26));
int number = random.nextInt(1000);
orderCode = String.format("%c%03d", letter, number);
} while (Singleton.productDAO.getByCode(orderCode).isPresent());

return orderCode;
}
}
35 changes: 35 additions & 0 deletions src/main/webapp/view/assets/js/management/product/add-product.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
$(document).ready(function () {
$('#add-product').on('submit', function (e) {
e.preventDefault();

var formData = new FormData(this);

$.ajax({
type: 'POST',
url: $(this).attr('action'),
data: formData,
processData: false,
contentType: false,
success: function (response) {
Swal.fire({
title: 'Thành công!',
text: 'Thêm sản phẩm thành công',
icon: 'success',
timer: 3000
}).then((result) => {
if (result.dismiss === Swal.DismissReason.timer) {
console.log('I was closed by the timer')
}
window.location.href = 'product';
});

setTimeout(function () {
window.location.href = 'product';
}, 3000);
},
error: function (response) {

}
});
});
});
43 changes: 22 additions & 21 deletions src/main/webapp/view/jsp/management/product/add-product.jsp
Original file line number Diff line number Diff line change
Expand Up @@ -36,16 +36,9 @@
<p class="text-primary m-0 fw-bold">Thêm sản phẩm mới</p>
</div>
<div class="card-body">
<form id="add-product" action="add-product" method="post">
<form id="add-product" enctype="multipart/form-data" action="add-product" method="post">
<div class="row">
<div class="col">
<div class="mb-3">
<label class="form-label" for="username">
<strong>Mã sản phẩm</strong>
</label>
<input class="form-control" type="text" id="codeP" placeholder="Nhập mã sản phẩm" name="codeP" required oninvalid="this.setCustomValidity('Vui lòng nhập Mã sản phẩm.')" oninput="this.setCustomValidity('')">
</div>
</div>

<div class="col">
<div class="mb-3">
<label class="form-label" for="email">
Expand All @@ -54,8 +47,7 @@
<input class="form-control" type="text" id="nameP" placeholder="Nhập tên sản phẩm" name="nameP" required oninvalid="this.setCustomValidity('Vui lòng nhập Tên sản phẩm.')" oninput="this.setCustomValidity('')">
</div>
</div>
</div>
<div class="row">

<div class="col">
<div class="mb-3">
<label class="form-label" for="username">
Expand All @@ -68,6 +60,8 @@
</select>
</div>
</div>
</div>
<div class="row">
<div class="col">
<div class="mb-3">
<label class="form-label" for="email">
Expand All @@ -76,21 +70,25 @@
<input class="form-control" type="number" id="priceP" placeholder="Nhập giá tiền sản phẩm" name="priceP" required min="0" oninvalid="this.setCustomValidity('Vui lòng nhập Giá sản phẩm.')" oninput="this.setCustomValidity('')">
</div>
</div>
<div class="col">
<div class="mb-3">
<label class="form-label" for="imageUpload">
<strong>Ảnh sản phẩm</strong>
</label>
<input class="form-control" type="file" id="imageUpload" name="imageUpload" accept="image/*">
</div>
</div>
</div>
<div class="mb-3">
<div class="mb-3">
<label class="form-label" for="imageUpload">
<strong>Ảnh sản phẩm</strong>
</label>
<input class="form-control" type="file" id="imageUpload" name="imageUpload" accept="image/*">
</div>
<div class="mb-3">
<label class="form-label" for="country">
<strong>Mô tả chi tiết</strong>
</label>
<textarea class="form-control" id="descriptionP"></textarea>
<textarea class="form-control" name="descriptionP" id="descriptionP"></textarea>
</div>
<button class="btn btn-primary btn-sm" type="submit">Lưu sản phẩm</button>
<a class="btn btn-primary btn-sm" href="product">Quay lại</a>

<button class="btn btn-primary btn-sm" type="submit">Thêm sản phẩm</button>
</div>
</form>
</div>
Expand All @@ -105,10 +103,13 @@
</div>
<%@include file="../../../common/_goback.jsp" %>
</div>


<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script src="<%=request.getContextPath()%>/view/assets/js/bootstrap.min.js"></script>
<script src="<%=request.getContextPath()%>/view/assets/js/bs-init.js"></script>
<script src="<%=request.getContextPath()%>/view/assets/js/theme.js"></script>

<script src="<%=request.getContextPath()%>/view/assets/js/management/product/add-product.js"></script>
</body>

</html>

0 comments on commit 1bb4676

Please sign in to comment.