簡體   English   中英

使用javascript調用Java Web服務

[英]call a java webservice using javascript

我使用netbeans中的模式創建了Java Restfull Web服務,並在一台計算機上運行該項目。 如何在JavaScript中從另一台計算機調用此Web服務

webservice類是

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://您的 IP /項目名稱/操作名稱。

例如

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

   return data;
}

並為方法添加@path注釋,這將決定要調用的方法。

我將使用提取 polyfill-> 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',
  })
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM