我的REST控制器代码如下:
@RequestMapping(value = "foo", method = RequestMethod.GET)
public ResponseEntity<Result> doSomething(@RequestParam int someParam)
{
try
{
final Result result = service.getByParam(someParam);
if (result == null)
{
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
} else
{
return ResponseEntity.ok(result);
}
} catch (Exception ex)
{
LOG.error("Error blah", ex);
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
我想使用 ResponseEntity.noContent()。build()但Eclipse给了我:
类型不匹配:无法从ResponseEntity转换为 ResponseEntity
有没有办法克服这个问题?
更新
可以像这样创建帮助:
public class ResponseUtils
{
public static <T> ResponseEntity<T> noContent()
{
return withStatus(HttpStatus.NO_CONTENT);
}
public static <T> ResponseEntity<T> internalServerError()
{
return withStatus(HttpStatus.INTERNAL_SERVER_ERROR);
}
public static <T> ResponseEntity<T> accepted()
{
return withStatus(HttpStatus.ACCEPTED);
}
private static <T> ResponseEntity<T> withStatus(HttpStatus status)
{
return new ResponseEntity<T>(status);
}
}
所以我可以像:
一样使用它return ResponseUtils.noContent();
但也许有这种东西的内置功能?
答案 0 :(得分:1)
这是你想要实现的吗?
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import javax.xml.transform.Result;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
检查导入,我正在使用:
mean