SpringMVC返回jsonp解决跨域问题

时间:2021-08-30 20:32:04
package s.s.m.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.converter.json.MappingJacksonValue;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import s.s.m.service.GoodsService;

import com.alibaba.fastjson.JSONObject;

@Controller
@RequestMapping({ "/gj" })
public class GoodsJsonpController {
@Autowired
private GoodsService goodsService;

@RequestMapping(value = { "/select" }, method = { RequestMethod.GET })
@ResponseBody
public MappingJacksonValue query(@RequestParam(value="callback",required=false) String callback) {
JSONObject obj = new JSONObject();
obj.put("name", "li");
MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(obj);
if(callback!=null){
mappingJacksonValue.setJsonpFunction("callbackname");
}
return mappingJacksonValue;
}
}


请求:包含参数如callback=jsonpCall时候返回jsonp:   callbackname({"name":"li"})

           不包含参数如callback=jsonpCall时候返回json: {"name":"li"}