Вызов службы Java EE REST через jQuery AJAX путем передачи параметров из текстового поля ввода - PullRequest
0 голосов
/ 23 января 2019

У меня есть HTML-код для создания текстового поля ввода, которое принимает форму ввода пользователя. И параметры должны быть переданы вместе с URL-адресом для остальных услуг. Это мой код вызова Ajax:

$(function() {

var empid = document.getElementById("ManagerId").value;
$('#submit').click(function(){ 
$.ajax({ 
    crossDomain : true,
     type: "GET",
     dataType: "json",
    url: "http://localhost:8088/JirasTrackingApp/reporter/Reportees?empid="+empid,

     success: function(result){        
        console.log(result);
        document.write(empid.value);
     }
 });
});

Это мой сервис:

@Path("/Reportees")
public class ReporteesService {
    ReporteeList   reportee = new ReporteeList();

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Map<Object, Object> getList(String empid) throws Exception {
        System.out.println("id is"+empid);  //when I try to print the empid,it  displays nothing
        Map<Object, Object> map=reportee.getReportees(empid);  
        return map;             
    }
});

Это мой getReportees () в классе ReporteeList

public class ReporteeList {

    public Map<Object, Object> getReportees(String idOfEmp) throws Exception {
        System.out.println(idOfEmp);
        String msg = "error";
        String api = "https://connect.ucern.com/api/core/v3/people/";
        String id = idOfEmp;
        String ext = "/@reports";
        String url = api + id + ext;
        String name = "*********";
        String password = "*********";
        String authString = name + ":" + password;
        String authStringEnc = new BASE64Encoder().encode(authString.getBytes());
        System.out.println("Base64 encoded auth string: " + authStringEnc);
        Client restClient = Client.create();
        WebResource webResource = restClient.resource(url);
        ClientResponse resp = webResource.accept("application/json")
                                         .header("Authorization", "Basic " + authStringEnc)
                                         .get(ClientResponse.class);
        if (resp.getStatus() != 200) {
            System.err.println("Unable to connect to the server");
        }
        String output = resp.getEntity(String.class);

        // JSONParser reads the data from string object and break each data into key
        // value pairs
        JSONParser parse = new JSONParser();
        // Type caste the parsed json data in json object
        JSONObject jobj = (JSONObject) parse.parse(output);
        // Store the JSON object in JSON array as objects (For level 1 array element i.e list)

        JSONArray jsonarr_s = (JSONArray) jobj.get("list");
        Map<Object, Object> map = new HashMap<Object, Object>(); //error in this line 

        if (jsonarr_s.size() > 0) {

            // Get data for List array
            for (int i = 0; i < jsonarr_s.size(); i++) {
                JSONObject jsonobj_1 = (JSONObject) jsonarr_s.get(i);
                JSONObject jive = (JSONObject) jsonobj_1.get("jive");
                Object names = jsonobj_1.get("displayName");
                Object userid = jive.get("username");
                map.put(names, userid);                  
            }

            return map;
        } else {
            map.put("errorcheck", msg);
        }
        return map;
    }
}

Значение empid из вызова ajax не принимается службой. И, пожалуйста, скажите мне, как перехватить параметры из URL и передать их остальным службам.

1 Ответ

0 голосов
/ 23 января 2019

Вы также должны будете указать аннотацию @QueryParam для вашего getList метода:

@GET
@Produces(MediaType.APPLICATION_JSON)
public Map<Object, Object> getList(@QueryParam("empId") String empid) throws Exception {
    System.out.println("id is"+empid);  //when I try to print the empid,it  displays nothing
    Map<Object, Object> map=reportee.getReportees(empid);  
    return map;             
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...