【问题标题】:Form validation with Java Spring 4.0 and Thymeleaf使用 Java Spring 4.0 和 Thymeleaf 进行表单验证
【发布时间】:2018-08-18 10:14:57
【问题描述】:

好的,这是我的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();

}

现在一切都很好

【问题讨论】:

    标签: java spring web thymeleaf


    【解决方案1】:

    尝试在customer参数前加@Valid注解开启校验:

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

    【讨论】:

    • 我在尝试使用 @Valid 注释添加新客户时收到此错误:“此应用程序没有 /error 的显式映射,因此您将其视为后备。周六 8 月18 16:47:48 EEST 2018 出现意外错误(类型=错误请求,状态=400)。对象='客户'的验证失败。错误计数:1"
    • 您的服务器端是否有任何错误堆栈跟踪?
    • 我收到 400 类型的错误请求。您可以克隆我的项目并运行它来检查自己。
    【解决方案2】:

    你可以这样使用:

    @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 不等于 Costumer。确保 Costumer 对象具有验证注释,例如 @NotNull、@NotEmpty、@NotBlank,例如

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-26
      • 2015-07-29
      • 2017-07-14
      • 2020-09-18
      • 2018-11-23
      • 2019-06-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多