我在将 thymleaf 形式的值映射到 Spring Controller 中的路径变量时遇到问题。
索引文件中的表单:
<!--/*@thymesVar id="fiatCurrency" type="java.lang.String"*/-->
<form
th:action="@{'/values/' + ${fiatCurrency}}" method="post" >
<select name="fiatCurrency" onchange="this.form.submit()">
<option th:value="USD" th:text="USD"> </option>
<option th:value="EUR" th:text="EUR"> </option>
<option th:value="CNY" th:text="CNY"> </option>
</select>
</form>
Controller 看起来像这样:
@Controller
public class DataController {
private ApiService apiService;
public DataController(ApiService apiService) {
this.apiService = apiService;
}
@GetMapping(value = {"/values","/values/","", "/", "/index","/cryptos"} )
public String index(Model model){
model.addAttribute("cryptos",apiService.getCrypto(100));
return "index";
}
@PostMapping(value = "/values/{fiatCurrency}")
public String choseCurrency(Model model,@PathVariable String fiatCurrency){
model.addAttribute("cryptos",apiService.getInDifferentValues(fiatCurrency));
return "index";
}
}
我的问题是它总是返回空值,并且我正在努力如何在 PathVariable
fiatCurrency
内绑定(bind)值 CNY, < strong>EUR 或 USD 形成 index.html
形式。
最佳答案
问题是,您试图在页面渲染后动态更改表单操作属性。至少不能按照您尝试的方式使用 Thymeleaf 来完成此操作。请记住,Thymeleaf 在服务器端工作。因此,您有两种选择来完成此任务。
- 不要使用路径变量,而是使用参数。
- 使用 js 动态更改表单的操作。
最简单的当然是第一个选项。因此,您需要更改 Controller 中的后映射并更改参数的路径变量。
更改以下 Controller 方法。
@PostMapping(value = "/values/fiatCurrency")
public String choseCurrency(Model model,
@RequestParam("fiatCurrency") String fiatCurrency) {
model.addAttribute("cryptos", apiService.getInDifferentValues(fiatCurrency));
return "index";
}
你的 html 最终看起来像这样。
<form id="fiatForm" th:action="@{/values/fiatCurrency}" method="post">
<select id="fiatSelect" name="fiatCurrency">
<option th:value="USD" th:text="USD"> </option>
<option th:value="EUR" th:text="EUR"> </option>
<option th:value="CNY" th:text="CNY"> </option>
</select>
</form>
如果您不想添加按钮来提交表单,那么添加此 jQuery
函数即可解决问题。
$("#fiatSelect").on("change", function() {
$("#fiatForm").submit();
})
我已经尝试过这段代码并且它已经可以工作了。希望对您有所帮助。
关于java - 获取 PathVariable 中的空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52904717/