Is it better to pass back String or Object in the ResponseEntity<>?

自古美人都是妖i 提交于 2019-12-25 09:29:02

问题


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.

Sample code below:

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);
}

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!


回答1:


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.

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.



来源:https://stackoverflow.com/questions/44497859/is-it-better-to-pass-back-string-or-object-in-the-responseentity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!