簡體   English   中英

當我嘗試使用 Spring Boot 將產品添加到購物車時出現錯誤

[英]I am getting an error while i am trying to add a product to the cart using Spring boot

我希望用戶插入客戶信息並輸入產品詳細信息,一旦他點擊添加,將在與此客戶信息相關聯的購物車項目中創建一個產品。

類別實體

@Entity
@Data
public class Categories {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long categories_id;

private String categoryName;

我有產品、客戶、訂單實體。 我需要找到將所有這些實體收集到 Order 實體上的關系,它將保存客戶信息和產品信息。

在此 Html 頁面中,我需要創建鏈接此信息,這些信息將添加到訂單實體中,因此當我創建另一個頁面以獲取所有訂單時,我可以查看所有訂單以及用戶插入的信息。

制作賬單 HTML 頁面

客戶實體類

    @Entity
@Table(name="customers")
public class Customers {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long customer_id;
    private String customer_fName;
    private String customer_lName;
    private String customer_email;
    private String customer_address;
    private String customer_state;
    private String customer_phone;
    private String customer_zipCode;

    @OneToMany(targetEntity = Orders.class,cascade = CascadeType.ALL)
    @JoinColumn(name = "customer_order_fk",referencedColumnName = "customer_id")//means will be a fk in orders table
    private List<Orders> orders;

    public Customers()
    {
        super();
    }

    public Customers(String customer_fName, String customer_lName, String customer_email, String customer_phone,String customer_address ,String customer_state,String customer_zipCode) {
        this.customer_zipCode = customer_zipCode;
        this.customer_phone = customer_phone;
        this.customer_state = customer_state;
        this.customer_address = customer_address;
        this.customer_fName = customer_fName;
        this.customer_lName = customer_lName;
        this.customer_email = customer_email;
    }

產品實體類

    @Entity
@Table(name = "Products")
@Data
public class Products {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long product_id;

    private String product_name;

    private BigDecimal product_price;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "categories_id",nullable = false) //the name of the column in the other class and that name will be a column in the class
    private Categories product_category;

    private String product_quantity;

    private String product_Section;

    private String product_ExpDate;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "")
    private Customers customer;

    @ManyToOne
    @JoinColumn(name = "order_order_id")
    private Orders order;

    public Products()
    {
        super();
    }

    public Products(String product_name, BigDecimal product_price,String product_quantity, String product_Section,String product_ExpDate) {
        this.product_name = product_name;
        this.product_price = product_price;
        this.product_quantity = product_quantity;
        this.product_Section = product_Section;
        this.product_ExpDate = product_ExpDate;
    }

購物車控制器

@Controller
public class CartItemsControllers {


    @Autowired
    private ShoppingCartImpService shoppingCartImpService;

    //Model

    @ModelAttribute("cartItem")
    public CartItem cartItem()
    {
        return new CartItem();
    }

    //Curd


    @GetMapping("/cart/create")
    public String createCartItemForm(Model model)
    {
        //create order object

        CartItem cartItem = new CartItem();

        model.addAttribute("cartItem",cartItem);

        return "makeABill";

    }

    //Save
    @PostMapping("/cart/save")
    public String saveCartItem(@ModelAttribute("cartItem") CartItem cartItem)
    {
        shoppingCartImpService.saveCart(cartItem);

        return "MakeABill";
    }

訂單實體

       @Entity
    @RequiredArgsConstructor
    @AllArgsConstructor
    @Data
    
    public class Orders {
    
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private long order_id;
    
        @OneToMany(fetch = FetchType.LAZY,mappedBy = "cart_item_id",cascade = CascadeType.ALL)
        private Set<CartItem> cartItem;
    
        private double total_price;

}

MakeABill HTML 頁面

<div class="col-md-7 col-lg-8">
            <h4 class="mb-3">Customer Information</h4>
            <form class="needs-validation" novalidate="" th:action="@{/cart/save}" method="post" th:object="${CartItem}" id="form">
                <div class="row g-3">
                    <div class="col-sm-6">
                        <label for="firstName" class="form-label">First name</label>
                        <input type="text" class="form-control" id="firstName"  placeholder="" value="" required="" autofocus th:field="*{customer.customer_fName}">
                        <div class="invalid-feedback">
                            Valid first name is required.
                        </div>
                    </div>


                    <div class="col-sm-6">
                        <label for="lastName" class="form-label">Last name</label>
                        <input type="text" class="form-control" id="lastName" placeholder="" value="" required="" autofocus th:field="*{customer.customer_lname}">
                        <div class="invalid-feedback">
                            Valid last name is required.
                        </div>
                    </div>


