【问题标题】:return value fails when call java restful webservice from javascript从javascript调用java restful webservice时返回值失败
【发布时间】:2014-06-30 06:34:32
【问题描述】:

我有一个用 java 编写的宁静的 web 服务。我用javascript调用它。

当我调用 web 服务时,所有代码都可以正常运行,但不能完美返回值。我的代码在这里:

ws:

@RestController
public class VillageService {

    @Autowired

private InnerService innerService;


@RequestMapping(value = "/services/getVillages")
public  Village getAllVillages(@RequestParam int param) throws JSONException {

      long startTime = System.currentTimeMillis();
      Village result = innerService.getAllVillagesCacheable(param);
      long stopTime = System.currentTimeMillis();
      long elapsedTime = stopTime - startTime;
      System.out.println("süre: " + elapsedTime);         

      startTime = System.currentTimeMillis();
      Village result2 = innerService.getAllVillages(param);
      stopTime = System.currentTimeMillis();
      elapsedTime = stopTime - startTime;
      System.out.println("süre cache'siz: " + elapsedTime);       

      return result;
    }
}

Js:

        function callWS()
        {

        $.ajax({
            type: 'GET',
            url: 'http://localhost/services/getVillages/',
            data: "param=5", // the data in form-encoded format, ie as it would appear on a querystring
            dataType: "json", // the data type we want back, so text.  The data will come wrapped in xml
            success: function (data) {
                alert("party hard"); // show the string that was returned, this will be the data inside the xml wrapper
            },
            error: function (data) {
                alert("restful cagirmada hata"); // show the string that was returned, this will be the data inside the xml wrapper
            }
        });


        };

当我调用 ws 时,所有“prinln”代码都可以正常工作,但不能返回值。我的 js 没有以“成功”结束,它属于“错误:”案例。

我该如何解决?

【问题讨论】:

  • result 执行System.out.println 并检查浏览器控制台是否有任何错误。

标签: java javascript web-services rest


【解决方案1】:

您应该使用 AJAX 调用传递数据:

data: {param:5},

使用 HTTP 请求读取参数,还需要为返回 JSON 的方法添加 @ResponseBody 注解:

@RequestMapping(value = "/services/getVillages")
@ResponseBody
public  Village getAllVillages(HttpServletRequest request) throws JSONException {
      String param = request.getParameter("param");

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-24
  • 1970-01-01
  • 2018-02-27
相关资源
最近更新 更多