当前位置: 首页 > 知识库问答 >
问题:

当我试图使用Spring boot将产品添加到购物车时,我得到了一个错误

程凯定
2023-03-14
@Entity
@Data
public class Categories {

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

private String categoryName;

在这个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>

FullTrace错误:

 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

共有1个答案

燕和同
2023-03-14

您的HTML中有错别字:

th:object="${CartItem}"

应改为:

th:object="${cartItem}" 

因为您的控制器具有:

@ModelAttribute("cartItem")
 类似资料: