java - 错误:Neither BindingResult nor plain target object for bean name 'id' available as request attribute

标签 java spring spring-mvc spring-boot thymeleaf

我正在使用 thymeleaf 和 Spring 。我想实现post请求。

我的 Controller 类是

public class URLController {

    @RequestMapping(value = "index")
    public String index1(Model model){
        model.addAttribute("employee",new Employee());
        return "index";
    }

    @RequestMapping(value = "/")
    public String index(Model model){
        model.addAttribute("employee",new Employee());

        return "index";
    }

    @PostMapping("/result")
    public String result(@ModelAttribute Employee employee){
        System.out.print(employee.getName());
        return "result";
    }
}

html 页面是

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>index page</title>
</head>
<body>
<form action="#" th:action="@{/result}" modelAttribute="employee" method="post">
    <p>Id: <input type="text" th:field="*{id}" /></p>
    <p>name: <input type="text" th:field="*{name}" /></p>
    <p>phone: <input type="text" th:field="*{phone}" /></p>
    <p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
</form>


</body>
</html>

没有与 id 字段绑定(bind)。

最佳答案

在 HTML 中,您需要对模型属性使用正确的语法。 Spring 提示找不到该属性 id因为您提供字符串 employee ,而不是对象。

modelAttribute="employee" --> th:object="${employee}"

此外,您还可以合并到:

@Controller //please add this
public class URLController {

    @GetMapping({"/", "/index"})
    public String index1(Model model){
        model.addAttribute("employee",new Employee());
        return "index";
    }

    @PostMapping("/result")
    public String result(@ModelAttribute Employee employee){
        System.out.print(employee.getName()); //use a logger instead
        return "result"; //may want to return a different page name for clarity
    }
}

如果您将 HTML 标记更改为:

,您的 IDE 不会提示:

<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">

最后,您可能想使用 tel电话字段的输入类型。这样做将允许为移动用户显示自定义键盘。

关于java - 错误:Neither BindingResult nor plain target object for bean name 'id' available as request attribute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53019769/

相关文章:

java - 我的 postman 中出现此错误(POST 和 DELETE 出现此错误),希望有人可以解决此问题

java - 使用 spring aop :around, 时,如何获取切入点方法的返回类型?

java - 实现可重用的@Controller

java - Spring Web应用程序-获取表单数据-post方法

java - Matrix.setTranslate() 只平移View 的视觉表面而不平移可点击区域?

java - 用于测试中调试语句的 Logger 或 System.out.print

java - 无法在 Java.util.Calendar 中设置月份

java - 存储库相关方法仅返回空值

Spring @Autowireing 与通用工厂构建的 bean

java - Spring MVC + hibernate : BeanCreationException error after regenerating model classes