如何从同一个控制器同时发送变量和接收模型?

时间:2016-11-01 20:21:04

标签: java spring spring-mvc spring-boot thymeleaf

在Spring boot中谁接收帖子模型并同时发送vars到thymeleaf模板?

@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方法中接收模型,如何设置模型将vars发送到模板?,如果发送两个参数不起作用:

@PostMapping("/")
public String receive(Model model, @ModelAttribute ModelForm form_model){

model_form为空。

模板:

<!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>

1 个答案:

答案 0 :(得分:1)

您可以使用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";
    }