struts2返回json,前端jsonp获取为null?

前端采用vue+webpack,监听端口8000
后端采用java(struts2+hibernate+spring)的组合,tomcat监听端口8080

前端想获取后端返回来的json数据,却获取为null?初步判断为后端的问题,求解决方案
用jquery的ajax方法测试过同样也获取为null

前端显示数据组件的jsonp代码:

jsonp: function(url, data={}, callbackName = 'callback') {
   return new Promise((resolve, reject) => {
       console.log(url)
       console.log(data)
       console.log(callbackName)
       window.__onGetData__ = data => resolve(data)
       console.log(window.__onGetData__)
       let queryString = Object.keys(data).map(k => `${k}=${data[k]}`).join(`&`)
       console.log(queryString)
       let script = document.createElement('script')
       document.head.appendChild(script)
       script.src = `${url}?${callbackName}=__onGetData__`
       script.addEventListener('error', ()=>{ reject('load error')})
       document.head.removeChild(script)
  })
},
  showData: function(){
       this.jsonp('http://localhost:8080/QAsys/user_getAll')
       .then(data =>{
       console.log(data)
          tableData = data;
       }).catch(err => {
          console.log(err)
       })
  }

返回json的action代码:

public class UserAction extends ActionSupport implements ServletRequestAware, ServletResponseAware {
    private HttpServletRequest request; //request-api
    private HttpServletResponse response;
    private ObjectMapper mapper = new ObjectMapper();//jackson 变量
    private String result = new String();//结果字符串
    private Page page = new Page(); //保存查询结果的页数信息

    public void setServletRequest(HttpServletRequest request) {
        this.request = request;
    }
    public void setServletResponse(HttpServletResponse response){ this.response = response;}
    public void setResult(String result){
        this.result = result;
    }

    @Autowired
    private UserService userService;

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    public String getAllUser(){
        //翻到首页
        page.setOffset(0);
        page.setLength(10);

        response.setContentType("text/plain");
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Access-Control-Allow-Origin", "*");//添加跨域访问
        response.setDateHeader("Expires", 0);

        try{
            List<User> list = userService.getAllUser(page.getOffset(), page.getLength());
            page.setMax(list.size());//设置数据量的大小
            //将查询结果转换成json字符串
            result = mapper.writeValueAsString(list);
            System.out.println(result);
            PrintWriter out = response.getWriter();
            String jsonpCallback = request.getParameter("callback");//客户端请求参数
            out.println(jsonpCallback+"("+result+")");//返回jsonp格式数据
        }catch (Exception e){
            e.printStackTrace();
        }
        return SUCCESS;
    }

struts.xml

<struts>
    <constant name="struts.i18n.encoding" value="UTF-8"></constant>
    <!--<constant name="struts.action.excludePattern" value="../webapp/static/*/.*?" />-->

    <!-- Struts2在2.5版本后添加strict-method-invocation(严格方法访问),默认为true,不能使用动态方法调用功能,故需设为false -->
    <package name="default" extends="struts-default" namespace="/" strict-method-invocation="false">
        <result-types>
            <result-type name="json" class="org.apache.struts2.json.JSONResult"/>
        </result-types>

        <!-- CRUD用户信息 -->
        <action name="user_*" class="org.ssh.action.UserAction" method="{1}User">
            <result name="success" type="json">
                <param name="root">result</param>
                <param name="callbackParameter">callback</param>
            </result>
        </action>
    </package>

</struts>

回答:

原来是自己一直在转牛角尖 获取不了数据跟前后端约定的回调函数名称有关,还有不需添加response的头文件信息(具体原理没有研究过)

暂无评论

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注