5

I have hard time dealing with JSONP while migrating to Spring 5.1 from Spring 4

Spring 4 provides AbstractJsonpResponseBodyAdvice class for jsonp

However, AbstractJsonpResponseBodyAdvice class is gone in Spring 5.

Is there any supplementary class in Spring 5.1???

Leo
  • 822
  • 2
  • 11
  • 22

2 Answers2

3

AbstractJsonpResponseBodyAdvice was deprecated starting from Spring 5.0.7 and 4.3.18 and in version 5.1 it is completely removed. There is no direct replacement in Spring 5.1 and instead of using of insecure JSON-P you should migrate on CORS (Cross-Origin Resource Sharing) which allows you to specify what kind of cross domain requests are authorized.

Read more about CORS in Spring documentation here: https://docs.spring.io/spring/docs/5.0.x/spring-framework-reference/web.html#mvc-cors

And there is also lot of question regarding CORS on SO - for example: How to configure CORS in a Spring Boot + Spring Security application?


And of course there is always a dirty option where you can disembowel AbstractJsonpResponseBodyAdvice class and all its dependencies into separate jar and use it also with new versions of Spring but I think it is better to start with CORS ;-)

cgrim
  • 4,890
  • 1
  • 23
  • 42
0

I handle it with raw code:

    // http://127.0.0.1:8080/jsonp/test?callback=json_123456
    @GetMapping(value = "/test")
    public void testJsonp(HttpServletRequest httpServletRequest,
                          HttpServletResponse httpServletResponse,
                          @RequestParam(value = "callback", required = false) String callback) throws IOException {
        JSONObject json = new JSONObject();
        json.put("a", 1);
        json.put("b", "test");
        String dataString = json.toJSONString();

        if (StringUtils.isBlank(callback)) {
            httpServletResponse.setContentType("application/json; charset=UTF-8");
            httpServletResponse.getWriter().print(dataString);
        } else {
            // important: contentType must be text/javascript
            httpServletResponse.setContentType("text/javascript; charset=UTF-8");
            dataString = callback + "(" + dataString + ")";
            httpServletResponse.getWriter().print(dataString);
        }
//        return dataString;
    }
learner
  • 1,381
  • 1
  • 10
  • 16