首页 > 解决方案 > 将 JSP 转换为 Thymleaf:属性名称不能为 Null 或 Empty

问题描述

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

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它是由它引起的,但是错误消息没有改变。

标签: javaspring-bootjspthymeleaf

解决方案


I think the problem is about these two lines:

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

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

Since you put a column ":" after th:fieldit might give you an error. So those two lines should be like these:

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

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

Since thymeleaf doesn't provide a good explanation of the problem or the problematic line number, it becomes really a headache to find the problem. It's just saying "Attribute Name cannot be Null or Empty" and you're just searching empty attributes.


推荐阅读