ssm返回jsonp数据格式

为了便于客户端使用数据,逐渐形成了一种非正式传输协议,人们把它称作JSONP,该协议的一个要点就是允许用户传递一个callback参数给服务端,然后服务端返回数据时会将这个callback参数作为函数名来包裹住JSON数据,这样客户端就可以随意定制自己的函数来自动处理返回数据了。
 
 
 
   
package shopping.controller;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.databind.util.JSONPObject;

import shopping.template.ResponseTemplate;
import shopping.utils.ReadExcel;

@Controller
@CrossOrigin
@RequestMapping("/shopping")
public class MyShopping {

       @RequestMapping("/get")    //通过http响应解决调用
       public void get(HttpServletRequest req,HttpServletResponse res) throws FileNotFoundException {
            ReadExcel obj = new ReadExcel();
            // 此处为我创建Excel路径:E:/zhanhj/studysrc/jxl下
//            File file = new File(this.getClass().getResource("/")+"test.xlsx");
            
        
            File file = ResourceUtils.getFile("classpath:test1.xls");

            List excelList = obj.readExcel(file);
            
           res.setContentType("text/plain");
           String callbackFunName =req.getParameter("callback");//得到js函数名称
           try {
               res.getWriter().write(callbackFunName + "([ { data:"excelList"}])"); //返回jsonp数据
           } catch (IOException e) {
               e.printStackTrace();
           }
       }
       
       @RequestMapping("/getJsonp")
       @ResponseBody
       public JSONPObject getJsonp(String callback) throws FileNotFoundException{
        
            ReadExcel obj = new ReadExcel();
            // 此处为我创建Excel路径:E:/zhanhj/studysrc/jxl下
//            File file = new File(this.getClass().getResource("/")+"test.xlsx");
            
        
            File file = ResourceUtils.getFile("classpath:test1.xls");

            List excelList = obj.readExcel(file);
            
            ResponseTemplate response=new ResponseTemplate(0, "成功", excelList);
            
           return new JSONPObject(callback, response); 
       }
}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
原文地址:https://www.cnblogs.com/liyafei/p/8325767.html