Bean Validation не выполняется, вместо этого переход к классу HandlerExceptionResolver - PullRequest
0 голосов
/ 07 марта 2020

Я добавил валидацию bean-компонента в класс JPA Breweries и путь к ошибке в форме. Когда я оставляю поля пустыми, вместо сообщения о проверке, отображаемого напротив правого поля, он использует мой класс HandlerExceptionResolver и отображает «ошибку». Код не входит в метод контроллера, когда я устанавливаю точку останова в первой строке, он никогда не достигает ее.

код в Breweries. java Класс JPA равен

    @Entity
@Table(name = "breweries")
@SecondaryTable(name = "breweries_geocode", pkJoinColumns = @PrimaryKeyJoinColumn(name = "brewery_id", referencedColumnName = "id"))

@XmlRootElement
@NamedQueries({
    @NamedQuery(name = "Breweries.findAll", query = "SELECT b FROM Breweries b"),
    @NamedQuery(name = "Breweries.findById", query = "SELECT b FROM Breweries b WHERE b.id = :id"),
    @NamedQuery(name = "Breweries.findByName", query = "SELECT b FROM Breweries b WHERE b.name = :name"),
    @NamedQuery(name = "Breweries.findByAddress1", query = "SELECT b FROM Breweries b WHERE b.address1 = :address1"),
    @NamedQuery(name = "Breweries.findByAddress2", query = "SELECT b FROM Breweries b WHERE b.address2 = :address2"),
    @NamedQuery(name = "Breweries.findByCity", query = "SELECT b FROM Breweries b WHERE b.city = :city"),
    @NamedQuery(name = "Breweries.findByState", query = "SELECT b FROM Breweries b WHERE b.state = :state"),
    @NamedQuery(name = "Breweries.findByCode", query = "SELECT b FROM Breweries b WHERE b.code = :code"),
    @NamedQuery(name = "Breweries.findByCountry", query = "SELECT b FROM Breweries b WHERE b.country = :country"),
    @NamedQuery(name = "Breweries.findByPhone", query = "SELECT b FROM Breweries b WHERE b.phone = :phone"),
    @NamedQuery(name = "Breweries.findByWebsite", query = "SELECT b FROM Breweries b WHERE b.website = :website"),
    @NamedQuery(name = "Breweries.findByImage", query = "SELECT b FROM Breweries b WHERE b.image = :image"),
    @NamedQuery(name = "Breweries.findByAddUser", query = "SELECT b FROM Breweries b WHERE b.addUser = :addUser"),
    @NamedQuery(name = "Breweries.findByLastMod", query = "SELECT b FROM Breweries b WHERE b.lastMod = :lastMod"),
    @NamedQuery(name = "Breweries.findByCreditLimit", query = "SELECT b FROM Breweries b WHERE b.creditLimit = :creditLimit"),
    @NamedQuery(name = "Breweries.findByEmail", query = "SELECT b FROM Breweries b WHERE b.email = :email")})
public class Breweries implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)


       @Column(name = "id")
        @Positive(message = "value must be positive")


           private Integer id;
        @Basic(optional = false)
        @NotNull
        @Column(name = "name")
        @NotBlank(message = " field cannot be empty")
        @Size(max = 50, message = "must be equal to or less then 50 chars")


          private String name;
            @Basic(optional = false)
            @NotNull

            @Column(name = "address1")
        @NotBlank(message = " field cannot be empty")
        @Size(max = 50, message = "must be equal to or less then 50 chars")
        private String address1;
        @Basic(optional = false)
        @NotNull

        @Column(name = "address2")
        @NotBlank(message = " field cannot be empty")
        @Size(max = 50, message = "must be equal to or less then 50 chars")
        private String address2;
        @Basic(optional = false)
        @NotNull

    @Column(name = "city")
    @NotBlank(message = " field cannot be empty")
    @Size(max = 30, message = "must be equal to or less then 30 chars")
    private String city;
    @Basic(optional = false)
    @NotNull

    @Column(name = "state")
    @NotBlank(message = " field cannot be empty")
    @Size(max = 20, message = "must be equal to or less then 200 chars")
    private String state;
    @Basic(optional = false)
    @NotNull

    @Column(name = "code")
    @NotBlank(message = " field cannot be empty")
    @Size(max = 5, message = "must contain at least 5 digits")
    private String code;
    @Basic(optional = false)
    @NotNull
    @Size(min = 1, max = 255)
    @Column(name = "country")
    @NotBlank(message = " field cannot be empty")
    private String country;
    // @Pattern(regexp="^\\(?(\\d{3})\\)?[- ]?(\\d{3})[- ]?(\\d{4})$", message="Invalid phone/fax format, should be as xxx-xxx-xxxx")//if the field contains phone or fax number consider using this annotation to enforce field validation
    @Basic(optional = false)
    @NotNull
    @Size(min = 1, max = 50)
    @Column(name = "phone")
