弹簧验证 - 未显示错误

时间:2016-11-02 16:43:12

标签: validation spring-mvc spring-boot thymeleaf spring-validator

我正在使用注释验证和自定义验证器的组合

对象:

@Entity
@Table(name = "monitoringsystems")
public class MonitoringSystem {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@NotNull(message = "Name must not be empty.")@Size(min=1, message="Name must not be empty.")
private String name;
@NotNull(message = "URL must not be empty.")@Size(min=1, message="Name must not be empty.")
private String url;
@NotNull(message = "Username must not be empty.")@Size(min=1, message="Name must not be empty.")
private String username;
@NotNull(message = "Password must not be empty.")@Size(min=1, message="Name must not be empty.")
private String password;
@NotNull(message = "Confirm Password must not be empty.")@Size(min=1, message="Name must not be empty.")
@Transient
private String passwordConfirm;

的CustomValidator:

@Component
public class MonitoringSystemValidator implements Validator {

@Override
public boolean supports(Class<?> type) {
    return MonitoringSystem.class.isAssignableFrom(type);
}

@Override
public void validate(Object o, Errors errors) {
    MonitoringSystem monitoringSystem = (MonitoringSystem) o;
    if(!monitoringSystem.getPassword().equals(monitoringSystem.getPasswordConfirm())){
        errors.rejectValue("passwordConfirm", "Passwords are not equal.");
    }
}  

}

我在控制器中初始化自定义验证器,并设置表单和保存方法的映射。

控制器:

@Controller
public class MonitoringSystemController {

@Autowired
private MonitoringSystemValidator monitoringSystemValidator;

@InitBinder
public void dataBinding(WebDataBinder binder) {
    binder.addValidators(monitoringSystemValidator);
}

@RequestMapping("/monitoringsystem/new")
public String newMonitoringSystem(Model model, HttpServletRequest request) {
    MonitoringSystem monitoringSystem = new MonitoringSystem();
    model.addAttribute("monitoringSystem", monitoringSystem);
    request.getSession().setAttribute("anonymization", monitoringSystem.getAnonymization());
    request.getSession().setAttribute("hosts", monitoringSystem.getHosts());

    return "monitoringsystem/form";
}

@RequestMapping(value = "/monitoringsystem/save", method = RequestMethod.POST)
public String save(@Valid MonitoringSystem monitoringSystem, BindingResult result, HttpServletRequest request, Model model) {

    if(result.hasErrors()){
        model.addAttribute("monitoringSystem", monitoringSystem);
        request.getSession().setAttribute("anonymization", request.getSession().getAttribute("anonymization"));
        request.getSession().setAttribute("hosts", request.getSession().getAttribute("hosts"));        
        return "monitoringsystem/form";
    }

//more code

在第一步中,我只想更改字段的CSS(我使用bootstrap),以便显示错误。

形式:

<form class="form-horizontal" th:modelAttribute="monitoringSystem" th:object="${monitoringSystem}" th:action="@{/monitoringsystem/save}" method="post">
            <input type="hidden" th:field="*{id}"/>
            <fieldset>
                <legend>New Monitoring-System</legend>
                <div class="form-group" th:classappend="${#fields.hasErrors('name')} ?: 'has-error has-danger'">
                    <label class="col-md-4 control-label" for="textinput">Systemname</label>  
                    <div class="col-md-5">
                        <input th:field="*{name}" class="form-control input-md" type="text" /> 
                    </div>
                </div>
                <div class="form-group" th:classappend="${#fields.hasErrors('url')} ?: 'has-error has-danger'">
                    <label class="col-md-4 control-label" for="textinput">URL</label>  
                    <div class="col-md-5">
                        <input th:field="*{url}" class="form-control input-md" type="text" /> 
                    </div>
                </div>
                <div class="form-group" th:classappend="${#fields.hasErrors('username')} ?: 'has-error has-danger'">
                    <label class="col-md-4 control-label" for="textinput">Username</label>  
                    <div class="col-md-5">
                        <input th:field="*{username}" class="form-control input-md" type="text" />
                    </div>
                </div>
                <div class="form-group" th:classappend="${#fields.hasErrors('password')} ?: 'has-error has-danger'">
                    <label class="col-md-4 control-label" for="textinput">Password</label>  
                    <div class="col-md-5">
                        <input th:field="*{password}" class="form-control input-md" type="password" />
                    </div>
                </div>
                <div class="form-group" th:classappend="${#fields.hasErrors('passwordConfirm')} ?: 'has-error has-danger'">
                    <label class="col-md-4 control-label" for="textinput">Confirm Password</label>  
                    <div class="col-md-5">
                        <input th:field="*{passwordConfirm}" class="form-control input-md" type="password" />
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-md-4 control-label" for="singlebutton"></label>
                    <div class="col-md-4">
                        <a th:href="@{/monitoringsystem}" class="btn btn-default btn-small">Cancel</a> <button id="singlebutton" name="singlebutton" class="btn btn-primary btn-small">Submit</button>
                    </div>
                </div>
            </fieldset>
        </form>

我的验证工作正常。仅当我的字段不为空,大小为1且密码匹配时,才会保存表单。如果没有,我的控制器会将我重定向到表单。

问题是,我的css不会改变。因此,我的视图代码一定存在问题,或者错误绑定未正确传递给视图。但我找不到我的错误。

1 个答案:

答案 0 :(得分:0)

我的if条件中有一个错误,它添加了错误类。我必须将${#fields.hasErrors('url')} ?: 'has-error has-danger'更改为${#fields.hasErrors('*{name}')} ? 'has-error has-danger'