我试图通过我的管理界面添加类别和添加产品(项目),但我无法将其插入数据库。我正在学习javaee并在这里关注电子商务教程https://netbeans.org/kb/docs/javaee/ecommerce/intro.html但是这个应用程序缺少很多东西所以我试图在管理部分中添加特性。但CRUD根本不起作用。
我已经提供了可能依赖于我已经解释过的所有内容的代码。主要问题区域是AdminServlet,addCategory.jsp,categoryManager和ProductManager。
我正在使用MySQL Netbeans IDE JAVA EE 8 EL EJB JSTL MVC
管理Servlet:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package controller;
import entity.Category;
import entity.Customer;
import entity.CustomerOrder;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.HttpConstraint;
import javax.servlet.annotation.ServletSecurity;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import session.CategoryFacade;
import session.CategoryManager;
import session.CustomerFacade;
import session.CustomerOrderFacade;
import session.OrderManager;
import validate.Validator;
/**
*
* @author Admin
*/
@WebServlet(name = "AdminServlet",
loadOnStartup = 1,
urlPatterns = {
"/admin/",
"/admin/viewOrders",
"/admin/viewCustomers",
"/admin/customerOrder",
"/admin/orderRecord",
"/admin/logout",
"/admin/showCategory",
"/admin/addCategory",
"/admin/addProduct"
})
@ServletSecurity( @HttpConstraint(rolesAllowed = {"eshopAdmin"}) )
public class AdminServlet extends HttpServlet {
@EJB
private OrderManager orderManager;
@EJB
private CategoryManager categoryManager;
@EJB
private CustomerFacade customerFacade;
@EJB
private CategoryFacade categoryFacade;
@EJB
private CustomerOrderFacade customerOrderFacade;
private Customer customer;
private CustomerOrder order;
private List orderList = new ArrayList();
private List customerList = new ArrayList();
private Category category;
private List categoryList = new ArrayList();
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//processRequest(request, response);
HttpSession session;
String userPath = request.getServletPath();
//customer list
if (userPath.equals("/admin/showCustomers")){
customerList = customerFacade.findAll();
request.setAttribute("customerList", customerList);
}
//order list
else if (userPath.equals("/admin/viewOrders")){
orderList = customerOrderFacade.findAll();
request.setAttribute("orderList", orderList);
}
//customer records of particular customer
else if (userPath.equals("/admin/customerRecord")){
//customer id from user request url
String customerId = request.getQueryString();
//get details of customer needs casting back
customer = customerFacade.find(Integer.parseInt(customerId));
request.setAttribute("customerRecord", customer);
//get customer's order details
order = customerOrderFacade.findByCustomer(customer);
request.setAttribute("order", order);
}
else if (userPath.equals("/admin/orderRecord")){
//get customer id from order request
String orderId = request.getQueryString();
//get order details by mapping orders and customer
Map orderMap = orderManager.getOrderDetails(Integer.parseInt(orderId));
//place order details into app's scope by mapping
request.setAttribute("customer", orderMap.get("customer"));
request.setAttribute("products", orderMap.get("products"));
}
else if (userPath.equals("/admin/showCategory")){
categoryList = categoryFacade.findAll();
request.setAttribute("categoryList", categoryList);
}
else if (userPath.equals("/admin/logout")){
try {
session = request.getSession();
session.invalidate();
response.sendRedirect("/e-Shop/admin/");
return;
}
catch (Exception e){
e.toString();
}
}
//forward request internally
userPath = "/admin/index.jsp";
try {
request.getRequestDispatcher(userPath).forward(request, response);
}
catch (ServletException | IOException ex){
ex.toString();
}
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//processRequest(request, response);
request.setCharacterEncoding("UTF-8");
String userPath = request.getServletPath();
HttpSession session = request.getSession();
Validator validator = new Validator() {};
if (userPath.equals("/admin/addCategory")){
if (category != null){
String name = request.getParameter("name");
boolean validationErrorFlag;
validationErrorFlag = validator.validateForm(name, request);
// if validation error found, return to same
if (validationErrorFlag == true) {
request.setAttribute("validationErrorFlag", validationErrorFlag);
}
else {
request.setAttribute("name" , name);
Category addCategory = categoryManager.addCategory(name);
userPath = "/admin/showCategory";
}
}
}
// use RequestDispatcher to forward request internally
String url = userPath + ".jsp";
try {
request.getRequestDispatcher(url).forward(request, response);
}
catch (ServletException | IOException ex){
ex.toString();
}
}
}
我的addCategory.jsp
<script src="../js/jquery.validate.js" type="text/javascript"></script>
<script type ="text/javascript">
$(document).ready(function(){
$("#addCatForm").validate({
rules: {
name: {
required: true
}
}
});
});
</script>
<!-- main container starts -->
<div class="container maincontainer">
<div class="row">
<div class="col-md-9">
<h1>Add Category: </h1>
<form id ="addCatForm" action="<c:url value='/admin/addCategory'/>" method="post">
<c:if test="${!empty validationErrorFlag}">
<c:if test="${!empty nameError}"><p>Name</p></c:if>
</c:if>
<p><strong>Category Name:</strong>
<input class ="form-control" type="text" size="20" name="name"></p>
<p><input class ="btn-success" type="submit" value="submit"></p>
</form>
</div>
<div class="col-md-3">
<h1>Side bar</h1>
<p>Something</p>
</div>
</div>
</div>
<!-- main container ends here -->
<div class="pullfooter"></div>
<div class ="jumbotron">
<p>Jumbo</p>
</div>
<div class="pullfooter"></div>
和
CategoryFacade会话bean
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package session;
import entity.Category;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
/**
*
* @author Admin
*/
@Stateless
public class CategoryFacade extends AbstractFacade<Category> {
@PersistenceContext(unitName = "e-ShopPU")
private EntityManager em;
@Override
protected EntityManager getEntityManager() {
return em;
}
public CategoryFacade() {
super(Category.class);
}
}
CategoryManager Bean
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package session;
import javax.ejb.Stateless;
import entity.Category;
import javax.ejb.EJB;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
/**
*
* @author Admin
*/
@Stateless
@TransactionManagement(TransactionManagementType.CONTAINER)
public class CategoryManager {
@PersistenceContext(unitName = "e-ShopPU")
private EntityManager em;
@EJB
private CategoryFacade categoryFacade;
public Category addCategory(String name) {
Category category = new Category();
category.setName(name);
em.persist(category);
return category;
}
// Add business logic below. (Right-click in editor and choose
// "Insert Code > Add Business Method")
}
ProductManager类
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package session;
import entity.Category;
import entity.Product;
import java.math.BigDecimal;
import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.ejb.SessionContext;
import javax.ejb.Stateless;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
/**
* @author Admin
*/
@Stateless
@TransactionManagement(TransactionManagementType.CONTAINER)
public class ProductManager {
@PersistenceContext(unitName = "e-ShopPU")
private EntityManager em;
// Add business logic below. (Right-click in editor and choose
// "Insert Code > Add Business Method")
@Resource
private SessionContext context;
@EJB
private ProductFacade productFacade;
public Product addProduct(String name, Double price, String description, String product_img , Category category) {
Product product = new Product();
product.setName(name);
product.setPrice(BigDecimal.ZERO);
product.setDescription(description);
product.setCategoryId(category);
product.setProductImg(product_img);
em.persist(product);
return product;
}
}
ProductFacade
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package session;
import entity.Product;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
/**
*
* @author Admin
*/
@Stateless
public class ProductFacade extends AbstractFacade<Product> {
@PersistenceContext(unitName = "e-ShopPU")
private EntityManager em;
@Override
protected EntityManager getEntityManager() {
return em;
}
public ProductFacade() {
super(Product.class);
}
}
Product.Java实体类
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package entity;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* @author Admin
*/
@Entity
@Table(name = "product")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Product.findAll", query = "SELECT p FROM Product p"),
@NamedQuery(name = "Product.findById", query = "SELECT p FROM Product p WHERE p.id = :id"),
@NamedQuery(name = "Product.findByName", query = "SELECT p FROM Product p WHERE p.name = :name"),
@NamedQuery(name = "Product.findByPrice", query = "SELECT p FROM Product p WHERE p.price = :price"),
@NamedQuery(name = "Product.findByDescription", query = "SELECT p FROM Product p WHERE p.description = :description"),
@NamedQuery(name = "Product.findByLastUpdate", query = "SELECT p FROM Product p WHERE p.lastUpdate = :lastUpdate"),
@NamedQuery(name = "Product.findByProductImg", query = "SELECT p FROM Product p WHERE p.productImg = :productImg")})
public class Product implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "id")
private Integer id;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 256)
@Column(name = "name")
private String name;
// @Max(value=?) @Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation
@Basic(optional = false)
@NotNull
@Column(name = "price")
private BigDecimal price;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 255)
@Column(name = "description")
private String description;
@Basic(optional = false)
@NotNull
@Column(name = "last_update")
@Temporal(TemporalType.TIMESTAMP)
private Date lastUpdate;
@Size(max = 1024)
@Column(name = "product_img")
private String productImg;
@JoinColumn(name = "category_id", referencedColumnName = "id")
@ManyToOne(optional = false)
private Category categoryId;
public Product() {
}
public Product(Integer id) {
this.id = id;
}
public Product(Integer id, String name, BigDecimal price, String description, Date lastUpdate) {
this.id = id;
this.name = name;
this.price = price;
this.description = description;
this.lastUpdate = lastUpdate;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Date getLastUpdate() {
return lastUpdate;
}
public void setLastUpdate(Date lastUpdate) {
this.lastUpdate = lastUpdate;
}
public String getProductImg() {
return productImg;
}
public void setProductImg(String productImg) {
this.productImg = productImg;
}
public Category getCategoryId() {
return categoryId;
}
public void setCategoryId(Category categoryId) {
this.categoryId = categoryId;
}
@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Product)) {
return false;
}
Product other = (Product) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
@Override
public String toString() {
return "entity.Product[ id=" + id + " ]";
}
}
Category.java实体bean
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package entity;
import java.io.Serializable;
import java.util.Collection;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
*
* @author Admin
*/
@Entity
@Table(name = "category")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Category.findAll", query = "SELECT c FROM Category c"),
@NamedQuery(name = "Category.findById", query = "SELECT c FROM Category c WHERE c.id = :id"),
@NamedQuery(name = "Category.findByName", query = "SELECT c FROM Category c WHERE c.name = :name")})
public class Category implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "id")
private Integer id;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 45)
@Column(name = "name")
private String name;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "categoryId")
private Collection<Product> productCollection;
public Category() {
}
public Category(Integer id) {
this.id = id;
}
public Category(Integer id, String name) {
this.id = id;
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@XmlTransient
public Collection<Product> getProductCollection() {
return productCollection;
}
public void setProductCollection(Collection<Product> productCollection) {
this.productCollection = productCollection;
}
@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Category)) {
return false;
}
Category other = (Category) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
@Override
public String toString() {
return "entity.Category[ id=" + id + " ]";
}
}
任何人都可以指出我的错误并帮助我解决问题吗?