gpt4 book ai didi

java - 如何通过表单方法 GET 将填写的表单字段作为查询参数专门发送?

转载 作者:行者123 更新时间:2023-12-01 18:46:40 26 4
gpt4 key购买 nike

我正在使用 Java 11、SpringBoot 和 Thymeleaf。

我有这个表格:

<form th:action="@{/accommodations/search}" th:object="${filter}" method="get">
<div class="form-row">
<div class="form-group col-lg-6">
<label for="checkin">Checkin</label>
<input class="form-control" th:field="*{checkin}" type="date" id="checkin">
</div>

<div class="form-group col-lg-6">
<label for="checkout">Checkout</label>
<input class="form-control" th:field="*{checkout}" type="date" id="checkout">
</div>
</div>
<div class="form-group">
<label for="type">Type:</label>
<select class="form-control" th:field="*{type}" id="type">
<option th:each="type : ${accommodationTypes}"
th:value="${type}"
th:text="${type.type}"></option>
</select>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="pricePerNight">Price Per Night:</label>
<input class="form-control" th:field="*{pricePerNight}" type="number" id="pricePerNight">
</div>
<div class="form-group col-md-6">
<label for="guests">Guests:</label>
<input class="form-control" th:field="*{guests}" type="number" id="guests">
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="country">Country:</label>
<input class="form-control" th:field="*{country}" type="text" id="country">
</div>
<div class="form-group col-md-6">
<label for="city">City:</label>
<input class="form-control" th:field="*{city}" type="text" id="city">
</div>
</div>
<button type="submit" class="btn btn-success">Search</button>
</form>

我想将插入字段中的值作为查询参数发送到此 Controller 端点:

@GetMapping("/accommodations/search")
public String accommodationSearch(@Valid AccommodationPaging accommodationPaging,
@ModelAttribute("filter") AccommodationFilter filter,
Model model) {
Page<AccommodationDto> accommodations = this.accommodationService.searchAccommodations(accommodationPaging, filter);
model.addAttribute("accommodations", accommodations);
model.addAttribute("accommodationTypes", AccommodationType.values());
return ACCOMMODATIONS_VIEW;
}

只有当我填写所有表单字段时,这才有效。如果我没有填写所有字段,假设我仅填写“国家/地区”和“城市”字段,则请求将发送至此:

/accommodations/search?checkin=&checkout=&type=WHOLE_APARTMENT&pricePerNight=&guests=&country=意大利&city=罗马

正如您所看到的,所有其他字段都是空的,但是空的查询参数仍在发送,而不是根本不发送。我该如何解决这个问题,以便在这种情况下将请求发送到此:

/accommodations/search?type=WHOLE_APARTMENT&country=意大利&city=罗马

最佳答案

找到了一个解决方案,在提交时将所有空输入设置为“禁用”就足够了。请参阅以下脚本:

<script th:inline="javascript">
jQuery(document).ready(function($){
$("#filterModal").submit(function() {
$(this)
.find(":input")
.filter(function(){ return !this.value; })
.attr("disabled", "disabled");
return true;
});
$("#filterModal")
.find( ":input" )
.prop( "disabled", false );
});</script>

其中“filterModal”应替换为表单的 id。

关于java - 如何通过表单方法 GET 将填写的表单字段作为查询参数专门发送?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59822352/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com