HTML Modal Validation with Spring不工作,因为它消失了

hof1towb  于 2023-10-16  发布在  Spring
关注(0)|答案(1)|浏览(95)

我已经创建了一个博客网站的登录和注册。然而,问题是,当我登录或注册时,网站重新加载。因此,我的模态消失,防止任何错误被显示。代码如下:
控制器:

@PostMapping("/login")
    public String login(Model model, String error, String logout){
        //If loggen in successfully go to /home
        if (securityService.isAuthenticated()) {
            return "redirect:/home";
        }

        //Error Messages (does not work)
        if (error != null)
            model.addAttribute("error", "Your username or password is invalid.");

        if (logout != null) {
            model.addAttribute("logoutMessage", "You have been logged out successfully.");
        }

        return "redirect:/home";
    }

    @PostMapping("/register")
    public String registration(@ModelAttribute("userForm") User userForm, BindingResult bindingResult, Model model) {
        //Validate Input
        userValidator.validate(userForm, bindingResult);

        //If Error (doesnt work)
        if (bindingResult.hasErrors()) {
            model.addAttribute("showModal", "true");
            return "index";
        }

        //Save in User Table
        userService.save(userForm);
        //Autologin after Registration
        //securityService.autoLogin(userForm.getUsername(), userForm.getPasswordConfirm());

        return "redirect:/home";
    }

我的html文件:

<!-- Login-Modal -->
<div class="modal fade" id="loginModal" tabindex="-1" role="dialog" aria-labelledby="loginModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="loginModalLabel">Anmelden</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form id="loginForm" method="post" th:action="@{/login}">
                    <div class="form-group">
                        <label for="loginUsername">Benutzername</label>
                        <input type="text" class="form-control" id="loginUsername" name="username" required>
                    </div>
                    <div class="form-group">
                        <label for="loginPassword">Passwort</label>
                        <input type="password" class="form-control" id="loginPassword" name="password" required>
                    </div>
                    <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>

                    <p class="has-error" th:text="${error}" style="color: red"></p>

                    <p th:if="${logoutMessage}" th:text="${logoutMessage}" style="color: green"></p>

                    <button type="submit" class="btn btn-primary">Login</button>
                </form>
                <!-- Link zum Registrierungs-Modal -->
                <p class="mt-3 text-center">
                    Noch kein Account?
                    <a href="#" data-toggle="modal" data-dismiss="modal" data-target="#registerModal">Jetzt registrieren!</a>
                </p>
            </div>
        </div>
    </div>
</div>

<!-- Registrierungs-Modal -->
<div class="modal fade" id="registerModal" tabindex="-1" role="dialog" aria-labelledby="registerModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="registerModalLabel">Registrieren</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form th:action="@{/register}" id="registrationForm" th:object="${userForm}" method="post">
                    <div class="form-group">
                        <label for="registerUsername">Benutzername</label>
                        <input type="text" class="form-control" id="registerUsername" th:field="*{username}" required>
                    </div>
                    <p class="has-error" th:if="${#fields.hasErrors('username')}" th:errors="*{username}" style="color: red"></p>

                    <div class="form-group">
                        <label for="registerPassword">Passwort</label>
                        <input type="password" class="form-control" id="registerPassword" th:field="*{password}" required>
                    </div>
                    <p class="has-error" th:if="${#fields.hasErrors('password')}" th:errors="*{password}" style="color: red"></p>

                    <div class="form-group">
                        <label for="registerPassword">Passwort Wiederholen</label>
                        <input type="password" class="form-control" id="registerPasswordRepeat" th:field="*{passwordConfirm}" required>
                    </div>
                    <span class="has-error" th:if="${#fields.hasErrors('passwordConfirm')}" th:errors="*{passwordConfirm}" style="color: red"></span>
                    <button type="submit" class="btn btn-primary">Registrieren</button>
                </form>
            </div>
        </div>
    </div>
</div>

验证:

@Override
    public void validate(Object o, Errors errors) {
        User user = (User) o;

        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "username", "NotEmpty");
        if (user.getUsername().length() < 2 || user.getUsername().length() > 32) {
            errors.rejectValue("username", "Size.userForm.username");
        }
        if (userService.findByUsername(user.getUsername()) != null) {
            errors.rejectValue("username", "Duplicate.userForm.username");
        }

        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "NotEmpty");
        if (user.getPassword().length() < 2 || user.getPassword().length() > 32) {
            errors.rejectValue("password", "Size.userForm.password");
        }

        if (!user.getPasswordConfirm().equals(user.getPassword())) {
            errors.rejectValue("passwordConfirm", "Diff.userForm.passwordConfirm");
        }
    }
}

我希望错误消息出现在模式中的行下面,类似于“字符太少”或类似的东西。这是目前不可能的,因为页面重新加载。我也试过使用AJAX,但不幸的是,它不适合我。

hyrbngr7

hyrbngr71#

我的建议是通过AJAXasynchronously提交表格。
首先,你应该在你的项目中包含一个库来发出AJAX请求,我将使用jQuery,你可以这样将它添加到你的html文件中:

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

然后,您应该修改HTML表单以防止默认表单提交行为:

<form id="loginForm" method="post" th:action="@{/login}" th:attr="data-url=@{/login}">

另外,更新控制器以返回JSON响应:

@PostMapping("/login")
public @ResponseBody Map<String, Object> login(Model model, String error, String logout) {
    Map<String, Object> response = new HashMap<>();

    // If logged in successfully, return a success response
    if (securityService.isAuthenticated()) {
        response.put("success", true);
        return response;
    }

    // Error example
    if (error != null) {
        response.put("success", false);
        response.put("html", "<p style='color: red'>Some error message here!</p>");
    }

    return response;
}

**注意:**我建议你对所有的控制器方法都这样做。

现在,您可以使用AJAX处理表单提交:

<script>
$(document).ready(function () {
    $("#loginForm").submit(function (event) {
        // Prevent the default submission
        event.preventDefault();

        var form = $(this);
        var url = form.attr("data-url");

        $.ajax({
            type: "POST",
            url: url,
            data: form.serialize(), // Serialize form data
            success: function (response) {
                // Check the response
                if (response.success) {
                    // Successful login
                    // TODO: Handle
                } else {
                    // Update the modal with the error message
                    $("#loginModal .modal-body").html(response.html);
                }
            }
        });
    });
});
</script>

这只是一个示例方法,您可以根据自己的需要进行调整。

相关问题