如何更改表单中的url get方法?

时间:2018-05-15 04:38:39

标签: spring spring-mvc spring-boot

我想制作一个按字母类型过滤数据的搜索功能。

形式:

<form action="/viewall/filterBy" th:object="${letter}" method="get">
    <table class="table table-bordered" style="width:100%">
        <tbody>
            <tr>
               <th>
                    <select class="form-control" id="type_form" th:field="*{id_type}" name="id_type">
                        <option disabled="disabled" selected="selected" value="0">--Select--</option>
                        <option th:each="type : ${letter_types}" th:value="${type.id}" th:text="${type.name}"></option>
                    </select>
               </th>
            </tr>
            <tr>
                <th>    
                    <button style="display: block" class="btn btn-info"> <i class="fa fa-search"></i> Search</button>
                </th>
            </tr>
        </tbody>
    </table>
</form>

控制器

@RequestMapping (value="/viewall/filterBy", method= RequestMethod.GET) public String filterBy(Model model,@ModelAttribute("letter") LetterModel letter, @RequestParam(value="id_type", required=true) Integer id_type)  {
    ....
    return "letter-view"; 
}

如果我执行,则URL在以下位置:

  

http://localhost:8080/viewall/filterBy?id_type=3

我的问题是,是否可以更改网址,因此它变为

  

http://localhost:8080/viewall/filterBy/3

提前谢谢你。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:1)

您可以使用以下网址类型:

http://localhost:8080/viewall/filterBy/3

然后您的Controller映射将如下所示:

@RequestMapping (value="/viewall/filterBy/{id_type}", method= RequestMethod.GET) 
public String filterBy(Model model, @PathVariable(name = "id_type") int idType)  {
    ....
    return "letter-view"; 
}

或更简化的方法:

@GetMapping (value="/viewall/filterBy/id_type/{id}") 
public String filterBy(Model model, @PathVariable(name = "id") int idType)  {
    ....
    return "letter-view"; 
}

<强>更新

现在,由于您的网址格式已更改,您必须通过javascript提交表单。您必须将所选值连接到您的URL,然后提交表单。要通过javascript提交表单,请参阅以下代码:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>

<body>

   <select class="form-control" id="type_form" th:field="*{id_type}" name="id_type">
     <option disabled="disabled" selected="selected" value="0">--Select--</option>
     <option th:each="type : ${letter_types}" th:value="${type.id}" th:text="${type.name}"></option>
   </select>

   <button onclick="submitForm()"> SUBMIT </button> <!--this will call the submitForm() javascript function given below -->

  <script type="text/javascript">
      function submitForm() {

          var selectedOption = document.getElementById("type_form"); // the <select> is assigned to the variable using its id

          window.location = "/viewall/filterBy/" + selectedOption.value; // here we concat the url with the selected  option and assign it to the action of the form
      }
  </script>

</body>
</html>