最好在ResponseEntity中传回String或Object? [英] Is it better to pass back String or Object in the ResponseEntity<>?

查看:960
本文介绍了最好在ResponseEntity中传回String或Object?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个返回ResponseEntity的控制器.现在,我更改了此代码,并使用ObjectMapper添加了一堆过滤器.进行此更改后,我将返回一个String作为响应.

I have a controller that returns ResponseEntity. Now I have altered this code and added a bunch of filters using ObjectMapper. After this change I am returning a String as the response.

下面的示例代码:

public ResponseEntity<String> search() {
SearchResult searchResults = service.search(criteria);
objectMapper.setFilterProvider(new SimpleFilterProvider()
                .addFilter("firstFilter", new FirstFilter())
                .addFilter("secondFilter",new SecondFilter()));
        return new ResponseEntity<>(objectMapper.writeValueAsString(searchResults), OK);
}

现在我的问题是,这是一种很好的方法吗?是否有任何影响.将实际对象发回而不是它的String变体有什么区别?任何帮助表示赞赏.谢谢!

Now my question is, is this a good way of doing it. Does it have any implications. What is the difference between sending the actual Object back as opposed to the String variant of it. Any help appreciated. Thanks!

推荐答案

ResponseEntity<T> represents the entire HTTP response. Besides the entity itself, its API allows you to set headers and a status code to the response.

从长远来看,返回普通的String不会给您太大的灵活性.例如,如果需要在响应中添加标头,则需要更改方法的返回类型.

Returning a plain String won't give you much flexibility in the long run. If you need to add a header to the response, for example, you need to change the method return type.

这篇关于最好在ResponseEntity中传回String或Object?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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