控制器方法没有返回值

控制器方法没有返回值

本文介绍了如果 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);
}

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

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?

推荐答案

你可以返回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(...) {
    ...
}

只有 get 方法隐式返回 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 控制器方法没有返回值,返回什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 04:11