【问题标题】:Spring Validation - Errors not displayedSpring Validation - 未显示错误
【发布时间】:2017-03-16 01:54:55
【问题描述】:

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

对象:

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

自定义验证器:

@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(我使用引导程序)以便显示错误。

表格:

<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 没有改变。所以我的视图代码一定有问题,或者错误绑定没有正确传递给视图。但我找不到我的错误。

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2020-12-20
      • 1970-01-01
      • 2016-07-05
      • 2017-04-12
      • 2011-01-28
      • 1970-01-01
      • 2011-02-21
      • 2020-10-19
      • 2011-11-25
      相关资源
      最近更新 更多