如何从我的休息服务发送 json 对象,以便我可以在客户端 javascript 解析输入

发布于 2024-11-15 20:02:32 字数 1298 浏览 0 评论 0原文

我只是想从服务器返回一个 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>

I just simply want to return a JSON object (using ajax) from my server to the client side - so I'm able to read the data in the client side

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

This would be in the client side for JSP I want to extract the data out on the page

<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>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

愚人国度 2024-11-22 20:02:32

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

The Jackson library should take care of marshalling json objects to your objects, and vice versa. Just create a simple POJO, like this:

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

Then return this object from your RESTful webservice:

@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");
}
左秋 2024-11-22 20:02:32
  @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>
  @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>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文