使用javascript调用javawebservice

call a java webservice using javascript

本文关键字:javawebservice 调用 javascript 使用      更新时间:2023-09-26

我使用netbeans中的模式创建了一个javaRestfull Web服务,并在一台机器上运行该项目。如何在javascript 中从另一台机器调用此web服务

Web服务类是

package com.gdb.webapi;

import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.Produces;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import static javax.ws.rs.HttpMethod.POST;
import javax.ws.rs.OPTIONS;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PUT;
import javax.ws.rs.core.MediaType;

/**
 * REST Web Service
 *
 * @author suhail
 */
@Path("displaylist")
public class DisplaylistResource {
    @Context
    private UriInfo context;
    /**
     * Creates a new instance of DisplaylistResource
     */
    public DisplaylistResource() {
    }
    /**
     * Retrieves representation of an instance of
     * com.gdb.appconstant.DisplaylistResource
     *
     * @return an instance of java.lang.String
     */
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public String getJson() {
        //TODO return proper representation object
        throw new UnsupportedOperationException();
    }
    /**
     * PUT method for updating or creating an instance of DisplaylistResource
     *
     * @param content representation for the resource
     */
    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public String putJson(String content) throws ParseException {
        System.out.println(content);
        return "true";
    }

}

我想使用ajax 调用post方法

创建服务调用的路径。http://YOURIP/项目名称/操作名称。

例如

 function fun() 
{
   var data="hello";
   $.get("http://localhost/projectNAME/HelloWorld", function(response) {
        data = response;
   }).error(function(){
  alert("Sorry could not proceed");
});
   return data;
}

并为方法放置@path注释,这将决定要调用哪个方法。

我会使用fetchpolyfill->https://github.com/github/fetch.查看自述文件,了解如何将数据发布到REST服务:

fetch('/users', {
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    name: 'Hubot',
    login: 'hubot',
  })
})