Spring Boot thymeleaf bad request 400 而不是显示用户错误

Spring Boot thymeleaf bad request 400 instead of showing user error

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

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

为了显示错误,我在 HTML.

中使用了 th:ifth:errors 标签

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

控制器class:

@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>

型号class(购买)

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 class 中的 post 方法并检查是否有任何错误来使其工作。如果是,我 return 表单所在的同一页面(/new 映射),即“neworder”。

return“购买错误”; 可能会造成一些混乱。

@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 中布置逻辑。

希望我的回答能解决您的疑问。如果不是,请见谅。