0

I have a spring form that submits via ajax. Here is my form...

<form:form action="addToCart" method="POST"
                modelAttribute="cartProduct">
                <form:input type="hidden" path="product.productId"
                    value="${inventory.getProduct().getProductId()}" />
                <div class="card-block" style="overflow: hidden; padding: 2%">
                    <h5 style="white-space: nowrap">
                        <a href="#" class="text-primary card-title">${inventory.getProduct().getName()}</a>
                    </h5>
                    <p class="card-text text-danger">&#8369;
                        ${inventory.getProduct().getPrice()}</p>
                    <p>
                    <div class="success-message-container">
                        <span class="text-success add-to-cart"><strong>&nbsp;</strong></span>
                    </div>
                    <div class="success-message vertical-center"
                        style="display: none;">
                        <span class="text-success add-to-cart"><strong>Added
                                to cart!</strong></span>
                    </div>
                    <form:button id="addToCart" class="btn btn-block btn-warning">Add to cart</form:button>
                    <a id="viewCart" href="viewCart" class="btn btn-block btn-warning" style="display: none;">View cart</a>
                </div>
</form:form>

Then it gets submitted via ajax code...

$(document).ready(function() {

var form = $("form");
var url = form.attr("action");
var formMethod = form.attr("method");

form.submit(function(event) {

    event.preventDefault();

    var thisForm = this;

    $.ajax({

        url : url,
        data : $(this).serialize(),
        type : "POST",
        headers: { 
            'Content-Type': 'application/json' 
        },
        success : function(cartProduct) {
            $(thisForm).find('.success-message-container').remove();
            $(thisForm).find('.success-message').show();
            $(thisForm).find('#addToCart').hide();
            $(thisForm).find('#viewCart').toggle();
        }
    });
});

});
});

And here is the receiving rest controller...

@RequestMapping(value="/addToCart", method = RequestMethod.POST)
public CartProduct addToCart(@RequestBody CartProduct cartProduct, HttpServletRequest request){

    System.out.println(cartProduct.getProduct().getProductId());
    return null;
}

However, I keep on getting this error...

POST http://localhost:8080/tommystore/customer/addToCart 400 (Bad Request)

I have imported Jackson for automatic object mapping but it still does not work...

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.6.3</version>
    </dependency>

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.6.3</version>
    </dependency>

How can I fix this?

saluyotamazing
  • 107
  • 1
  • 9

1 Answers1

0

Spring use HttpMessageConverter to convert request body to the method argument . There are two format (json or xml, i prefer json) HttpMessageConverter is responsible for converting from the HTTP request message to an object and converting from an object to the HTTP response body. HttpMessageConverter use you should add dataType: 'xml' or to your ajax and change the format of data to xml

in the server, config XML Converter to convert you xml data to object

@Configuration
@ComponentScan({ "yourpackage" })
public class WebConfig extends WebMvcConfigurerAdapter 
{
@Override
public void configureMessageConverters(
  List<HttpMessageConverter<?>> converters) {

    messageConverters.add(createXmlHttpMessageConverter());
    messageConverters.add(new MappingJackson2HttpMessageConverter());

    super.configureMessageConverters(converters);
}
private HttpMessageConverter<Object> createXmlHttpMessageConverter() {
    MarshallingHttpMessageConverter xmlConverter = 
      new MarshallingHttpMessageConverter();

    XStreamMarshaller xstreamMarshaller = new XStreamMarshaller();
    xmlConverter.setMarshaller(xstreamMarshaller);
    xmlConverter.setUnmarshaller(xstreamMarshaller);

    return xmlConverter;
}
}

in your XML context, register your converter

<context:component-scan base-package="your package" />

<mvc:annotation-driven>
    <mvc:message-converters>
       <bean
         class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>

       <bean class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter">
           <property name="marshaller" ref="xstreamMarshaller" />
           <property name="unmarshaller" ref="xstreamMarshaller" />
       </bean> 
    </mvc:message-converters>
</mvc:annotation-driven>

<bean id="xstreamMarshaller" class="com.fasterxml.jackson.core" />
Tung Vo
  • 2,227
  • 5
  • 27
  • 45