0

I want my string method to return value. The below code returns a view(jsp). In the code "line" stores the product details.I want the method to return this value. Could someone show me how to do it.

@RequestMapping(value="addtocart{id}")
@ResponseBody
    public String addToCart(@PathVariable("id") int id, @ModelAttribute("cart") Cart cart)
    {
        Product product = productService.getProductById(id);
            if (product != null) {
            CartLine line = new CartLine();
            line.setProduct(product);
            line.setQuantity(1);
return "viewcart"; 
    }

xml config

<bean id="jsonConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
        <property name="prefixJson" value="false"/>
        <property name="supportedMediaTypes" value="application/json"/>
    </bean>
mattias
  • 2,079
  • 3
  • 20
  • 27

1 Answers1

1

Just change the return type of the controller method to Product and return the Product instance.

Dependending on what HttpMessageConverters you have configured, the response will be the object serialized to JSON for example.

Update

You can see how to configure the Jackson converter here or in Spring MVC documentation.

Community
  • 1
  • 1
Bohuslav Burghardt
  • 33,626
  • 7
  • 114
  • 109
  • I can't use String method? Could you show me please. –  Nov 10 '14 at 17:25
  • @user3844782 what format do you want the returned data to be displayed in? Can it be JSON or do you have some other format in mind? – Bohuslav Burghardt Nov 10 '14 at 17:30
  • You can take a look at this link. It explains how to configure Jackson message converter, which takes care of the object serialization to JSON http://stackoverflow.com/questions/4823358/spring-configure-responsebody-json-format. Try it and if you run in to any problems please update your question with your Spring MVC configuration, right now I can only give you these general directions without knowing how you configure your application (XML or JavaConfig, etc) – Bohuslav Burghardt Nov 10 '14 at 17:34
  • OK. And now that you have the converter registered and return the product itself from the method it still behaves same way as it originally did or do you have some other problem with it? Also just a quick note the version of converter you are using is deprecated, you should use MappingJackson2HttpMessageConverter. – Bohuslav Burghardt Nov 10 '14 at 17:43
  • Ok i will change that. I want to access the value from ajax response. –  Nov 10 '14 at 17:48
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/64647/discussion-between-user3844782-and-bohuslav-burghardt). –  Nov 10 '14 at 17:50