簡體   English   中英

如何從我的休息服務發送一個json對象,以便我可以在客戶端javascript解析

[英]How do I send a json object from my rest service so I can parse in out on the client side javascript

我只是想從我的服務器向客戶端返回一個JSON對象(使用ajax) - 所以我能夠在客戶端讀取數據

  @GET
  @Produces("application/json")
  @Consumes("application/json") 
  @Path("/getStatus/")

  public void getStatus(
      @Context HttpServletRequest request,
      @Context HttpServletResponse response) throws ServletException,
      IOException
  {

      //create the JSON Object to pass to the client
      JSONObject object=new JSONObject();

      response.setContentType("text/javascript");    

      try
      {  
            object.put("name", nameDataFromClass);
            object.put("status",someData);

       }
       catch(Exception e)
       {  
            throw new ServletException("JSON Hosed up");  
       }  

       String json = object.toString();  
       response.getOutputStream().println(json);   
  }

這將是JSP的客戶端我希望在頁面上提取數據

<html>
<head>

<!-- Calls in jQuery file -->
<script src="jquery.js"></script>

<title>JQuery Test</title>

<script>

    $.getJSON("http://localhost:8080/scout/rest/admin/mamba/getStatus",
    function(json) 
    {  
        alert("Server naame: " + json.name);  
    });  



</script>

</head>
<body>



</body>
</html>

Jackson庫應該負責將json對象編組到您的對象,反之亦然。 只需創建一個簡單的POJO,如下所示:

public class Mystatus{
   public String name;
   public String status;
   public Mystatus(){}  // a default empty constructor is needed
   public Mystatus(String name,String status){
     this.name=name;
     this.status=status;
   }
}

然后從RESTful Web服務返回此對象:

@GET
@Produces("application/json")
@Consumes("application/json") 
@Path("/getStatus/")

public Mystatus getStatus(
  @Context HttpServletRequest request,
  @Context HttpServletResponse response)
{
  response.setContentType("text/javascript");
  return new Mystatus("Hello","World");
}
  @GET
  @Produces("application/json")
  @Consumes("application/json")
  @Path("/status")
  // server:8080/server/rest/status
  public String getStatus(
      @Context HttpServletRequest request,
      @Context HttpServletResponse response) throws Exception
  {

    // Create a string to hold JSON
    String json;

      Collection<Server> svr = SomeHashMap.getStuff().values();

      JSONArray jArray = new JSONArray();

      for (Server i : svr)
      {
        JSONObject m = new JSONObject();

        ServerStatus status = i.getStatus();

        m.put("id", i.getId());
        m.put("name", i.getName());
        m.put("status", status.getState());

        jArray.add(m);
      }

      json = jArray.toString();
    }

    response.setContentType("text/javascript");
    response.getOutputStream().print(json);
    response.flushBuffer();

    return null;
}

的index.jsp

<head>
<script src="jquery-1.6.js"></script>
     <!--AJAX FOR STATUS PAGE REFRESH -->
     <script type="text/javascript">

    //when page is ready do the following
    $(document).ready(function()
    {
        // Disable caching of AJAX responses
        $.ajaxSetup ({cache: false});

        //set interval of refresh
        setInterval(doAjaxStuff, 1000);

        //function to call to fire off ajax
        function doAjaxStuff()
        {
            $.ajax
            ({
                url: "status", // <-- this refers to the Controller function above called "status()"
                dataType: 'json',
                success: function(json) 
                {
                    //traverse throught each element in the incoming JSON object
                    for(var i = 0; i< json.length; i++)
                    {
                        if(json[i].status ==  "ACTIVE")
                        {
                            $("#Status"+json[i].id).html("Running");
                        }


                    }               
                }
            });
        }
    });
    </script>

</head>

暫無
暫無

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

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