通过JSONP实现ajax跨域请求java接口实现

用jsonp实现跨域

 @ApiOperation(value = "Test vehicle param info")
    @RequestMapping(method = RequestMethod.GET, value = {
            "/api/1.0/ups/test",
    }, produces = APPLICATION_JSON_UTF8_VALUE,headers ={"Accept=" + APPLICATION_JSON_UTF8_VALUE})
    public void test(HttpServletRequest request, HttpServletResponse response)throws Exception{
        response.setContentType("text/plain");
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setHeader("Access-Control-Allow-Origin", "*");//添加跨域访问

        Map result = new HashMap();
        Map data=new HashMap();
        ObdParam param=obdParamRepository.getParams().get(0);
        data.put("obdParam",param);
        String jsonpCallback = request.getParameter("callback");//客户端请求参数
        try {
          //  String test=request.getParameter("test");
            result.put("errorCode", "0");
            result.put("errorMessage","success!");
            result.put("data",data);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            PrintWriter out = response.getWriter();
            Gson gson=new Gson();
            String json = gson.toJson(data);
           // JSONObject resultJSON = JSONObject.fromObject(result); //根据需要拼装json
           // out.println(jsonpCallback+"("+resultJSON.toString(1,1)+")");//返回jsonp格式数据
            System.out.print(jsonpCallback+"("+json.toString()+")");
            out.println(jsonpCallback+"("+json.toString()+")");//返回jsonp格式数据
            out.flush();
            out.close();
        }
    }


你可能感兴趣的:(通过JSONP实现ajax跨域请求java接口实现)