java - Spring Boot thymeleaf 错误请求 400 而不是显示用户错误

标签 java spring spring-boot thymeleaf

我正在尝试使用发布请求提交表单并首先验证输入。

但是,当我输入错误的内容(例如全部为空)而不是显示错误时,我收到错误的请求 (400)。

为了显示错误,我在 HTML 中使用 th:ifth:errors 标记。

如果我提交所有有效的输入,就没有问题。

Controller 类:

@Controller
@RequestMapping(path = "/order")
public class PurchaseController
{
    @GetMapping(path = "/new")
    public String newOrder(Model model)
    {
        model.addAttribute("Purchase", new Purchase());
        return "neworder";
    }

    @PostMapping(path = "/new")
    public String createPurchase(@Valid @ModelAttribute(name = "Purchase") Purchase purchase)
    {
        int purchaseId = 0;
        try
        {
            purchaseId = PurchaseManager.insertPurchase(purchase);
        }
        catch (SQLException e)
        {
            return "purchaseerror";
        }
        if (purchaseId == 0)
            return "purchaseerror";
        return "redirect:/order/success?id=" + purchaseId;
    }

    @GetMapping(path = "/success")
    public String successPurchase(@RequestParam(required = true, name = "id") int id, Model model)
    {
        model.addAttribute("id", id);
        return "ordersuccess";
    }
}

HTML 表单:

<form th:action="@{new}" th:object="${Purchase}" method="post">
                <table>
                    <tr>
                        <td>First name:</td>
                        <td><input type="text" th:field="*{firstName}" /></td>
                        <td th:if="${#fields.hasErrors('firstName')}"
                            th:errors="*{firstName}">Must be filled</td>
                        <td>Last name:</td>
                        <td><input type="text" th:field="*{lastName}" /></td>
                        <td th:if="${#fields.hasErrors('lastName')}"
                            th:errors="*{lastName}">Must be filled</td>
                    </tr>
                    <tr>
                        <td>Adresa:</td>
                        <td><input type="text" th:field="*{address}" /></td>
                        <td th:if="${#fields.hasErrors('address')}" th:errors="*{address}">Must be filled</td>
                    </tr>
                    <tr>
                        <td>ico:</td>
                        <td><input type="text" th:field="*{ico}" /></td>
                        <td th:if="${#fields.hasErrors('ico')}" th:errors="*{ico}">Must be filled</td>
                        <td>dic:</td>
                        <td><input type="text" th:field="*{dic}" /></td>
                        <td th:if="${#fields.hasErrors('dic')}" th:errors="*{dic}">Must be filled</td>
                    </tr>
                    <tr>
                        <td>Email:</td>
                        <td><input type="text" th:field="*{email}" /></td>
                        <td th:if="${#fields.hasErrors('email')}" th:errors="*{email}">Must be filled</td>
                        <td>phone:</td>
                        <td><input type="text" th:field="*{phone}" /></td>
                        <td th:if="${#fields.hasErrors('phone')}" th:errors="*{phone}">Must be filled</td>
                    </tr>
                </table>
                <input type="submit" value="Submit"/>
            </form>

模型类(购买)

public class Purchase
{
    private int id;

    @NotBlank
    @Size(max = 50)
    private String firstName;

    @NotBlank
    @Size(max = 50)
    private String lastName;

    @NotBlank
    @Size(max = 50)
    private String ico;

    @NotBlank
    @Size(max = 50)
    private String dic;

    @NotBlank
    @Size(max = 400)
    private String address;

    @NotBlank
    @Size(max = 50)
    private String email;

    @NotBlank
    @Size(max = 50)
    private String phone;

    private LocalDateTime creationDate;

    ... getters and setters, constructors

如何使用 thymeleaf 来显示错误?

编辑: 我设法通过将 BindingResult 参数添加到 Controller 类中的 post 方法并检查是否有任何错误来使其工作。如果是,我返回表单所在的同一页面(/新映射),即“neworder”。

返回“purchaseerror”;可能会造成一些困惑。

@PostMapping(path = "/new")
    public String createPurchase(@Valid @ModelAttribute(name = "Purchase") Purchase purchase, BindingResult result)
    {
        if (result.hasErrors())
        {
            return "neworder";
        }
        int purchaseId = 0;
        try
        {
            purchaseId = PurchaseManager.insertPurchase(purchase);
        }
        catch (SQLException e)
        {
            return "redirect:/purchaseerror";
        }
        if (purchaseId == 0)
            return "redirect:/purchaseerror";
        return "redirect:/order/success?id=" + purchaseId;
    }

最佳答案

我认为如果您在 createPurchase 方法中使用 Model 作为第二个参数,您的问题就可以解决。然后在您的方法中,您可以执行如下操作来添加消息:

@PostMapping("/add")
    public String addUser(@Valid User user, BindingResult result, Model model) {
        if (result.hasErrors()) {
            return "errors/addUser";
        }
        repository.save(user);
        model.addAttribute("users", repository.findAll()); //this is what you could do.
        return "errors/home";
    }

这会导致你的方法如下(请自行修改——我只是为了演示目的而写的):

@PostMapping(path = "/new")
    public String createPurchase(@Valid @ModelAttribute(name = "Purchase") Purchase purchase, Model model)
    {
        int purchaseId = 0;
        try
        {
            purchaseId = PurchaseManager.insertPurchase(purchase);
        }
        catch (SQLException e)
        {
            // todo: don't return right away. Add `model.addAttribute` first.
            return "purchaseerror";
        }
        if (purchaseId == 0) {
            // todo: don't return right away. Add `model.addAttribute` first.
            return "purchaseerror";
        }
        
        return "redirect:/order/success?id=" + purchaseId;
    }

然后,您的 Thymeleaf 实现将选择 modelAttribute 中的添加值,您可以从中选择错误(就像您填充它一样)并在此基础上简单地建立逻辑。

您可以按照示例 from here为了更好的理解。请记住,您需要添加到 Model 中,然后才能基于此在 thymeleaf 中布局逻辑。

希望我的回答能解决您的疑问。如果没有,抱歉。

关于java - Spring Boot thymeleaf 错误请求 400 而不是显示用户错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70426357/

相关文章:

Spring MQTT JAva Config 示例问题

java - 如何使用 JUnit 和 Mockito 通过静态 util 调用测试 Rest Controller

java - 未从 application.properties 中获取 Spring Boot JOOQ sql 方言

c# - 无法从字符串值加载类型

spring-boot - Spring Boot执行器尝试建立数据库连接

java - 在 Spring Boot 中使用 spring.application.json 作为 application.properties 文件

java - 在实体类中定义一个不是列的变量

java - 循环遍历枚举作为参数

java - 如何修复Spring Web应用程序的 ‘404--Not Found'问题

java - 如何在录音 Android 时显示 MIC 输入可视化