@NotBlank(message = " field cannot be empty")
private String phone;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 255)
@Column(name = "website")
@URL(protocol = "http", message = "must be a valid url")
private String website;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 255)
@Column(name = "image")
private String image;
@Basic(optional = false)
@NotNull
@Lob
@Size(min = 1, max = 65535)
@Column(name = "description")
@NotBlank(message = " field cannot be empty")
private String description;
@Basic(optional = false)
@NotNull
@DecimalMax("99.00")
@Positive(message = "value must be positive")
@NotBlank(message = " field cannot be empty")
@Column(name = "add_user")
private int addUser;
@Basic(optional = false)
@NotNull
@Column(name = "last_mod")
@Temporal(TemporalType.TIMESTAMP)
private Date lastMod;
@Basic(optional = false)
@NotNull
@NotBlank(message = " field cannot be empty")
@Column(name = "credit_limit")
@Digits(integer = 6, fraction = 2, message = "Must have a max of 6 digits before the decimal point and 2 afterwards.")
private double creditLimit;
// @Pattern(regexp="[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", message="Invalid email")//if the field contains email address consider using this annotation to enforce field validation
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 50)
@Column(name = "email")
@Email(message = "must be a valid email adress")
private String email;
@Column(table = "breweries_geocode")
@NotBlank(message = " field cannot be empty")
@Size(min = -90, max = 90, message = "latitide must be between -90 and 90")
private float latitude;
@NotBlank(message = " field cannot be empty")
@Column(table = "breweries_geocode")
@Size(min = -180, max = 180, message = "latitide must be between -180 and 180")
private float longitude;

public float getLatitude() {
    return latitude;
}

public void setLatitude(float latitude) {
    this.latitude = latitude;
}

public float getLongitude() {
    return longitude;
}

public void setLongitude(float longitude) {
    this.longitude = longitude;
}

public Breweries() {
}

public Breweries(Integer id) {
    this.id = id;
}

public Breweries(Integer id, String name, String address1, String address2, String city, String state, String code, String country, String phone, String website, String image, String description, int addUser, Date lastMod, double creditLimit, String email) {
    this.id = id;
    this.name = name;
    this.address1 = address1;
    this.address2 = address2;
    this.city = city;
    this.state = state;
    this.code = code;
    this.country = country;
    this.phone = phone;
    this.website = website;
    this.image = image;
    this.description = description;
    this.addUser = addUser;
    this.lastMod = lastMod;
    this.creditLimit = creditLimit;
    this.email = email;
}

public Integer getId() {
    return id;
}

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

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getAddress1() {
    return address1;
}

public void setAddress1(String address1) {
    this.address1 = address1;
}

public String getAddress2() {
    return address2;
}

public void setAddress2(String address2) {
    this.address2 = address2;
}

public String getCity() {
    return city;
}

public void setCity(String city) {
    this.city = city;
}

public String getState() {
    return state;
}

public void setState(String state) {
    this.state = state;
}

public String getCode() {
    return code;
}

public void setCode(String code) {
    this.code = code;
}

public String getCountry() {
    return country;
}

public void setCountry(String country) {
    this.country = country;
}

public String getPhone() {
    return phone;
}

public void setPhone(String phone) {
    this.phone = phone;
}

public String getWebsite() {
    return website;
}

public void setWebsite(String website) {
    this.website = website;
}

public String getImage() {
    return image;
}

public void setImage(String image) {
    this.image = image;
}

public String getDescription() {
    return description;
}

public void setDescription(String description) {
    this.description = description;
}

public int getAddUser() {
    return addUser;
}

public void setAddUser(int addUser) {
    this.addUser = addUser;
}

public Date getLastMod() {
    return lastMod;
}

public void setLastMod(Date lastMod) {
    this.lastMod = lastMod;
}

public double getCreditLimit() {
    return creditLimit;
}

