1. 程式人生 > >SpringMVC返回jsonp解決跨域問題

SpringMVC返回jsonp解決跨域問題

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"}