                    <div class="col-12">
                        <br>
                        <label for="address" class="form-label">Address</label>
                        <input type="text" class="form-control" id="address" placeholder="Address" required="" autofocus th:field="*{customer.customer_address}">
                        <div class="invalid-feedback">
                            Please enter your shipping address.
                        </div>
                    </div>

                </div>

                <br>
                <hr class="my-4">

                <!--product info-->

                <div class="row g-3">
                    <div class="col-12">
                        <h4 class="mb-3">Select A Product</h4>
                        <br>

                        <label th:for="category"> Category : </label>
                        <select class="form-control form-control-sm" id="category" name="category" autofocus>
                            <option value="">Select Category</option>
                            <option th:each = "product: ${cartItem}"
                                    th:text="${product_category}"
                            >
                            </option>
                        </select>

                        <br>
                        <label th:for="product"> Product Name : </label>
                        <select class="form-control form-control-sm" id="product" name="product" autofocus>
                            <option value="">Select Product</option>
                            <option th:each = "product: ${cartItem}"
                                    th:text="${product_name}"
                            >
                            </option>
                        </select>

                        <br>
                        <label th:for="product_price"> Product Price : </label>
                        <input class="form-control form-control-sm" id="product_price" name="product_price" disabled >

                        <br>
                        <label th:for="roles"> Product Quantity : </label>
                        <input class="form-control form-control-sm" id="product_Qty" name="product_Qty" autofocus>

                        <br>

                        <button class="w-5 btn btn-primary " type="submit" id="add_submit" >Add </button>

                    </div>
                </div>

            </form>

                <br>
                <hr class="my-4">

                <!-- TABLE -->

                <table class = "table table-striped table-bordered" id="show">
                    <thead class = "table-white">
                    <tr>
                        <th> Category </th>
                        <th> Product Name </th>
                        <th> Product Price </th>
                        <th> Product Quantity </th>
                        <th> Total </th>
                        <th> Edit </th>
                        <th> Delete </th>
                    </tr>
                    </thead>

                    <tbody>

                    <tr th:each = "product: ${product}"> <!-- this attribute to list up products  -->

                        <td th:text="${product.product_category}" ></td>
                        <td th:text="${product.product_name}"></td>
                        <td th:text="${product.product_price}"></td>
                        <td th:text="${product.product_quantity}" ></td>
                        <td th:text="${product.product_quantity}" ></td>

                        <td> <center> <a th:href="@{/products/edit/{id}(id=${product.product_id})}" style="color: green"> Edit </a> </center> </td>

                        <td> <center> <a th:href="@{/products/delete_product/{id}(id=${product.product_id}) }" style="color: red"> Delete </a> </center> </td>

                    </tr>

                    </tbody>

                </table>




                <h4 class="mb-3"></h4>

                <br>

                <div class="row g-3">
                    <div class="col-12">
                        <h5 class="mb-3" id="total_bill"> Total: $</h5>
                    </div>
                </div>

                <br>

                <button class="w-100 btn btn-primary btn-lg" type="submit">Generate Bill</button>



        </div>

完整跟蹤錯誤:

 Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.

Mon Oct 18 05:38:16 EDT 2021
There was an unexpected error (type=Internal Server Error, status=500).
An error happened during template parsing (template: "class path resource [templates/makeABill.html]")
org.thymeleaf.exceptions.TemplateInputException: An error happened during template parsing (template: "class path resource [templates/makeABill.html]")
    at org.thymeleaf.templateparser.markup.AbstractMarkupTemplateParser.parse(AbstractMarkupTemplateParser.java:241)
    at org.thymeleaf.templateparser.markup.AbstractMarkupTemplateParser.parseStandalone(AbstractMarkupTemplateParser.java:100)
    at org.thymeleaf.engine.TemplateManager.parseAndProcess(TemplateManager.java:666)
    at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1098)
    at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1072)
    at org.thymeleaf.spring5.view.ThymeleafView.renderFragment(ThymeleafView.java:366)
    at org.thymeleaf.spring5.view.ThymeleafView.render(ThymeleafView.java:190)
    at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1400)
    at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1145)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1084)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:963)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:655)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:764)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:327)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:115)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:81)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:121)
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:115)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
    at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:126)
    at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:81)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
    at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:105)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
    at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:149)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
    at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:218)
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:212)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:103)
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:89)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
    at org.springframework.security.web.csrf.CsrfFilter.doFilterInternal(CsrfFilter.java:117)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
    at org.springframework.security.web.header.HeaderWriterFilter.doHeadersAfter(HeaderWriterFilter.java:90)
    at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:75)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:110)
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:80)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
    at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:55)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:211)
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:183)
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:358)
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:271)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:540)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:382)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:893)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1726)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
    at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.base/java.lang.Thread.run(Thread.java:831)
