如何在百里香输入文本中传递模型值

时间:2019-07-15 15:38:26

标签: spring-boot thymeleaf

我在Model对象中有数据,我想将其放入Thymeleaf模板的输入字段中,这样,如果该值为null,则不会显示任何内容,否则,输入中将包含该值。我试过了,但这不起作用。

<input id="first_name" type="text" name="firstName" placeholder="First" value=${accountInfo.firstName} maxlength=31 required>

我将值传递到java异常处理程序内的模型对象中,如下所示:

@ExceptionHandler(value=SignupFormException.class)
public String handle(HttpSession session, SignupFormException ex, Model response) {

    response.addAttribute("accountInfo", (Account) session.getAttribute("accountToRegister"));
    response.addAttribute("Error", ex.getMessage());
    session.invalidate();

    return "redirect:/signup";

}

如何从我在百里香模板中的模型中传递的accountInfo对象中获取属性?

更新: 现在它正在工作,但是没有模型对象时第一次无法访问该页面。以下是代码:

我的百里香形式:

<form action="/signup_do" th:object="${accountInfo}" method="post">
    <input id="first_name" type="text" name="firstName" placeholder="First" th:value=*{firstName} maxlength=31 required>

控制器:

@PostMapping("/signup_do")
public String register(Account account, HttpSession session) {

    session.setAttribute("accountToRegister", account);
    accountManagement.accountRegistration(account);

    return "Success";
}

有一个帐户注册服务会引发SignupFormException,该服务由以下方式处理:

@ExceptionHandler(value=SignupFormException.class)
public String handle(HttpSession session, SignupFormException ex, Model response) {

    response.addAttribute("accountInfo", (Account) session.getAttribute("accountToRegister"));
    response.addAttribute("Error", ex.getMessage());
    session.invalidate();

    return "redirect:/signup";

}

只有现在,我有一个带有百里香模板属性的模型对象...

1 个答案:

答案 0 :(得分:0)

"value"更改为"th:field"

OR

"value"更改为th:value="${accountInfo.firstName}"

<form action="#" th:action="@{/yourURL}" th:object="${accountInfo}" method="post">                      
     <input id="first_name" type="text" name="firstName" placeholder="First" th:field=*{firstName} maxlength=31 required>
     <input type="submit" class="btn btn-primary" value="Submit">
</form>
相关问题