【问题标题】:How to pass model value in thymeleaf input text如何在百里香输入文本中传递模型值
【发布时间】:2019-11-24 08:24:57
【问题描述】:

我在 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";

}

如何从我在 thymeleaf 模板中传入模型的 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";

}

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

【问题讨论】:

    标签: spring-boot thymeleaf


    【解决方案1】:

    "value" 更改为"th:field"

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

    【讨论】:

    • 这会引发异常:org.thymeleaf.exceptions.TemplateProcessingException:处理器执行期间出错 'org.thymeleaf.spring5.processor.SpringInputGeneralFieldTagProcessor
    • 你好@YeetCoder 哪一个给出了这个错误?你都试过了吗
    • th:field 不起作用,但如果我将其更改为 th:value,它会起作用,但会引发 null 异常。事情是我第一次访问该页面时,没有模型对象,用户注册后发生异常,然后将模型对象发回。如果 accountInfo 不为空,是否有某种方法只能访问 firstName?
    • 你好@YeetCoder,能不能分享下你的相关代码,对你有帮助
    • @YeetCoder 在执行处理程序中将return "redirect:/signup"; 更改为return "redirect:/signup_do";,这里是最后一课
    猜你喜欢
    • 2017-04-17
    • 1970-01-01
    • 1970-01-01
    • 2018-07-02
    • 2021-02-26
    • 1970-01-01
    • 2019-10-27
    • 2017-02-27
    • 1970-01-01
    相关资源
    最近更新 更多