如果Spring MVC控制器方法没有返回值,返回什么? [英] What to return if Spring MVC controller method doesn't return value?

查看:408
本文介绍了如果Spring MVC控制器方法没有返回值,返回什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用jQuery的 $。getJSON()来对我的简单Spring MVC后端进行异步调用。大多数Spring控制器方法如下所示:

I am using jQuery's $.getJSON() to make asynchronous calls to my simple Spring MVC backend. Most of the Spring controller methods look like this:

@RequestMapping(value = "/someURL", method = RequestMethod.POST)
public @ResponseBody SomePOJO getSomeData(@ModelAttribute Widget widget,
    @RequestParam("type") String type) {
    return someDAO.getSomeData(widget, type);
}   

我设置了一些东西,以便每个控制器返回 @ResponseBody 作为JSON,这是客户端所期望的。

I have things set up so that each controller returns the @ResponseBody as JSON, which is what the client-side expects.

但是当一个请求不应该返回任何请求时会发生什么内容到客户端?我可以:

But what happens when a request isn't supposed to return any content to the client-side? Can I have:

@RequestMapping(value = "/updateSomeData" method = RequestMethod.POST)
public @ResponseBody void updateDataThatDoesntRequireClientToBeNotified(...) {
    ...
}

如果不,这里使用的语法是什么?在此先感谢!

If not, what's the appropriate syntax to use here? Thanks in advance!

推荐答案

你可以返回void,然后你必须用@ResponseStatus标记方法(value = HttpStatus.OK )你不需要@ResponseBody

you can return void, then you have to mark the method with @ResponseStatus(value = HttpStatus.OK) you don't need @ResponseBody

@RequestMapping(value = "/updateSomeData" method = RequestMethod.POST)
@ResponseStatus(value = HttpStatus.OK)
public void updateDataThatDoesntRequireClientToBeNotified(...) {
    ...
}

只有获取方法返回200状态代码隐含,所有其他方法你做三件事之一:

Only get methods return a 200 status code implicity, all others you have do one of three things:


  • 返回void并使用标记方法@ResponseStatus(value = HttpStatus.OK)

  • 返回一个对象标记为 @ResponseBody

  • 返回 HttpEntity 实例

  • Return void and mark the method with @ResponseStatus(value = HttpStatus.OK)
  • Return An object and mark it with @ResponseBody
  • Return an HttpEntity instance

这篇关于如果Spring MVC控制器方法没有返回值,返回什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