@ResponseBody与ResponseEntity

第一篇文章:

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值