【问题标题】:How thymleaf submits variable from a form to controller to be attached to Urlthymeleaf 如何将变量从表单提交到控制器以附加到 Url
【发布时间】:2021-03-08 06:53:28
【问题描述】:

我在 thymleaf 的表单中有一个变量,该变量是一个日期,必须嵌入到控制器中的方法中,该方法将显示特定日期的数据。我的问题是选择变量并提交时,我在URL中获得了一个奇怪的链接 localhost:8080/masomo/somo/?date=11-03-2021&date=date 没有对该特定页面的任何响应。我在提交变量时做错了什么。

这是 masomo.html 中 thymleaf 中的表格

           <form th:action="@{/masomo/somo/}">
                <select id="date" name="date" required="true">
                <option value="none" selected disabled hidden > 
                    Select a Date 
                </option> 
               
                <th:block th:each="somoChagua : ${masomoChagua}">
                 <option th:each="date : ${somoChagua.date}"  th:value="${date}" th:text="${date}" ></option>
                </th:block>
                </select>

                <button type="submit" th:name="date" th:value="date" ><i class="fa fa-search"></i> </button> 
               
            </form> 

这是我在控制器中设置方法以接收变量的方式

  @Autowired
  private MisaleRepository misaleRepository;

  @RequestMapping(value = "/masomo/somo/{date}", method=RequestMethod.GET  )
  public String chaguaSomo(@RequestParam(value = "date", required = true) String date, Model model  ){

    List<Misale> masomo = misaleRepository.getSomoBytarehe(date);
    model.addAttribute("masomoYote", masomo);

    return "masomo";

}

这是我的仓库

 public interface MisaleRepository extends JpaRepository <Misale, String> {

     @Query(value ="SELECT * FROM misale WHERE misale.date = ?1 " , nativeQuery = true)
    public List<Misale> getSomoBytarehe(String date);


}

【问题讨论】:

    标签: java spring spring-boot spring-mvc thymeleaf


    【解决方案1】:

    删除提交按钮行中的th:nameth:value

     <button type="submit" ><i class="fa fa-search"></i> </button> 
    

    日期值作为请求参数从视图传递到控制器,但控制器将其作为路径变量接收。

      @RequestMapping(value = "/masomo/somo/", method=RequestMethod.GET  )
      public String chaguaSomo(@RequestParam(value = "date", required = true) String date, Model model  )
    

    【讨论】:

      【解决方案2】:

      我必须像下面这样更改我的表单

          <form th:action="@{'/masomo/somo/' + ${date}}">
      

      我把按钮改成

           <button type="submit"><i class="fa fa-search"></i> </button> 
      

      我也将控制器中的方法更改为

           @GetMapping("/masomo/somo/{date}")
           public String chaguaSomo(@RequestParam(value = "date",required = true) String date, Model model ){......}
           
      

      经过上述更改后,我现在可以将数据从块 th:each 中的表单传递到控制器

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-10-11
        • 2014-01-22
        • 2021-10-01
        • 1970-01-01
        • 2021-10-08
        相关资源
        最近更新 更多