@ResponseBody与ResponseEntity

转载 2016年05月31日 13:45:48

第一篇文章:

from:

http://stackoverflow.com/questions/22725143/what-is-the-difference-between-responseentityt-and-responsebody

ResponseEntity will give you some added flexibility in defining arbitrary HTTP response headers. See the 4th constructor here:

http://docs.spring.io/spring/docs/3.0.x/api/org/springframework/http/ResponseEntity.html

ResponseEntity(T body, MultiValueMap<String,String> headers, HttpStatus statusCode) 

A List of possible HTTP response headers is available here:

http://en.wikipedia.org/wiki/List_of_HTTP_header_fields#Responses

Some commonly-used ones are Status, Content-Type and Cache-Control.

If you don't need that, using @ResponseBody will be a tiny bit more concise.



第二篇文章:

from:

http://stackoverflow.com/questions/26549379/when-use-responseentityt-and-restcontroller-for-spring-restful-applications

ResponseEntity is meant to represent the entire HTTP response. You can control anything that goes into it: status code, headers, and body.

@ResponseBody is a marker for the HTTP response body and @ResponseStatus declares the status code of the HTTP response.

@ResponseStatus isn't very flexible. It marks the entire method so you have to be sure that your handler method will always behave the same way. And you still can't set the headers. You'd need the HttpServletResponse or a HttpHeaders parameter.

Basically, ResponseEntity lets you do more.



第三篇文章:

from:

http://www.concretepage.com/spring-4/spring-4-mvc-jsonp-example-with-rest-responsebody-responseentity

In this page we will provide Spring 4 MVC and JSONP example with REST, @ResponseBody and ResponseEntity. JSONP is JSON with padding. It supports JavaScript code running in web browser to request data from a server in different domain which is normally prohibited because of same-origin policy. According to this policy a web browser can allow the script code of one web browser to access data from another web browser within the same domain. Same-origin policy is because of web application security model. But this policy is not forced to <script> tag by web browser. From here the role of JSONP comes into picture. JSONP allows to access data from different domain using<script> tag by web browser. If we have a URL as
http://localhost:8080/concretepage-1/book1?callback=myfunction
and if it throws the JSONP response as

myfunction({"bookName":"Godan","writer":"Premchand"});
 
then in another domain, we can use it as
<script src=" http://localhost:8080/concretepage-1/book1?callback=myfunction " type="application/javascript"> </script>
 
In our client code to access JSONP, there should already be a function named myfunction() defined in script code.To throw the JSONP response using spring, it provides AbstractJsonpResponseBodyAdvice class which is implemented by a class annotated with @ControllerAdvice.

Spring 4 Support for JSONP with AbstractJsonpResponseBodyAdvice

Find the our class which will support JSONP response.
JsonpAdvice.java
@ControllerAdvice
public class JsonpAdvice extends AbstractJsonpResponseBodyAdvice {
    public JsonpAdvice() {
        super("callback");
    }
} 
In the constructor, we need to call super method passing a key. This key will be used in query string of URL while requesting JSONP data. The above method facilitates REST web service to respond JSONP data and also controller method which respond using @ResponseBody and ResponseEntity.

JSONP with Spring REST

Find the bean being used in the example to generate JSON.
Book.java
public class Book {
        private String bookName;
        private String writer;
	public String getBookName() {
		return bookName;
	}
	public void setBookName(String bookName) {
		this.bookName = bookName;
	}
	public String getWriter() {
		return writer;
	}
	public void setWriter(String writer) {
		this.writer = writer;
	}
} 
We are creating a web service which will respond JSONP.
BookService.java
@RestController
class BookService {
    @RequestMapping(value= "/book1", produces = MediaType.APPLICATION_JSON_VALUE)
    Book bookInfo1() {
    	Book book = new Book();
    	book.setBookName("Godan");
    	book.setWriter("Premchand");
        return book;
    }
} 
When we access the URL http://localhost:8080/concretepage-1/book1?callback=functionCall, it will throw the response as
functionCall({"bookName":"Godan","writer":"Premchand"});
 

JSONP with @ResponseBody and ResponseEntity

