代码之家  ›  专栏  ›  技术社区  ›  Theo

使用JavaSpring4.0和Thymeleaf进行表单验证

  •  0
  • Theo  · 技术社区  · 6 年前

    好的,这是我的 project .

    但是表单验证不起作用。这意味着我可以添加带有空字段的客户,这不应该发生。

    public class Customer {
    
    @NotNull
    private Integer id;
    
    @NotNull
    private String firstName;
    
    @NotNull
    private String secondName;
    
    @NotNull
    private String email;
    
    @NotNull
    private String phoneNumber;
    
    @NotNull
    private String addressLineOne;
    
    @NotNull
    private String addressLineTwo;
    
    @NotNull
    private String city;
    
    @NotNull
    private String state;
    
    @NotNull
    private String zipCode;
    
    public void setId(Integer id) {
        this.id = id;
    }
    
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    
    public void setSecondName(String secondName) {
        this.secondName = secondName;
    }
    
    public void setEmail(String email) {
        this.email = email;
    }
    
    public void setPhoneNumber(String phoneNumber) {
        this.phoneNumber = phoneNumber;
    }
    
    public void setAddressLineOne(String addressLineOne) {
        this.addressLineOne = addressLineOne;
    }
    
    public void setAddressLineTwo(String addressLineTwo) {
        this.addressLineTwo = addressLineTwo;
    }
    
    public void setCity(String city) {
        this.city = city;
    }
    
    public void setState(String state) {
        this.state = state;
    }
    
    public void setZipCode(String zipCode) {
        this.zipCode = zipCode;
    }
    
    public Integer getId() {
        return id;
    }
    
    public String getFirstName() {
        return firstName;
    }
    
    public String getSecondName() {
        return secondName;
    }
    
    public String getEmail() {
        return email;
    }
    
    public String getPhoneNumber() {
        return phoneNumber;
    }
    
    public String getAddressLineOne() {
        return addressLineOne;
    }
    
    public String getAddressLineTwo() {
        return addressLineTwo;
    }
    
    public String getCity() {
        return city;
    }
    
    public String getState() {
        return state;
    }
    
    public String getZipCode() {
        return zipCode;
    }
    }
    

    我的控制器

    @Controller
    public class CustomerController {
    
    CustomerService customerService;
    
    @Autowired
    public void setCustomerService(CustomerService customerService) {
        this.customerService = customerService;
    }
    
    @RequestMapping("/customers")
    public String listAllProducts(Model model){
    
        model.addAttribute("customers",customerService.listCustomers());
    
        return "customers";
    }
    
    @RequestMapping("/customer/{id}")
    public String showCustomer(@PathVariable Integer id, Model model){
    
        model.addAttribute("customer", customerService.getCustomerById(id));
    
        return "customer";
    
    }
    
    @RequestMapping("/customer/new")
    public String newCustomer(Model model){
        model.addAttribute("customer",new Customer());
        return "customerform";
    }
    
    @RequestMapping(value = "/customer", method = RequestMethod.POST)
    public String saveOrUpdateProduct(Customer customer){
    
        Customer saveCustomer = customerService.saveOrUpdateCustomer(customer);
        return "redirect:/customer/" + saveCustomer.getId();
    
    }
    
    @RequestMapping("/customer/edit/{id}")
    public String edit(@PathVariable Integer id, Model model){
    
        model.addAttribute("customer",customerService.getCustomerById(id));
    
        return "customerform";
    }
    
    @RequestMapping("/customer/delete/{id}")
    public String delete(@PathVariable Integer id){
    
        customerService.deleteCustomer(id);
    
        return "redirect:/customers";
      }
     }
    

    以及包含表单的html文件

    <div class="container">
    
    
    <h2>Product Details</h2>
    <div>
        <form class="form-horizontal" th:object="${customer}" th:action="@{/customer}" method="post">
            <input type="hidden" th:field="*{id}"/>
            <table>
                <tr>
                    <td><input type="hidden" th:field="*{id}"/></td>
                </tr>
                <tr>
                    <td>Fist Name:</td>
                    <td><input type="text" th:field="*{firstName}" /></td>
                    <td th:if="${#fields.hasErrors('firstName')}" th:errors="*{firstName}">Name Error</td>
                </tr>
                <tr>
                    <td>Surname:</td>
                    <td><input type="text" th:field="*{secondName}" /></td>
                    <td th:if="${#fields.hasErrors('secondName')}" th:errors="*{secondName}">Surname Error</td>
                </tr>
                <tr>
                    <td>Email:</td>
                    <td><input type="text" th:field="*{email}" /></td>
                    <td th:if="${#fields.hasErrors('email')}" th:errors="*{email}">Email Error</td>
                </tr>
                <tr>
                    <td>Phone Number:</td>
                    <td><input type="text" th:field="*{phoneNumber}" /></td>
                    <td th:if="${#fields.hasErrors('phoneNumber')}" th:errors="*{phoneNumber}">Phone Number Error</td>
                </tr>
                <tr>
                    <td>Address Line One:</td>
                    <td><input type="text" th:field="*{addressLineOne}" /></td>
                    <td th:if="${#fields.hasErrors('addressLineOne')}" th:errors="*{addressLineOne}">Address Line One Error</td>
                </tr>
                <tr>
                    <td>Address Line Two:</td>
                    <td><input type="text" th:field="*{addressLineTwo}" /></td>
                    <td th:if="${#fields.hasErrors('addressLineTwo')}" th:errors="*{addressLineTwo}">Address Line Two Error</td>
                </tr>
                <tr>
                    <td>City:</td>
                    <td><input type="text" th:field="*{city}" /></td>
                    <td th:if="${#fields.hasErrors('city')}" th:errors="*{city}">City Error</td>
                </tr>
                <tr>
                    <td>State:</td>
                    <td><input type="text" th:field="*{state}" /></td>
                    <td th:if="${#fields.hasErrors('state')}" th:errors="*{state}">State Error</td>
                </tr>
                <tr>
                    <td>Zip Code: </td>
                    <td><input type="text" th:field="*{zipCode}" /></td>
                    <td th:if="${#fields.hasErrors('zipCode')}" th:errors="*{zipCode}">Zip Code Error</td>
                </tr>
                <tr>
                    <td><button type="submit">Submit</button></td>
                </tr>
            </table>
        </form>
      </div>
     </div>
    

    我看着那个官员 documentation ,但我还在挣扎。

    固定的

    我添加了这个方法。

    @RequestMapping(value = "/customer", method = RequestMethod.POST)
    public String saveOrUpdateProduct(@Valid Customer customer, BindingResult bindingResult){
        if (bindingResult.hasErrors()) {
            return "customerform";
        }
        Customer saveCustomer = customerService.saveOrUpdateCustomer(customer);
        return "redirect:/customer/" + saveCustomer.getId();
    
    }
    

    2 回复  |  直到 6 年前
        1
  •  0
  •   Tony    6 年前

    尝试在customer的参数前添加@Valid注解以启用验证:

    @RequestMapping(value = "/customer", method = RequestMethod.POST)
    public String saveOrUpdateProduct(@Valid Customer customer){
    
        Customer saveCustomer = customerService.saveOrUpdateCustomer(customer);
        return "redirect:/customer/" + saveCustomer.getId();
    
    }
    
        2
  •  -1
  •   Nasibulloh Yandashev    6 年前

    @PostMapping("/add")
    @Transactional
    public String addUser(@Valid @ModelAttribute("userForm") UserEditForm userForm,
                          BindingResult result, ModelMap model) {
    
        if (userService.getUserByEmail(userForm.getEmail()).isPresent()) {
            FieldError emailError = new FieldError("userForm", "email", userForm.getEmail(), false, null, null, "Email already registered");
            result.addError(emailError);
        }
    
        if (result.hasErrors()) {
            return "users/add";
        }
    
    
    }
    

    但在你的例子中,UserEditForm等于customer。确保customer对象具有诸如@NotNull、@NotEmpty、@NotBlank之类的验证注释。