使用Spring Boot在同一页面上重复提交表单

Recurrent form submission on the same page using Spring Boot

本文关键字:提交 表单 一页 Spring Boot 使用      更新时间:2023-09-26

我有一个包含两个部分的页面:第一部分是表单,第二部分显示提交时表单的响应。该表单接受来自附加的网络摄像头的图像。因此,我必须使用Webcam js包装器:https://github.com/jhuckaby/webcamjs表单提交需要是一个重复的过程,这意味着,一旦提交了表单,第二部分将显示表单结果,并且需要使用相同的页面再次提交表单。我使用Spring Boot/Thymeleaf来完成这个。我的部分代码如下:

form.html

<form name="mainform"   action="">
   <input  type="text" name="sbid[]" id="sbid">
   <td><input type="submit" value="Compare"  onclick="submit_snapshot()"/></td>
</form>
<div id="resdiv">
   <div><img src="images/imgnew.jpg" alt="" width="100%" height="220" /></div>
   <p> This is part of the second div</p>
</div>
<script>
   function submit_snapshot() {
   url=url+'sbid[]='+batchId[i].value;
   //alert(url);
   var batchId=document.getElementsByName('sbid[]');
   var url='/imagecompare-0.1.0/compare?';
   for(var i=0; i<batchId.length-1; i++){
   url=url+'sbid[]='+batchId[i].value+'&';
   }
   Webcam.upload( webcamuri, url, function(code, text) {
   document.write(text);
   } );
   }
</script>

控制器代码如下:

@CrossOrigin
@RequestMapping(method = RequestMethod.POST, value = "/compare")
public String handleCompare(@RequestParam("sbid[]") String sbid[],
    @RequestParam("webcam[]") MultipartFile webcamFiles[],
    RedirectAttributes redirectAttributes, Model model) throws IOException {
    return "formresults";
}

formresults页面几乎与form.html相同,只是第二个名为resdiv的div具有不同的数据:

<div id="resdiv">
    <div><img src="images/imgnew.jpg" alt="" width="100%" height="220" /></div>
    <p> This is part of the result div</p>
</div>

然而,这种设计似乎不起作用。从form.html提交的表单正确地重定向到formresults并显示数据。但是,如果我从表单结果页面执行后续表单请求,则不会显示正确的表单响应。相反,它会自动重定向回form.html。有没有人能帮忙指出为什么会发生这种行为?

终于解决了这个问题。这里的问题是下面的语句:

<form name="mainform"   action="">

由于表单是由XHR单独提交的,因此这个空白的action标记强制页面返回到先前的页面。我尝试删除form标签,现在它正在工作。