Всем привет! Нашел в сети интересный проект "Онлайн-магазин" на Spring Boot. Но возникла проблема когда я попытался добавить кнопку Удалить продукт из списка. Объясните пожалуйста что не так. Вот мой класс Admin Controller:
package com.webapp.agroxapp.controller;
import java.util.List;
import org.apache.commons.lang.exception.ExceptionUtils;
import com.webapp.agroxapp.dao.OrderDAO;
import com.webapp.agroxapp.dao.ProductDAO;
import com.webapp.agroxapp.entity.Product;
import com.webapp.agroxapp.form.ProductForm;
import com.webapp.agroxapp.model.OrderDetailInfo;
import com.webapp.agroxapp.model.OrderInfo;
import com.webapp.agroxapp.pagination.PaginationResult;
import com.webapp.agroxapp.validator.ProductFormValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
@Controller
@Transactional
public class AdminController {
@Autowired
private OrderDAO orderDAO;
@Autowired
private ProductDAO productDAO;
@Autowired
private ProductFormValidator productFormValidator;
@InitBinder
public void myInitBinder(WebDataBinder dataBinder) {
Object target = dataBinder.getTarget();
if (target == null) {
return;
}
System.out.println("Target=" + target);
if (target.getClass() == ProductForm.class) {
dataBinder.setValidator(productFormValidator);
}
}
// GET: Show Login Page
@RequestMapping(value = { "/admin/login" }, method = RequestMethod.GET)
public String login(Model model) {
return "login";
}
@RequestMapping(value = { "/admin/accountInfo" }, method = RequestMethod.GET)
public String accountInfo(Model model) {
UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
System.out.println(userDetails.getPassword());
System.out.println(userDetails.getUsername());
System.out.println(userDetails.isEnabled());
model.addAttribute("userDetails", userDetails);
return "accountInfo";
}
@RequestMapping(value = { "/admin/orderList" }, method = RequestMethod.GET)
public String orderList(Model model, //
@RequestParam(value = "page", defaultValue = "1") String pageStr) {
int page = 1;
try {
page = Integer.parseInt(pageStr);
} catch (Exception e) {
}
final int MAX_RESULT = 5;
final int MAX_NAVIGATION_PAGE = 10;
PaginationResult<OrderInfo> paginationResult //
= orderDAO.listOrderInfo(page, MAX_RESULT, MAX_NAVIGATION_PAGE);
model.addAttribute("paginationResult", paginationResult);
return "orderList";
}
// GET: Show product.
@RequestMapping(value = { "/admin/product" }, method = RequestMethod.GET)
public String product(Model model, @RequestParam(value = "code", defaultValue = "") String code) {
ProductForm productForm = null;
if (code != null && code.length() > 0) {
Product product = productDAO.findProduct(code);
if (product != null) {
productForm = new ProductForm(product);
}
}
if (productForm == null) {
productForm = new ProductForm();
productForm.setNewProduct(true);
}
model.addAttribute("productForm", productForm);
return "product";
}
// POST: Save product
@RequestMapping(value = { "/admin/product" }, method = RequestMethod.POST)
public String productSave(Model model, //
@ModelAttribute("productForm") @Validated ProductForm productForm, //
BindingResult result, //
final RedirectAttributes redirectAttributes) {
if (result.hasErrors()) {
return "product";
}
try {
productDAO.save(productForm);
} catch (Exception e) {
Throwable rootCause = ExceptionUtils.getRootCause(e);
String message = rootCause.getMessage();
model.addAttribute("errorMessage", message);
// Show product form.
return "product";
}
return "redirect:/productList";
}
@RequestMapping(value = "product/{code}", method = RequestMethod.DELETE)
public String delete(@PathVariable("code") String code) {
productDAO.delete(code);
return "redirect:/productList";
}
@RequestMapping(value = { "/admin/order" }, method = RequestMethod.GET)
public String orderView(Model model, @RequestParam("orderId") String orderId) {
OrderInfo orderInfo = null;
if (orderId != null) {
orderInfo = this.orderDAO.getOrderInfo(orderId);
}
if (orderInfo == null) {
return "redirect:/admin/orderList";
}
List<OrderDetailInfo> details = this.orderDAO.listOrderDetailInfos(orderId);
orderInfo.setDetails(details);
model.addAttribute("orderInfo", orderInfo);
return "order";
}
}
И класс ProductDAO:
package com.webapp.agroxapp.dao;
import java.io.IOException;
import java.util.Date;
import javax.persistence.NoResultException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.query.Query;
import com.webapp.agroxapp.entity.Product;
import com.webapp.agroxapp.form.ProductForm;
import com.webapp.agroxapp.model.ProductInfo;
import com.webapp.agroxapp.pagination.PaginationResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
@Transactional
@Repository
public class ProductDAO {
@Autowired
private SessionFactory sessionFactory;
public Product findProduct(String code) {
try {
String sql = "Select e from " + Product.class.getName() + " e Where e.code =:code ";
Session session = this.sessionFactory.getCurrentSession();
Query<Product> query = session.createQuery(sql, Product.class);
query.setParameter("code", code);
return (Product) query.getSingleResult();
} catch (NoResultException e) {
return null;
}
}
public ProductInfo findProductInfo(String code) {
Product product = this.findProduct(code);
if (product == null) {
return null;
}
return new ProductInfo(product.getCode(), product.getName(), product.getPrice());
}
@Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
public void save(ProductForm productForm) {
Session session = this.sessionFactory.getCurrentSession();
String code = productForm.getCode();
Product product = null;
boolean isNew = false;
if (code != null) {
product = this.findProduct(code);
}
if (product == null) {
isNew = true;
product = new Product();
product.setCreateDate(new Date());
}
product.setCode(code);
product.setName(productForm.getName());
product.setPrice(productForm.getPrice());
if (productForm.getFileData() != null) {
byte[] image = null;
try {
image = productForm.getFileData().getBytes();
} catch (IOException e) {
}
if (image != null && image.length > 0) {
product.setImage(image);
}
}
if (isNew) {
session.persist(product);
}
// If error in DB, Exceptions will be thrown out immediately
session.flush();
}
public PaginationResult<ProductInfo> queryProducts(int page, int maxResult, int maxNavigationPage,
String likeName) {
String sql = "Select new " + ProductInfo.class.getName() //
+ "(p.code, p.name, p.price) " + " from "//
+ Product.class.getName() + " p ";
if (likeName != null && likeName.length() > 0) {
sql += " Where lower(p.name) like :likeName ";
}
sql += " order by p.createDate desc ";
//
Session session = this.sessionFactory.getCurrentSession();
Query<ProductInfo> query = session.createQuery(sql, ProductInfo.class);
if (likeName != null && likeName.length() > 0) {
query.setParameter("likeName", "%" + likeName.toLowerCase() + "%");
}
return new PaginationResult<ProductInfo>(query, page, maxResult, maxNavigationPage);
}
public PaginationResult<ProductInfo> queryProducts(int page, int maxResult, int maxNavigationPage) {
return queryProducts(page, maxResult, maxNavigationPage, null);
}
public void delete(String code) {
// TODO Auto-generated method stub
Session session = sessionFactory.getCurrentSession();
Query deleteQuery = session.createQuery("DELETE FROM Product p WHERE p.code = :code");
deleteQuery.setParameter("code", code);
deleteQuery.executeUpdate();
}
}
Как видно я прописал метод DELETE в AdminController:
@RequestMapping(value = "product/{code}", method = RequestMethod.DELETE)
public String delete(@PathVariable("code") String code) {
productDAO.delete(code);
return "redirect:/productList";
}
И в классе ProductDAO:
public void delete(String code) {
// TODO Auto-generated method stub
Session session = sessionFactory.getCurrentSession();
Query deleteQuery = session.createQuery("DELETE FROM Product p WHERE p.code = :code");
deleteQuery.setParameter("code", code);
deleteQuery.executeUpdate();
}
При попытке нажать на DELETE появляется ошибка
Whitelabel Error Page - This application has no explicit mapping for /error, so you are seeing this as a fallback.
Tue Dec 03 22:00:10 GMT 2019 There was an unexpected error (type=Not Found, status=404). No message available
Так-же страница Thymeleaf:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<head>
<meta charset="UTF-8">
<title>Product List</title>
<link rel="stylesheet" type="text/css" th:href="@{/styles.css}">
</head>
<body>
<th:block th:include="/_header"></th:block>
<th:block th:include="/_menu"></th:block>
<div class="page-title">Product List</div>
<div class="product-preview-container" th:each="prodInfo : ${paginationProducts.list}">
<ul>
<li><img class="product-image"
th:src="@{|/productImage?code=${prodInfo.code}|}" /></li>
<li>Code: <span th:utext="${prodInfo.code}"></span></li>
<li>Name: <span th:utext="${prodInfo.name}"></span></li>
<li>Price: <span th:utext="${#numbers.formatDecimal(prodInfo.price,3,2,'COMMA')}"></span></li>
<li>
<a th:href="@{|/buyProduct?code=${prodInfo.code}|}">Buy Now</a>
</li>
<!-- For Manager edit Product -->
<th:block sec:authorize="hasAuthority('ROLE_MANAGER')">
<li>
<a style="color:green;"
th:href="@{|/admin/product?code=${prodInfo.code}|}">Edit Product</a>
</li>
<li>
<a style="color:red;"
th:href="|@{admin/delete/${prodInfo.code}}|">Delete Product</a>
</li>
</li>
</th:block>
</ul>
</div>
<br/>
<div class="page-navigator" th:if="${paginationProducts.totalPages > 1}">
<th:block th:each="page : ${paginationProducts.navigationPages}">
<a th:href="@{|/productList?page=${page}|}" th:if="${page != -1}"
class="nav-item" th:utext="${page}"></a>
<span class="nav-item" th:if="${page == -1}"> ... </span>
</th:block>
</div>
<th:block th:include="/_footer"></th:block>
</body>
</html>