neverwinter
neverwinter

Reputation: 810

return value fails when call java restful webservice from javascript

I have a restful webservice which written in java. And I call it in javascript.

When I call webservice, all codes works perfectly but don't return value perfectly. My codes are here:

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
            }
        });


        };

When I call ws, all "prinln" codes works perfectly but not return value. My js not finish with "success" it fall into "error:" case.

How can I fix it?

Upvotes: 0

Views: 90

Answers (1)

Nikhil Talreja
Nikhil Talreja

Reputation: 2774

You should pass the data using AJAX call as:

data: {param:5},

Use HTTP Request to read the param and you also need to have @ResponseBody annotation for a method that returns JSON:

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

Upvotes: 1

Related Questions