Caused by: org.attoparser.ParseException: Error during execution of processor 'org.thymeleaf.spring5.processor.SpringInputGeneralFieldTagProcessor' (template: "makeABill" - line 150, col 131)
    at org.attoparser.MarkupParser.parseDocument(MarkupParser.java:393)
    at org.attoparser.MarkupParser.parse(MarkupParser.java:257)
    at org.thymeleaf.templateparser.markup.AbstractMarkupTemplateParser.parse(AbstractMarkupTemplateParser.java:230)
    ... 89 more
Caused by: org.thymeleaf.exceptions.TemplateProcessingException: Error during execution of processor 'org.thymeleaf.spring5.processor.SpringInputGeneralFieldTagProcessor' (template: "makeABill" - line 150, col 131)
    at org.thymeleaf.processor.element.AbstractAttributeTagProcessor.doProcess(AbstractAttributeTagProcessor.java:117)
    at org.thymeleaf.processor.element.AbstractElementTagProcessor.process(AbstractElementTagProcessor.java:95)
    at org.thymeleaf.util.ProcessorConfigurationUtils$ElementTagProcessorWrapper.process(ProcessorConfigurationUtils.java:633)
    at org.thymeleaf.engine.ProcessorTemplateHandler.handleStandaloneElement(ProcessorTemplateHandler.java:918)
    at org.thymeleaf.engine.TemplateHandlerAdapterMarkupHandler.handleStandaloneElementEnd(TemplateHandlerAdapterMarkupHandler.java:260)
    at org.thymeleaf.templateparser.markup.InlinedOutputExpressionMarkupHandler$InlineMarkupAdapterPreProcessorHandler.handleStandaloneElementEnd(InlinedOutputExpressionMarkupHandler.java:256)
    at org.thymeleaf.standard.inline.OutputExpressionInlinePreProcessorHandler.handleStandaloneElementEnd(OutputExpressionInlinePreProcessorHandler.java:169)
    at org.thymeleaf.templateparser.markup.InlinedOutputExpressionMarkupHandler.handleStandaloneElementEnd(InlinedOutputExpressionMarkupHandler.java:104)
    at org.attoparser.HtmlVoidElement.handleOpenElementEnd(HtmlVoidElement.java:92)
    at org.attoparser.HtmlMarkupHandler.handleOpenElementEnd(HtmlMarkupHandler.java:297)
    at org.attoparser.MarkupEventProcessorHandler.handleOpenElementEnd(MarkupEventProcessorHandler.java:402)
    at org.attoparser.ParsingElementMarkupUtil.parseOpenElement(ParsingElementMarkupUtil.java:159)
    at org.attoparser.MarkupParser.parseBuffer(MarkupParser.java:710)
    at org.attoparser.MarkupParser.parseDocument(MarkupParser.java:301)
    ... 91 more
Caused by: java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'CartItem' available as request attribute
    at org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:153)
    at org.springframework.web.servlet.support.RequestContext.getBindStatus(RequestContext.java:903)
    at org.thymeleaf.spring5.context.webmvc.SpringWebMvcThymeleafRequestContext.getBindStatus(SpringWebMvcThymeleafRequestContext.java:227)
    at org.thymeleaf.spring5.util.FieldUtils.getBindStatusFromParsedExpression(FieldUtils.java:306)
    at org.thymeleaf.spring5.util.FieldUtils.getBindStatus(FieldUtils.java:253)
    at org.thymeleaf.spring5.util.FieldUtils.getBindStatus(FieldUtils.java:227)
    at org.thymeleaf.spring5.processor.AbstractSpringFieldTagProcessor.doProcess(AbstractSpringFieldTagProcessor.java:174)
    at org.thymeleaf.processor.element.AbstractAttributeTagProcessor.doProcess(AbstractAttributeTagProcessor.java:74)
    ... 104 more

您的 HTML 中有錯字:

th:object="${CartItem}"

應改為:

th:object="${cartItem}" 

由於您的控制器具有:

@ModelAttribute("cartItem")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM