当我从下拉列表中选择一个选项时,我遇到了问题,我得到了所需的信息,但我单击的选项并未保持选中状态。 有什么想法吗?
<form th:action="@{/values/fiatCurrency} "method="post">
<select name="fiatCurrency" onchange="this.form.submit()">
<option id="USD" onclick="document.getElementById(this).selected = true" value="USD" th:text="USD"> </option>
<option id="EUR" onclick="document.getElementById(this).selected = true" value="EUR" th:text="EUR"> </option>
<option id="CNY" onclick="alert( 'a ') " 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,
@RequestBody String fiatCurrency) {
String replace=fiatCurrency.replace("fiatCurrency=","");
model.addAttribute("cryptos", apiService.getInDifferentValues(fiatCurrency));
return "index";
}}
它始终返回美元值(value)。
最佳答案
您将法定货币作为请求参数而不是请求正文发送。 Spring 有一个强大的机制可以将 View 表单映射到实际对象。该对象将作为 @ModelAttribute
发送,并在加载 View 之前添加到模型中。
您的表格将是:
<form th:action="@{/values/fiatCurrency}" th:object="${fiat}" method="post">
<select th:field="*{fiatCurrency}" onchange="this.form.submit()">
<option id="USD" th:value="USD" th:text="USD"></option>
<option id="EUR" th:value="EUR" th:text="EUR"></option>
<option id="CNY" th:value="CNY" th:text="CNY"></option>
</select>
</form>
下一步是创建一个 Fiat 类来包装您所需的数据:
public class Fiat {
private String fiatCurrency;
//getters and setters
}
在提供 View 之前,必须将法定对象添加到模型中。一个简单而优雅的解决方案是在 Controller 中定义一个新方法:
@ModelAttribute
public void addModelAttribute(Map<String, Object> model) {
model.put("fiat", new Fiat());
}
您的 post 方法将接收新创建的对象:
@PostMapping(value = "/values/fiatCurrency")
public String choseCurrency(Model model,
@ModelAttribute Fiat fiat) {
//..
return "index";
}
关于java - 如何在 Thymeleaf 和 Spring 中设置选定的选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52907576/