繁体   English   中英

使用Java Spring 4.0和Thymeleaf进行表单验证

[英]Form validation with Java Spring 4.0 and Thymeleaf

好的,这是我的项目

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

这是我的模型课。

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>

为什么会这样?

我查看了官方文档 ,但仍在努力。

我该如何解决这个问题?

固定

我添加了此方法。

@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();

}

现在一切都很好

尝试在客户参数之前添加@Valid批注以启用验证:

@RequestMapping(value = "/customer", method = RequestMethod.POST)
public String saveOrUpdateProduct(@Valid Customer customer){

    Customer saveCustomer = customerService.saveOrUpdateCustomer(customer);
    return "redirect:/customer/" + saveCustomer.getId();

}

您可以这样使用:

@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之类的Validation注释,例如

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM