Hibernate Validator无法正常工作

时间:2018-04-18 08:07:47

标签: hibernate spring-mvc hibernate-validator

我尝试使用JSR303,Hibernate验证器来验证字段。我正在使用@NotEmpty annonation,并尝试打印简单的错误消息。但它不起作用。

这是我的用户pojo类。

package com.kalam.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;

import org.hibernate.validator.constraints.NotEmpty;

@Entity
@Table(name="User")
public class User {

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long userId;

@Column
@NotEmpty(message="username can't be blank")
private String UserName;

@Column
@NotEmpty(message="password can't be blank")
private String Password;

@Column
@NotEmpty(message="Mobile can't be blank")
private Integer MobileNo;

public Integer getMobileNo() {
    return MobileNo;
}

public void setMobileNo(Integer mobileNo) {
    MobileNo = mobileNo;
}

@Enumerated(EnumType.ORDINAL)
private Role userRole;

public Long getUserId() {
    return userId;
}

public void setUserId(Long userId) {
    this.userId = userId;
}

public String getUserName() {
    return UserName;
}

public void setUserName(String userName) {
    UserName = userName;
}

public String getPassword() {
    return Password;
}

public void setPassword(String password) {
    Password = password;
}

public Role getUserRole() {
    return userRole;
}

public void setUserRole(Role userRole) {
    this.userRole = userRole;
}

}

用户jsp页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>   
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Registration</title>
<style>
    .error {
        color: red; font-weight: bold;
    }
</style>
</head>
<body>
    <div align="center">
        <form:form action="addUser" method="post" modelAttribute="userFrom">
            <table border="0">
                <tr>
                    <td colspan="2" align="center"><h2>Spring MVC Form Demo - Registration</h2></td>
                </tr>
               <tr>
                    <td>User Name:</td>
                    <td><form:input path="UserName" /></td>
                    <td><form:errors path="UserName" cssClass="error" /></td>
                </tr>

                <tr>
                    <td>Password:</td>
                    <td><form:password path="Password" /></td>
                    <td><form:errors path="Password" cssClass="error" /></td>
                </tr>
                <tr>
                    <td>Mobile No:</td>
                    <td><form:input path="MobileNo" /></td>
                    <td><form:errors path="MobileNo" cssClass="error" /></td>
                </tr>

                <tr>
                    <td colspan="2" align="center"><input type="submit" value="Register" /></td>
                </tr>
            </table>
        </form:form>
    </div>
</body>
</html>

和finnaly控制器类。我试图运行简单的注册操作,并验证字段值。

package com.kalam.controller;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.kalam.daoimpl.EmployeeDaoImpl;
import com.kalam.model.Employee;
import com.kalam.model.User;
import com.kalam.service.EmployeeService;
import com.kalam.serviceimpl.EmployeeServiceImpl;




@Controller

public class KalamController {

//@Autowired 
//EmployeeService employeeService;

    @RequestMapping("/kalam")
    public String showMessage(ModelMap map) {

        map.put("dollar", "50 US $");
        return "KalamWorld";
    }

    @RequestMapping("/insertData")
    public void InserData() {

        Employee emp= new Employee();
        emp.setEmpID(11);
        emp.setEmpName("On Target");
        emp.setEmpSalary(20000);
        emp.setAddress("Mumbai");


            ApplicationContext context=new ClassPathXmlApplicationContext("hibernate-cfg.xml"); 
            EmployeeDaoImpl dao= (EmployeeDaoImpl)context.getBean("employeeDaoImpl");
            dao.addEmployee(emp); 
            System.out.println("Data successfully inserted");

    //  employeeService.addEmployee(emp);  
    } 


    @RequestMapping(value ="/",method = RequestMethod.GET)
    public String login(ModelMap model) {
        User userForm=new User();
        model.put("userFrom", userForm);
        return "User";

    }

    @RequestMapping(value = "/addUser", method = RequestMethod.POST)
       public String addEmployee(@Valid @ModelAttribute("userFrom")User user,BindingResult result) {
         if(result.hasErrors()){
             return "User";
         }

          return "success";
       }


    @RequestMapping(value ="/welcome",method = RequestMethod.GET)
    public String welcome(ModelMap model) {
        return "User";

    }



}

当我点击注册按钮而没有填写任何值时,它没有显示任何错误,而是重定向到成功页面。请帮我。谢谢。

1 个答案:

答案 0 :(得分:0)

为什么你没有使用弹簧验证器。https://www.journaldev.com/2668/spring-validation-example-mvc-validator

试试这个。