簡體   English   中英

使用Spring MVC進行Thymeleaf表單驗證

[英]Thymeleaf form validation with spring MVC

這個問題已經問過幾次了,但是所有人都沒有回答我的問題。 我一直在嘗試獲得與Thymeleaf一起使用的不同功能兩天了,但還是很失敗。 我只能使它與spring-boot一起使用,但是現在我正在使用spring-MVC。

首先,我將向您展示我的依賴性

1個

<%@ taglib prefix="sf" uri="http://www.springframework.org/tags/form" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html xmlns:th="http://www.thymeleaf.org" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Create a New Account</title>
    <link th:href="@{/resources/css/loginForm.css}" href="/resources/css/loginForm.css" rel="stylesheet"
          type="text/css"/>
</head>
<body>

<form action="#" th:action="@{/createNewAccount}" th:object="${user}" method="post">
    <table>
        <tr>
            <td>Name:</td>
            <td><input type="text" th:field="*{username}" /></td>
            <td th:if="${#fields.hasErrors('name')}" th:errors="*{username}">Name Error</td>
        </tr>
        <tr>
            <td>Password:</td>
            <td><input type="text" th:field="*{password}" /></td>
            <td th:if="${#fields.hasErrors('age')}" th:errors="*{password}">Password Error</td>
        </tr>
        <tr>
            <td><button type="submit">Submit</button></td>
        </tr>
    </table>
</form>

</body>
</html>

現在,您可以看到我的IntelliJ IDE顯示的錯誤:

2

User.java

package com.practice.domain;

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

/**
 * Created by DrewJocham on 8/30/15.
 */

public class User {

    @NotNull
    @Size(min = 2, max = 30)
    private String username;
    @NotNull
    private String password;

    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;
    }

    @Override
    public String toString() {
        return "User{" +
                "username='" + username + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}

您調用的hasErrors字段名稱必須與對象中的字段名稱匹配。 像這樣:

<td th:if="${#fields.hasErrors('username')}" th:errors="*{username}">Name Error</td>

請注意, hasErrors('name')成為hasErrors('username') ,並且:

<td th:if="${#fields.hasErrors('password')}" th:errors="*{password}">Password Error</td>

請注意, hasErrors('age')變為hasErrors('password')

至於在Intellij中突出顯示的錯誤,我認為它們具有誤導性,並且與以下未解決的問題有關: https ://youtrack.jetbrains.com/issue/IDEA-132738

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM