Java 如何从同一控制器同时发送VAR和接收模型?
在Spring boot中,谁接收post模型并同时向thymeleaf模板发送VARJava 如何从同一控制器同时发送VAR和接收模型?,java,spring,spring-mvc,spring-boot,thymeleaf,Java,Spring,Spring Mvc,Spring Boot,Thymeleaf,在Spring boot中,谁接收post模型并同时向thymeleaf模板发送VAR @Controller public class ProfilingController { @GetMapping("/") public String main(Model model){ FormModel form_model = new FormModel(); model.addAttribute("form_model", form_model
@Controller
public class ProfilingController {
@GetMapping("/")
public String main(Model model){
FormModel form_model = new FormModel();
model.addAttribute("form_model", form_model);
model.addAttribute("demo", "abc");
return "main_template";
}
@PostMapping("/")
public String receive(@ModelAttribute ModelForm form_model){
FormModel form_model = new FormModel();
// How to set model to send the var to thymeleaf template?
model.addAttribute("form_model", form_model);
model.addAttribute("demo", "abc");
return "main_template";
}
}
如果在post方法中接收模型,如何将模型设置为将变量发送到模板?如果发送两个参数不起作用:
@PostMapping("/")
public String receive(Model model, @ModelAttribute ModelForm form_model){
模型表单为空
模板:
<!DOCTYPE html>
<html>
<head>
<title>Demo</title>
</head>
<body>
<form class="form-signin" action="#" method="post" th:action="@{/}" th:object="${form_model}">
<input th:field="*{email}" required="required" type="email" />
<input th:field="*{password}" type="password" />
<p th:text="${demo}"></p>
<button type="submit">Submit</button>
</form>
</body>
</html>
演示
提交
您可以使用ModelMap
执行此操作,如下所示:
我对新建的form_model
对象创建进行了评论,假设您需要保留接收到的数据以发送回用户
@PostMapping("/")
public String receive(@ModelAttribute ModelForm form_model, ModelMap modelMap){
//other code to call service layer & save the data
//Commented new object creation for FormModel
//FormModel form_model = new FormModel();
modelMap.addAttribute("form_model", form_model);
modelMap.addAttribute("demo", "abc");
return "main_template";
}
在post-mapping-method参数中,尝试再添加一个变量
ModelMap-model
,向model
对象添加所需的属性。model对象工作正常,但form\u-model是空的:(能否为FormModel
提供基本代码?是否有getter/setter?同样,您正在创建一个空对象(我假设,因为使用默认构造函数FormMode()
)是正确的。。