Now find a controller in which we have created methods that will return @ResponseBody and ResponseEntity.
@Controller
class BookController {
    @RequestMapping(value ="/book2", produces =MediaType.APPLICATION_JSON_VALUE )
    @ResponseBody
    Book bookInfo2() {
    	Book book = new Book();
    	book.setBookName("Ramcharitmanas");
    	book.setWriter("TulasiDas");
    	return book;
    }
    @RequestMapping(value ="/book3", produces =MediaType.APPLICATION_JSON_VALUE )
    public ResponseEntity<Book> bookInfo3() {
    	Book book = new Book();
    	book.setBookName("Ramayan");
    	book.setWriter("Valmiki");
        return ResponseEntity.accepted().body(book);
    } 
} 
When we access the URL http://localhost:8080/concretepage-1/book2?callback=functionCall, we will get the output in browser as
functionCall({"bookName":"Ramcharitmanas","writer":"TulasiDas"});
 
And for the URL http://localhost:8080/concretepage-1/book3?callback=functionCall, the output will be
functionCall({"bookName":"Ramayan","writer":"Valmiki"});
 

JSONP Client Code

Now we will write client code which can be used in any other domain.
jsonptest.html
<html>
 <head>
   <script>
     function functionCall(data) {   
		console.log(data.bookName);
		console.log(data.writer);
		console.log('-----------');
     }
   </script>
  </head>
  <body>
        <!-- Using REST URL-->
        <script src="http://localhost:8080/concretepage-1/book1?callback=functionCall" type="application/javascript"> </script>
	
	<!--Using @ResponseBody -->
	<script src="http://localhost:8080/concretepage-1/book2?callback=functionCall" type="application/javascript"> </script>
	
	<!--Using ResponseEntity -->
	<script src="http://localhost:8080/concretepage-1/book3?callback=functionCall" type="application/javascript"> </script>
  </body>
</html> 
Run this page and check the output in console.
Spring 4 MVC  + JSONP Example with REST, @ResponseBody and ResponseEntity


Now we are done. Happy Learning!

Download Source Code


SPRING MVC3.2案例讲解--SPRING MVC3的@ResponseBody和ResponseEntity

在传统的开发过程中,我们的控制CONTROLL层通常需要转向一个JSP视图;但随着WEB2.0相关技术的崛起,我们很多时候只需要返回数据即可,而不是一个JSP页面。   SPRING MVC3的@...

MongoDB分片(Sharding)集群(Cluster)

单数据量大或者吞吐量大到一定程度的时候,一个服务器已经无法支撑了——频繁的查询会耗尽CPU资源、不断增多的数据会耗尽硬盘空间、不断增大的工作空间(包括索引)会耗尽内存最终导致虚拟内存(磁盘)的使用、等...

spring mvc @ResponseStatus 和 ResponseEntity

@ResponseStatus 是标记一个方法或异常类在返回时响应的http状态。其代码注释如下:* * The status code is applied to the HTTP response...
  • Mr_rain
  • Mr_rain
  • 2017年05月05日 17:36
  • 4033

使用Itext做pdf文档下载--返回前端类型为ResponseEntity(byte[])

近期项目中需要使用到下载pdf文档的操作,由于之前都没接触过,然后到网上查了下有两种选择OpenOffice和Itext。开始试了下OpenOffice,但是感觉太繁琐笨重,果断放弃了。后来就选用了I...

SpringMVC中controller中方法返回类型为ResponseEntity<String>乱码的问题

返回类型为ResponseEntity 代表我们返回的数据是一个对象,在springMVC中,请求数据到对象和对象到响应数据的转换是通过消息转换器来完成的。 HttpMessageConverter是...

######springmvc中方法返回值为String时@responseBody不能返回json对象。

==============【应用:这一特性,springmvc文件上传时,富文本 kindEditor插件,页面返回 改为 String,解决了《文件上传浏览器兼容性问题》】 ===因为所有浏览器...

SpringMVC使用@ResponseBody时返回json的日期格式、@DatetimeFormat使用注意

一、SpringMVC使用@ResponseBody时返回json的日期格式        前提了解: @ResponseBody 返回json字符串的核心类是org.springfram...

SpringMVC中使用@RequestBody,@ResponseBody注解实现Java对象和XML/JSON数据自动转换(下)

上一篇分析了spring中是如何通过使用@ResponseBody注解,实现自动转换Java对象为XML,JSON数据到Reponse中。 接下来看看如果request中包含了XML或者JSON...

Spring中Responsebody注解的作用

@responsebody表示该方法的返回结果直接写入HTTP response body中 一般在异步获取数据时使用。在使用@RequestMapping后,返回值通常解析为跳转路径。...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:@ResponseBody与ResponseEntity
举报原因:
原因补充:

(最多只允许输入30个字)