JAX RS Jersey Rest Webservice发布由用户输入生成的数组

时间:2015-03-21 13:31:14

标签: rest post jersey jax-rs

我正在制作一款智能应用程序,用于记录用户家中家电的能源消耗。如果设备在某个时间间隔之外,它也可以关闭设备,例如用户希望他的计算机在晚上关闭。

我有以下问题,用户必须输入他想要注册的设备数量,然后会生成该数量的文本字段,这样他就可以输入这些设备的时间间隔。我已经使用一些javascript将这个输入保存在数组中了,但是如何通过发布请求发送它?我认为我必须使用@FormParam,就像发布用户名和密码一样,但这对我来说似乎不起作用。这就是applianceInfo.html的样子:

<html>
<body>
<h2>Hello World!</h2>

<form action="/Smart_Webapp/rest/hello/applianceInfo"
    method="POST" oninput="array.value=getArray(numberOfAppliances.value)">
    <p>
        <input type="text" name="numberOfAppliances" id="numberOfAppliances" />
        <input type="button" name="button" id="button" value="Create" onclick="createTextFields(numberOfAppliances.value);" />
        <input type="button" name="saveButton" id="saveButton" value="Save" onclick="getArray(numberOfAppliances.value);" />
        <div id="textFields"></div>
        <output name="array" for="numberOfAppliances"></output>
    </p>    
    <input type="submit" value="Submit" />
    <p id="array"></p>
</form>

<script>
function createTextFields(nums){
    var input = "";
    for(i=0;i<nums;i++){
        input += "<input type='text' id='name" + i + "'" + "  + '  /> "
            +"<input type='text' id='start" + i + "'" + "  + '  /> "
            +"<input type='text' id='end" + i + "'" + "  + '  /> <br/>";
    }
    document.getElementById("textFields").innerHTML = input;
}

function getArray(nums) {
    var array = [];
    for(i=0;i<nums;i++) {
        array[i] = []
        array[i].push(document.getElementById("name" + i).value);
        array[i].push(document.getElementById("start" + i).value);  
        array[i].push(document.getElementById("end" + i).value);
    }
document.getElementById("array").innerHTML = array.toString();
}
</script>
</body>
</html> 

将在服务器端调用以下函数:

  @Path("/applianceInfo")
  @POST
  @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
  public void applianceInfo(@FormParam("array") String array, @Context HttpServletResponse servletResponse) throws IOException { 
      System.out.println(array);
  }

我想要的是在那里接收的数组,但是在打印它时,它只是打印&#39; null&#39;。然而,当我尝试使用例如numberOfAppliances的相同的东西时,它很好地接收它并打印出来就好了。首先我认为这是因为可能在按下提交按钮后,将创建数组。所以它会发布空数组变量然后生成数组。所以我做了一个额外的保存按钮来检查这个,但这并没有解决我的问题。

所以我的问题是如何将此数组与用户填写的设备输入发送到服务器端?

1 个答案:

答案 0 :(得分:1)

<output>未在表单提交中发送。您应该将name属性添加到您动态创建的所有<input>元素中。

 input += "<input name='array' type='text' id='name" + i + "'" + "  + '  /> "
       + "<input name='array' type='text' id='start" + i + "'" + "  + '  /> "
       + "<input name='array' type='text' id='end" + i + "'" + "  + '  /> <br/>"; 

然后您可以在资源方法中执行此操作。

@Path("/applianceInfo")
@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response applianceInfo(@FormParam("array") List<String> array)

记住name元素的<input>属性值,它将是for参数的关键字。所以请求正文看起来像

array=hello&array=world&array=blah

这就是我们在这里使用List的原因,因为密钥array有多个参数。

如果要将每一行组合在一起,可以考虑使用不同的格式(如JSON)来发送数据。