NinjaBoy
NinjaBoy

Reputation: 3755

spring mvc - How to retrieve values from controller without creating a view

I have a problem here and I need your help.

Im trying to retrieve an integer value from the controller to the jsp.

In my jsp I have an ajax call:

$("#hdnCustomerSize").load(contextPath+"/customer/size", function() {
// some codes
});

In my controller:

@RequestMapping(method = RequestMethod.GET, value="/size")
public void getCustomerSize(Model model) {
   model.addAttribute("customerSize", customerService.getCustomers().size());
}

My problem is Im getting an exception:

javax.servlet.ServletException: Could not resolve view with name 'customer/size' in servlet with name 'tombuyandsell'.

I know Im getting this exception because I intentionally did not map this in views.properties. The reason is I only want to get the integer value size and not a whole jsp page. Please help.

Upvotes: 2

Views: 3074

Answers (2)

sinuhepop
sinuhepop

Reputation: 20307

Try with @ResponseBody:

@ResponseBody
@RequestMapping(method = RequestMethod.GET, value="/size")
public int getGroupChatSize() {
    return customerService.getCustomers().size();
}

Upvotes: 1

Kevin Bowersox
Kevin Bowersox

Reputation: 94429

Use the @ResponseBody annotation and return the int as a String. @ResponseBody will cause the return type to be written to the response HTTP body.

@RequestMapping(method = RequestMethod.GET, value="/size")
@ResponseBody
public String getGroupChatSize(Model model) {
   return Integer.toString(customerService.getCustomers().size());
}

Documentation

Upvotes: 2

Related Questions