[英]Using Map for binding in Spring - Thymeleaf
我可以使用Spring MVC将这些字段绑定到百里香中的Map上吗?
例如考虑这个例子。
假设我有一个像这样的简单命令对象
@Data
public class SampleCommand {
@Email(message = "{invalidEmail}")
private String email;
private String password;
}
我的sample.html
<form role="form" th:action="@{/sample/saveSample}" th:method="post" th:object="${sampleCommand}">
<div class="row">
<div class="form-group col-md-6">
<label class="control-label" for="emailaddress" th:text="#{email}"></label>
<input type="email" class="form-control" name="emailAddress" id="emailaddress" placeholder="Enter email" th:field="${sampleCommand.email}"/>
</div>
<div class="form-group col-md-6">
<label class="control-label" for="password">Password</label>
<input type="password" class="form-control" name="password" id="password" placeholder="Password" th:field="${sampleCommand.password}"/>
</div>
</div>
<div class="row text-center">
<div class="col-lg-12">
<button type="submit" class="btn btn-default align-center">Create User</button>
</div>
</div>
</form>
我的控制器包含:
@RequestMapping(produces = "text/html")
public String sampleFormController(Model model) {
System.out.println("Hello world");
model.addAttribute("sampleCommand", new SampleCommand());
return "/pla/sample/sample";
}
因此,每当我点击url http:// host:port / contextName / sample时 ,由于绑定,下面的方法包含来自表单的数据,当我输入字段并点击Submit按钮时 ,它将立即将我重定向到sample.html。 。
@RequestMapping(value = "/saveSample",method = RequestMethod.POST)
public String saveAgent(@Valid SampleCommand sampleCommand,
BindingResult bindingResult){
System.out.println(sampleCommand);
return "pla/sample/sample";
}
因此,这就是我尝试向您展示如何将对象绑定到Thymeleaf中的模板的方式。
我的问题是有某种方法可以使用Map代替对象(在我们的情况下为simpleObject)。
我是怎么做到的
<form role="form" th:action="@{/sample/saveSample}" th:method="post" th:object="${someMapForTest}">
//Map should define the binding to the controller.
</form>
控制器有点像这样。
@RequestMapping(produces = "text/html")
public String sampleFormController(Model model) {
System.out.println("Hello sampleUsingMap");
Map<String, Object> someMapForTest = Maps.newHashMap();
model.addAttribute("someMapForTest", someMapForTest);
return "/pla/sample/sampleUsingMap";
}
@RequestMapping(value = "/useMap",method = RequestMethod.POST)
public String saveAgent(@Valid Map<String,Object> someMapForTest){
System.out.println("inside useMap");
System.out.println(someMapForTest);
return "pla/sample/sampleUsingMap";
}
因此,有一种方法可以将百里香叶中的表单数据绑定到控制器中的映射,而无需使用命令对象。
您可以在文档中使用@RequestParam
批注
在Map或MultiValueMap参数上使用@RequestParam批注时,将使用所有请求参数填充该地图。
@RequestParam
@RequestMapping(value = "/useMap",method = RequestMethod.POST)
public String saveAgent(@RequestParam Map<String,Object> someMapForTest){
System.out.println("inside useMap");
System.out.println(someMapForTest);
return "pla/sample/sampleUsingMap";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.