2013-06-19 2 views
0

Я пытаюсь использовать форму Spring с моим контроллером, а сущность, к которой она привязана, имеет вложенные объекты. Когда вы пытаетесь попасть на страницу с помощью формы, она выдает следующую ошибку.Весенняя форма с вложенными объектами бросает ошибку привязки объекта-объекта

Я не инициализирую модель правильно?

Контроллер:

@RequestMapping(value = "/payPal2", 
     headers = "Accept=application/json", 
     method = RequestMethod.POST) 
public 
@ResponseBody 
Payment payByCreditCard2(@ModelAttribute("orderContext") OrderContext orderContext, Model model) throws Exception { 
    PaymentWithCreditCard paymentWithCreditCard = new PaymentWithCreditCardImpl(); 
    model.addAttribute("billingAddress", new Address()); 

    OTHER Setters and getters down here 

Форма:

<form:form modelAttribute="orderContext" method="post" action="/service/payments/payPal2"> 
    <form:input path="billingAddress.city"/> 
</form:form> 

Ошибка:

org.apache.jasper.JasperException: An exception occurred processing JSP page /paypalTest.jsp at line 14 

11: </head> 
12: <body> 
13: <form:form modelAttribute="orderContext" method="post" action="/service/payments/payPal2"> 
14:  <form:input path="billingAddress.city"/> 
15: </form:form> 
16: </body> 
17: </html> 

root cause 

java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'orderContext' available as request attribute 
    org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:141) 
    org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getBindStatus(AbstractDataBoundFormElementTag.java:178) 
    org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getPropertyPath(AbstractDataBoundFormElementTag.java:198) 
    org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getName(AbstractDataBoundFormElementTag.java:164) 
    org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.autogenerateId(AbstractDataBoundFormElementTag.java:151) 
    org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.resolveId(AbstractDataBoundFormElementTag.java:142) 
    org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.writeDefaultAttributes(AbstractDataBoundFormElementTag.java:126) 
    org.springframework.web.servlet.tags.form.AbstractHtmlElementTag.writeDefaultAttributes(AbstractHtmlElementTag.java:421) 
    org.springframework.web.servlet.tags.form.InputTag.writeTagContent(InputTag.java:142) 
    org.springframework.web.servlet.tags.form.AbstractFormTag.doStartTagInternal(AbstractFormTag.java:102) 
    org.springframework.web.servlet.tags.RequestContextAwareTag.doStartTag(RequestContextAwareTag.java:79) 
    org.apache.jsp.paypalTest_jsp._jspx_meth_form_005finput_005f0(paypalTest_jsp.java:151) 
    org.apache.jsp.paypalTest_jsp._jspx_meth_form_005fform_005f0(paypalTest_jsp.java:116) 
    org.apache.jsp.paypalTest_jsp._jspService(paypalTest_jsp.java:77) 
    org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70) 
    javax.servlet.http.HttpServlet.service(HttpServlet.java:728) 
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432) 
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390) 
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334) 
    javax.servlet.http.HttpServlet.service(HttpServlet.java:728) 
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) 
    org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118) 
    org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84) 
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) 
    org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113) 
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) 
    org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103) 
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) 
    org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113) 
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) 
    org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter.doFilter(RememberMeAuthenticationFilter.java:139) 
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) 
    org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:54) 
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) 
    org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45) 
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) 
    org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:150) 
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) 
    org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter.doFilter(DefaultLoginPageGeneratingFilter.java:91) 
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) 
    org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:183) 
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) 
    org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105) 
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) 
    org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87) 
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) 
    org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192) 
    org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160) 
    org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346) 
    org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:259) 

заказа Контекст:

import com.paypal.api.payments.*; 
import com.paypal.api.payments.Address; 

import java.util.List; 

public class OrderContext { 
    private com.paypal.api.payments.Address billingAddress; 
    private CreditCard creditCard; 
    private Details details; 
    private Amount amount; 
    private List<Transaction> transactions; 
    private List<FundingInstrument> fundingInstruments; 
    private Payer payer; 
    private Payment payment; 

