簡體   English   中英

Spring MVC 5+:Bean 驗證不顯示錯誤

[英]Spring MVC 5+: Bean validation not show error

我的Bean Validation有問題,當我提交包含錯誤數據的表單時,盡管BindingResult有錯誤,但表單沒有顯示錯誤。 我錯過了Pom.xml中的任何配置或依賴項嗎?

我通過實現Validator 接口嘗試了messages.properties和自定義驗證,但它不起作用。

請幫我。 非常感謝

這是我的Controller

package WatchShop.UserController;

import WatchShop.Dao.UsersDao;
import WatchShop.Entity.Users;
import WatchShop.Service.User.AccountServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;

@Controller
public class UserController extends BaseController {
    @Autowired
    AccountServiceImpl accountService = new AccountServiceImpl();
    @Autowired
    UsersDao userDao = new UsersDao();

//    private UserValidator userValidator = new UserValidator();

    @RequestMapping(value = "/dang-ky", method = RequestMethod.GET)
        public ModelAndView Register(){
        _mvShare.setViewName("user/register");
        _mvShare.addObject("user",new Users());
        return _mvShare;
    }
    @RequestMapping(value = "/dang-ky", method = RequestMethod.POST)
    public ModelAndView CreateAccount( @Valid @ModelAttribute("user") Users user, BindingResult rs){
        int count = 0;
        if(rs.hasErrors()){
//            _mvShare.addObject("signup", "Error");
            _mvShare.addObject("count", count);
//            _mvShare.setViewName("user/register");
            System.out.println(rs);
            return _mvShare;
        }else{
            boolean check = accountService.checkEmailExist(user);
            if(!check){
                count = accountService.AddAccount(user);
                if(count > 0){
//                    _mvShare.addObject("signup", "Email ");
                    _mvShare.addObject("count", count);
                    _mvShare.setViewName("user/login");
                }
            }else{
                _mvShare.addObject("signup", "Email đã tồn tại");
                _mvShare.addObject("count", count);
                _mvShare.setViewName("user/register");
                return _mvShare;
            }
        }
        return _mvShare;
    }

這是我的文件config-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:jdbc="http://www.springframework.org/schema/jdbc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
                        http://www.springframework.org/schema/beans/spring-beans.xsd
                        http://www.springframework.org/schema/context
                        http://www.springframework.org/schema/context/spring-context.xsd
                        http://www.springframework.org/schema/tx 
                        http://www.springframework.org/schema/tx/spring-tx.xsd 
                        http://www.springframework.org/schema/mvc 
                        http://www.springframework.org/schema/mvc/spring-mvc.xsd
                        http://www.springframework.org/schema/jdbc http://springframework.org/schema/jdbc/spring-jdbc-4.3.xsd">

    <mvc:annotation-driven validator="myBeansValidator"/>
    <mvc:resources location="/assets/" mapping="/assets/**"></mvc:resources>

    <bean id="viewResolver" p:prefix="/WEB-INF/views/" p:suffix=".jsp"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver" />

    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName"
            value="com.mysql.jdbc.Driver"></property>
        <property name="url"
            value="jdbc:mysql://localhost:3306/watch_shop"></property>
        <property name="username" value="root"></property>
        <property name="password" value=""></property>
    </bean>

    <bean id="jdbcTemplate"
        class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <context:component-scan base-package="WatchShop" />

    <bean id="myBeansValidator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />
    
    <bean id="messageSource"
        class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basename" value="/WEB-INF/messages" />
    </bean>

</beans>

這是我在Pom.xml中驗證的依賴項

        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>2.0.1.Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate.validator</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>6.0.7.Final</version>
        </dependency>
        <dependency>
          <groupId>org.hibernate.validator</groupId>
          <artifactId>hibernate-validator-annotation-processor</artifactId>
          <version>6.1.3.Final</version>
        </dependency>
        <dependency>
            <groupId>javax.el</groupId>
            <artifactId>javax.el-api</artifactId>
            <version>3.0.1-b04</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish</groupId>
            <artifactId>javax.el</artifactId>
            <version>3.0.1-b08</version>
        </dependency>

這是我的觀點

<form:form action="dang-ky" method="POST" modelAttribute="user" cssClass="fmrt">
                                <div class="form-group last mb-3">
                                    <label for="firstName">Họ </label> <br/> <form:errors path="firstName" cssClass="error"/>
                                    <form:input path="firstName" class="form-control" placeholder="Nguyễn" type="text" name="firstName"/>
                                   
                                </div>
                                <div class="form-group last mb-3">
                                    <label for="lastName">Tên</label> <br/> <form:errors path="lastName" cssClass="error"/>
                                    <form:input path="lastName" class="form-control" placeholder="Văn A" type="text" name="lastName" />
                                </div>
                                <div class="form-group first">
                                    <label for="email">Email</label> <br/> <form:errors path="email" cssClass="error"/>
                                    <form:input path="email" class="form-control" placeholder="your-email@gmail.com" type="email" name="email" />
                                </div>
                                <div class="form-group last mb-3">
                                    <label for="password">Mật khẩu</label> <br/> <form:errors path="password" cssClass="error"/>
                                    <form:input path="password" class="form-control" placeholder="mật khẩu" type="password" name="password" />
                                </div>
                                <div class="form-group last mb-3">
                                    <label for="address">Địa chỉ</label>
                                    <form:input path="address" class="form-control" type="text" placeholder="địa chỉ chi tiết" id="address" name="address" />
                                </div>
                                <div class="d-sm-flex mb-5 align-items-center">
                                    <span class="ml-auto"> <a href="<c:url value="/dang-nhap"/>" class="forgot-pass">Về trang đăng nhập</a></span>
                                </div>
                                <input type="submit" id="submit" value="Đăng ký" class="btn btn-block py-2 btn-primary">
                            </form:form>

這是我的Model

package WatchShop.Entity;

import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;

public class Users {
    private long id;
    @Valid
    @NotEmpty(message = "Email không được để trống")
    private String email;
//    @Size(min = 6, max = 50, message = "password phải từ 6-50 ký tự")
    @Valid
    @NotEmpty(message = "password không được bỏ trống")
    @Pattern(regexp = "^(?=.*[a-z])(?=.*[A-Z]).{6,50}$", message = "password phải chứ ký tự hoa, 6-50 ký tự")
    private String password;
    @Valid
    @NotEmpty(message = "họ không được bỏ trống")
    private String firstName;
    @Valid
    @NotEmpty(message = "tên không được bỏ trống")
    private String lastName;
    private String address;

    public Users() {
    }

    public Users(long id, String email, String password, String firstName, String lastName, String address) {
        this.id = id;
        this.email = email;
        this.password = password;
        this.firstName = firstName;
        this.lastName = lastName;
        this.address = address;
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "Users{" +
                "id=" + id +
                ", email='" + email + '\'' +
                ", password='" + password + '\'' +
                ", firstName='" + firstName + '\'' +
                ", lastName='" + lastName + '\'' +
                ", address='" + address + '\'' +
                '}';
    }
}

最后,我做到了。 我添加了新的 ModelAndView 然后返回它。 這行得通

@RequestMapping(value = "/dang-ky", method = RequestMethod.POST)
    public ModelAndView CreateAccount( @Valid @ModelAttribute("user") Users user, BindingResult rs){
        int count = 0;
        if(rs.hasErrors()){
            System.out.println(rs);
            _mvShare = new ModelAndView("user/register");
            return _mvShare;
        }else{

它打敗了我很多時間:(

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM