Spring 4 MVC + JSONP Example with REST, @ResponseBody and ResponseEntity

By Arvind Rai, April 25, 2015
On 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

POSTED BY
ARVIND RAI
ARVIND RAI







©2024 concretepage.com | Privacy Policy | Contact Us