    public Address getBillingAddress() { 
     return billingAddress; 
    } 

    public void setBillingAddress(Address billingAddress) { 
     this.billingAddress = billingAddress; 
    } 

    public CreditCard getCreditCard() { 
     return creditCard; 
    } 

    public void setCreditCard(CreditCard creditCard) { 
     this.creditCard = creditCard; 
    } 

    public Details getDetails() { 
     return details; 
    } 

    public void setDetails(Details details) { 
     this.details = details; 
    } 

    public Amount getAmount() { 
     return amount; 
    } 

    public void setAmount(Amount amount) { 
     this.amount = amount; 
    } 

    public List<Transaction> getTransactions() { 
     return transactions; 
    } 

    public void setTransactions(List<Transaction> transactions) { 
     this.transactions = transactions; 
    } 

    public List<FundingInstrument> getFundingInstruments() { 
     return fundingInstruments; 
    } 

    public void setFundingInstruments(List<FundingInstrument> fundingInstruments) { 
     this.fundingInstruments = fundingInstruments; 
    } 

    public Payer getPayer() { 
     return payer; 
    } 

    public void setPayer(Payer payer) { 
     this.payer = payer; 
    } 

    public Payment getPayment() { 
     return payment; 
    } 

    public void setPayment(Payment payment) { 
     this.payment = payment; 
    } 

    @Override 
    public String toString() { 
     return "OrderContext{" + 
       "billingAddress=" + billingAddress + 
       ", creditCard=" + creditCard + 
       ", details=" + details + 
       ", amount=" + amount + 
       ", transactions=" + transactions + 
       ", fundingInstruments=" + fundingInstruments + 
       ", payer=" + payer + 
       ", payment=" + payment + 
       '}'; 
    } 
} 
+0

плз разделяют реализации OrderContext – sidgate

+0

@sidgate, добавил :) – zmanc

ответ

1

Я считаю, что вам нужно создать два метода в контроллерах: один, который обрабатывает отображение формы (GET), а другой - обрабатывает форму после отправки (POST).

Вы используете только метод POST, т. Е. При получении данных формы после отправки.

// just displays the form 
@RequestMapping(value = "/payPal2", method = RequestMethod.GET) 
public String payByCreditCardGet(@ModelAttribute("orderContext") OrderContext orderContext, Model model) throws Exception { 
    // orderContext is "empty", just need to return the JSP path to the form 
    return "paypal/index"; // for example 
} 

// receives the form 
@RequestMapping(value = "/payPal2", headers = "Accept=application/json", method = RequestMethod.POST) 
public @ResponseBody Payment payByCreditCardPost(@ModelAttribute("orderContext") OrderContext orderContext, Model model) throws Exception { 
    // form is submitted, orderContext is set depending on the form entries 
} 
+0

это единственный view Я буду возвращать, кроме индекса, поскольку все остальное обрабатывается AngularJS. Есть ли способ, которым я могу это сделать, не возвращая взгляда на запрос GET? Если мне нужно переключиться с (@) ModelAttribute на (@) ResponseBody, это нормально. – zmanc

+0

Этот ответ правильный в вопросе. В итоге я перешел к (@) RequestBody, хотя, поскольку я мог просто передать Json. Спасибо за ответ. – zmanc

-1

Метод, из которого вы перенаправляют сформировать, добавить OrderContext объект в области действия запроса, как это:

@RequestMapping(ur_mapping_url) 
public String loadForm(Model model){ 
    model.addAttribute(new OrderContext()); 
    return "formPage_name"; 
} 
+0

Аннотация '@ ModelAttribute' автоматически добавляет соответствующий параметр в качестве атрибута модели. – sp00m

+0

@ sp00m: перед тем, как перейти на страницу формы, ему нужно поместить экземпляр объекта в область запроса. '@ ModelAttribute' будет использоваться для извлечения модели с страницы jsp на ваш контроллер. –

+0

Это также можно сделать с помощью аннотации: аннотированный параметр будет автоматически создан, если он уже не связан переданной формой. – sp00m

Смежные вопросы