简体   繁体   English

spring mvc - 如何在不创建视图的情况下从控制器检索值

[英]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.我试图从控制器检索一个整数值到 jsp。

In my jsp I have an ajax call:在我的jsp中,我有一个ajax调用:

$("#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 .我知道我收到了这个异常,因为我故意没有在views.properties映射它。 The reason is I only want to get the integer value size and not a whole jsp page.原因是我只想获取整数值size而不是整个 jsp 页面。 Please help.请帮忙。

Use the @ResponseBody annotation and return the int as a String.使用@ResponseBody注释并将 int 作为字符串返回。 @ResponseBody will cause the return type to be written to the response HTTP body. @ResponseBody将导致将返回类型写入响应 HTTP 正文。

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

Documentation 文档

Try with @ResponseBody :尝试使用@ResponseBody

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM