将 JSP 转换为 Thymleaf:属性名称不能为 Null 或 Empty

Posted

技术标签:

【中文标题】将 JSP 转换为 Thymleaf:属性名称不能为 Null 或 Empty【英文标题】:Converting JSP to Thymleaf: Attribute Name cannot be Null or Empty 【发布时间】:2020-01-11 05:55:13 【问题描述】:

我目前正在使用Thymeleaf 将许多.jsp 页面转换为html。我已经成功转换了其中的一些,但是在检查任何带有表单标签的页面时,我收到以下错误:

Attribute name cannot be null or empty during the initial page load.

我一直在关注以下指南:https://spring.io/guides/gs/handling-form-submission/

查看代码

    <!-- Registration Form -->
            <form action="#" th:action="@/register/processRegistrationForm" th:object="$user" method="POST" class="form-horizontal">

    <!-- User name -->
                    <div style="margin-bottom: 25px" class="input-group">
                        <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span> 
                        <input type="text" th:field:="*userName" placeholder="Username (*)" class="form-control" />
                    </div>

                    <!-- Password -->
                    <div style="margin-bottom: 25px" class="input-group">
                        <span class="input-group-addon"><i class="glyphicon glyphicon-lock"></i></span> 
                        <input type="text" th:field:="*password" placeholder="First Name (*)" class="form-control" />
                    </div>

控制器代码

@GetMapping("/showRegistrationForm")
public String showMyRegistrationPage(
        Model theModel) 

    theModel.addAttribute("user", new UserRegistrationDto());

    return "Login/registration-form";


@PostMapping("/processRegistrationForm")
public String processRegistrationForm(
            @Valid @ModelAttribute ("user") UserRegistrationDto userDto, 
            BindingResult theBindingResult, 
            Model theModel) 

    String userName = userDto.getUserName();
    logger.info("Processing registration form for: " + userName);

    // form validation
     if (theBindingResult.hasErrors())
         return "Login/registration-form";
        

    // check the database if user already exists
    User existing = userService.findByUserName(userName);
    if (existing != null)
        theModel.addAttribute("user", new UserRegistrationDto());
        theModel.addAttribute("registrationError", "User name already exists.");

        logger.warning("User name already exists.");
        return "Login/registration-form";
    
 // create user account                             
    userService.save(userDto);

    logger.info("Successfully created user: " + userName);

    return "redirect:/loginPage?rSuccess";      

DTO 代码

public class UserRegistrationDto 

    @NotNull(message = "is required")
    @Size(min = 1, message = "is required")
    private String userName;

    @NotNull(message = "is required")
    @Size(min = 1, message = "is required")
    private String password;

实体代码

@Entity
@Table(name = "user")
public class User 

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;

@Column(name = "username")
private String userName;

@Column(name = "password")
private String password;

@Column(name = "first_name")
private String firstName;

@Column(name = "last_name")
private String lastName;

@Column(name = "email")
private String email;

@ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinTable(name = "users_roles", 
joinColumns = @JoinColumn(name = "user_id"), 
inverseJoinColumns = @JoinColumn(name = "role_id"))
private Collection<Role> roles;

public User() 


public User(String userName, String password, String firstName, String lastName, String email) 
    this.userName = userName;
    this.password = password;
    this.firstName = firstName;
    this.lastName = lastName;
    this.email = email;


public User(String userName, String password, String firstName, String lastName, String email,
        Collection<Role> roles) 
    this.userName = userName;
    this.password = password;
    this.firstName = firstName;
    this.lastName = lastName;
    this.email = email;
    this.roles = roles;


public Long getId() 
    return id;


public void setId(Long id) 
    this.id = id;


public String getUserName() 
    return userName;


public void setUserName(String userName) 
    this.userName = userName;


public String getPassword() 
    return password;


public void setPassword(String password) 
    this.password = password;

堆栈跟踪指向方法周围的问题:

@GetMapping("/showRegistrationForm")
public String showMyRegistrationPage(

& 用

读取
An error happened during template parsing (template: "class path resource [templates/Login/registration-form.html]")
Caused by: java.lang.IllegalArgumentException: Attribute name cannot be null or empty

只有在使用 th:field:=""* 时才会出现这种情况,并且在以 .jsp 离开页面时效果很好。

我看不出代码有问题。 有人知道是什么原因造成的吗?

我已经尝试从DTO 中删除验证,因为它是由它引起的,但错误消息没有改变。

【问题讨论】:

你可以试试th:field=(删除colon,即:=之前)?还有一个建议,将existing 变量而不是new UserRegistrationDto() 放入theModel.addAttribute("user", new UserRegistrationDto()); 行中 嗨乔希尔!这是第二个:不敢相信我错过了!非常感谢:) 【参考方案1】:

我认为问题在于这两行:

<input type="text" th:field:="*userName" placeholder="Username (*)" class="form-control" />

<input type="text" th:field:="*password" placeholder="First Name (*)" class="form-control" />

由于您在th:field 之后添加了“:”列,因此可能会出现错误。所以这两行应该是这样的:

<input type="text" th:field="*userName" placeholder="Username (*)" class="form-control" />

<input type="text" th:field="*password" placeholder="First Name (*)" class="form-control" />

由于 thymeleaf 没有很好地解释问题或有问题的行号,所以找到问题真的很头疼。它只是说“属性名称不能为空或空”,而您只是在搜索空属性。

【讨论】:

【参考方案2】:

我遇到了同样的问题,我只是将错误 1 ​​减 1。所以我对每个输入和每个表单都进行了评论。而问题就在这里

<form action="#" th:action="@/register/processRegistrationForm" th:object="$user" method="POST" class="form-horizontal">

th:object="$user",也许这个技巧可以帮助你一点,因为这个问题还没有解决。

【讨论】:

以上是关于将 JSP 转换为 Thymleaf:属性名称不能为 Null 或 Empty的主要内容,如果未能解决你的问题,请参考以下文章

springboot整合thymleaf模板引擎

Thymleaf js直接获取后台传过来的对象或者对象的属性

为啥将 numpy 数组转换为 csv 文件不显示属性名称,而是将第一行值作为属性名称?

使用对象解构赋值时,为啥将属性“名称”转换为字符串? [复制]

C# - 如何将复杂的 json 转换为 XML,并将名称和值属性转换为标签

未定义的属性名称(sec:authentication)