• Angular4 JSONP + JAVA代码


    一、在app.module.ts模块中,注入JsonpModule模块

    import {JsonpModule} from "@angular/http";
    
    @NgModule({
        imports: [
            JsonpModule    //注入JSonpModule模块
        ]
    })

    二、创建服务httpService,并注入jsonp和map(分装好的服务 可以直接调用)

    import {Injectable} from '@angular/core';
    import {Jsonp, URLSearchParams} from "@angular/http";
    
    @Injectable()
    export class HttpService {
    
        private jsonpTimes = 0;   // 用于记录jsonp请求的次数
    
        constructor(private jsonp: Jsonp) {
    
        }
    
        jsonpGet(apiURL, req){
            let params = new URLSearchParams();
            //设置参数
            for (let key in req) {
                params.set(key, req[key]);
            }
            params.set('format', 'json');
            params.set("callback", `__ng_jsonp__.__req${this.jsonpTimes}.finished`);
            this.jsonpTimes++;
    
            let request = this.jsonp.get(apiURL, { search: params })
                .map((res) => {
                    let response = res.json();
                    return response;
                });
            return request;
        }
    
    }

    三、业务组件调用httpService

    let newUrl = localServer + "/search"; //查询网址 
    let req = { id: 123, name: "abc" }; //查询参数
    this.httpService.jsonpGet(newUrl, req).subscribe(data => {
                let result = data.data;
            });

    后端JAVA代码

    @RequestMapping(value = "mergeJson")
         public void exchangeJson(HttpServletRequest request,HttpServletResponse response)  throws Exception {  
                  String businessnum = request.getParameter("businessnum");
                  String paths = request.getParameter("paths");
                  List<String>  pathList =  Arrays.asList( paths.split(","));  
                 
                  List<String> resultPath = mergeService.merge(businessnum, pathList);
                  String return_JSONP = String.join(",", resultPath);
                  String jsonCallback = request.getParameter("callback"); //jsonpCallback 客户端请求参数  
                  Map<String,Object> map = new HashMap<>();
                  map.put("data",return_JSONP);
                  JSONObject resultJSON = new JSONObject(map);//根据需要拼装json  
    
                  PrintWriter pw = response.getWriter();
                  pw.write(jsonCallback+"("+resultJSON+")");  
                  pw.close();
                  pw = null;
            }  

    参考资料:https://www.cnblogs.com/minigrasshopper/p/7692368.html

  • 相关阅读:
    【Oracle】修改oracle数据库的字符集
    【OS_Linux】Centos7 设置定时任务
    【 DB_Oracle】Oracle多表关联更新
    Java后端技术路线
    【 OS_Linux】centos下查找jdk的安装路径
    【实用工具】Notepad++的主题和字体设置
    【OS_Linux】Linux删除指定日期之前的文件
    【OS_Windows】windows下删除指定日期前的文件
    C#计算一段程序运行时间的三种方法
    Win10 新功能 改变显示器色彩
  • 原文地址:https://www.cnblogs.com/Anlycp/p/9366909.html
Copyright © 2020-2023  润新知