public void setCreditLimit(double creditLimit) {
    this.creditLimit = creditLimit;
}

public String getEmail() {
    return email;
}

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

@Override
public int hashCode() {
    int hash = 0;
    hash += (id != null ? id.hashCode() : 0);
    return hash;
}

@Override
public boolean equals(Object object) {
    // TODO: Warning - this method won't work in the case the id fields are not set
    if (!(object instanceof Breweries)) {
        return false;
    }
    Breweries other = (Breweries) object;
    if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
        return false;
    }
    return true;
}

@Override
public String toString() {
    return "lit.sd4.model.Breweries[ id=" + id + " ]";
}

addBrewery. jsp форма -

<form:form method="POST" action="/Assignment2/breweries/addBrewery" modelAttribute="brewerie">

    <table>

        <tr>
            <td><form:label path="name">Name</form:label></td>
            <td><form:input path="name" /></td>
            <td style="color:red"><form:errors path="name"/> </td>
        </tr>

        <tr>
            <td><form:label path="address1">Address 1</form:label></td>
            <td><form:input path="address1" /></td>
            <td style="color:red"><form:errors path="address1"/> </td>
        </tr>
        <tr>
            <td><form:label path="address2">Address 2</form:label></td>
            <td><form:input path="address2"/></td>
            <td style="color:red"><form:errors path="address2"/> </td>

        </tr>
        <tr>
            <td><form:label path="city">City</form:label></td>
            <td><form:input path="city"/></td>
            <td style="color:red"><form:errors path="city"/> </td>

        </tr>
        <tr>
            <td><form:label path="state">State</form:label></td>
            <td><form:input path="state"/></td>
            <td style="color:red"><form:errors path="state"/> </td>

        </tr>
           <tr>
            <td><form:label path="code">Code</form:label></td>
            <td><form:input path="code"/></td>
            <td style="color:red"><form:errors path="code"/> </td>

        </tr>

        <tr>
            <td><form:label path="country">Country</form:label></td>
            <td><form:input path="country"/></td>
            <td style="color:red"> <form:errors path="country"/> </td>
        </tr>

        <tr>
            <td><form:label path="phone">Phone Number</form:label></td>
            <td><form:input path="phone"/></td>
            <td style="color:red"> <form:errors path="phone"/> </td>
        </tr>
              <tr>
            <td><form:label path="website">Website</form:label></td>
            <td><form:input path="website"/></td>
            <td style="color:red"><form:errors path="website"/> </td>

        </tr>

        <tr>
            <td><form:label path="description">Description</form:label></td>
            <td><form:input path="description"/></td>
            <td style="color:red"> <form:errors path="description"/> </td>
        </tr>
        <tr>
            <td><form:label path="addUser">Add User</form:label></td>
            <td><form:input path="addUser"/></td>
            <td style="color:red"> <form:errors path="addUser"/> </td>
        </tr>

        <tr>
            <td><form:label path="creditLimit">Credit Limit</form:label></td>
            <td><form:input path="creditLimit"/></td>
            <td style="color:red"> <form:errors path="creditLimit"/> </td>
        </tr>
        <tr>
            <td><form:label path="email">Email</form:label></td>
            <td><form:input path="email"/></td>
            <td style="color:red"> <form:errors path="email"/> </td>
        </tr>
              <tr>
            <td><form:label path="latitude">Latitude</form:label></td>
            <td><form:input path="latitude"/></td>
            <td style="color:red"> <form:errors path="latitude"/> </td>
        </tr>
        <tr>
            <td><form:label path="longitude">Longitude</form:label></td>
            <td><form:input path="longitude"/></td>
            <td style="color:red"> <form:errors path="longitude"/> </td>
        </tr>

       <tr>
            <td><form:label path="image">Image</form:label></td>
            <td><form:input path="image"/></td>
            <td style="color:red"><form:errors path="image"/> </td>

        </tr>


        <tr>

            <td><input type="submit" value="Submit"/></td>
        </tr>
    </table>
</body>

метод контроллера, к которому он обращается при нажатии кнопки отправки, -

    @PostMapping("/addBrewery")
public ModelAndView addAnBrewery(ModelMap model, @Valid @ModelAttribute("brewerie") Breweries brewerie, BindingResult result) {

     if (result.hasErrors()) {
        return new ModelAndView("/addBrewery");
    }

    service.addAnBreweries(brewerie);
    return new ModelAndView("redirect:/breweries");

}
...