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



我正在制作一个智能应用程序,它可以记录用户家中电器的能源支出。如果电器在某个时间间隔之外打开,它也可以关闭电器,例如用户希望他的电脑在晚上关闭。

我有以下问题,用户必须输入他想要注册的设备数量,然后会生成该数量的文本字段,这样他就可以输入这些设备的时间间隔。我已经使用一些javascript将这些输入保存在一个数组中,但如何通过post请求发送这些输入呢?我以为我必须使用@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);
  }

我想要的是在那里接收数组,但在打印它时,它只打印"null"。然而,当我在numberOfAppliances上尝试同样的东西时,它会很好地接收到它,并打印出来。起初我认为这是因为按下提交按钮后,可能会创建数组。因此,它会发布空数组变量,然后生成数组。所以我做了一个额外的保存按钮来检查这个,但这并没有解决我的问题。

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

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

记住<input>元素的name属性值,这将是for参数的关键。因此,请求主体将看起来像

array=hello&array=world&array=blah

这就是为什么我们在这里使用List,因为有多个关键字为array的参数。

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

最新更新