【问题标题】:Invalid target for Validator - Spring MVCValidator 的目标无效 - Spring MVC
【发布时间】:2017-10-27 16:22:12
【问题描述】:

我在 Spring 中进行验证时遇到问题。打开表单后出现以下错误:

java.lang.IllegalStateException: Invalid target for Validator [com.example.validator.UserValidator@6ac0a8f4]: com.example.web.forms.UserDTO@4d3b2379

我的 Validator 暂时,想先检查是否有任何工作:

@Component
public class UserValidator implements Validator {

    @Autowired
    ServiceUser serviceUser;

    @Override
    public boolean supports(Class<?> clazz) {
        return User.class.equals(clazz);
    }

    @Override
    public void validate(Object target, Errors errors) {

        User user = (User) target;

        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "NotEmpty.userForm.name");

    }

}

控制器:

@Controller
public class UserController {
    @Autowired
    UserValidator userValidator;

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        CustomDateEditor editor = new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true, 10);
        binder.registerCustomEditor(Date.class, editor);
        binder.setValidator(userValidator);
//        binder.addValidators(userValidator);
    }

    final static Logger logger = Logger.getLogger(UserController.class);

    @Autowired
    protected ServiceUserImpl service;


    @RequestMapping("/lista")
    public String showIndex(Model model) {
        User contest = new User();
        model.addAttribute("element", contest);
        model.addAttribute("collection", service.findAll());
        return "lista";
    }

    @RequestMapping("/dodaj")
    public String showFormPublication(HttpServletRequest request, @ModelAttribute("userDto") @Valid UserDTO userDTO, BindingResult result) {
        if (request.getMethod().equalsIgnoreCase("post") && !result.hasErrors()) {
            if (result.hasErrors()) {
                return "forms/contest";
            } else {
                User user = new User();
                user.setId(userDTO.getId());
                user.setName(userDTO.getName());
                user.setSurname(userDTO.getSurname());
                user.setDateOfBirth(userDTO.getDateOfBirth());
                user.setIndexNumber(userDTO.getIndexNumber());
                user.setEmail(userDTO.getEmail());
                service.save(user);

                return "redirect:/lista";
            }
        }
        return "dodaj";
    }
}

.jsp 中的表单:

<form:form action="dodaj" method="POST" modelAttribute="userDto">
        <table border="1">
            <tbody>
            <tr>
                <th>Imię</th>
                <td>
                    <form:input type="text" path="name" />
                    <c:if test="${pageContext.request.method=='POST'}"><form:errors path="name" /></c:if>
                </td>
            </tr>
            <tr>
                <th>Nazwisko</th>
                <td>
                    <form:input type="text" path="surname" />
                    <c:if test="${pageContext.request.method=='POST'}"><form:errors path="surname" /></c:if>
                </td>
            </tr>
            <tr>
                <th>DataUrodzenia</th>
                <td>
                    <form:input type="date" path="dateOfBirth" />
                    <c:if test="${pageContext.request.method=='POST'}"><form:errors path="dateOfBirth" /></c:if>
                </td>
            </tr>
            <tr>
                <th>NumerIndeksu</th>
                <td>
                    <form:input type="number" path="indexNumber" />
                    <c:if test="${pageContext.request.method=='POST'}"><form:errors path="indexNumber" /></c:if>
                </td>
            </tr>
            <tr>
                <th>Email</th>
                <td>
                    <form:input type="text" path="email" />
                    <c:if test="${pageContext.request.method=='POST'}"><form:errors path="email" /></c:if>
                </td>
            </tr>
            <tr>
                <td colspan="2" align="right"><input type="submit" value="Dodaj!" /></td>
            </tr>
            </tbody>
        </table>
    </form:form>

我尝试在 @InitBinder 旁边添加 ("userDto"),但不幸的是它没有帮助。在适用的解决方案方面还没有找到更多。如果还有什么我应该在这里发布的,请告诉我。如果有人急于尝试运行它,我还可以提供存储库的链接。

【问题讨论】:

    标签: java spring validation spring-mvc


    【解决方案1】:

    我认为您需要将UserValidator 中的supports 方法更改为UserDTO 类:

    public boolean supports(Class<?> clazz) {
         return UserDTO.class.equals(clazz);
    }
    

    【讨论】:

    • 谢谢,将验证方法中的用户更改为 UserDTO 有帮助。但是现在我在尝试提交无效表单后出现另一个错误-org.springframework.context.NoSuchMessageException:在区域设置'pl_PL'的代码'NotEmpty.userForm.name.userDTO.name'下找不到消息。如何摆脱它或添加本地化消息?
    • 它正在寻找显示该错误的文本,使用键 NotEmpty.userForm.name.userDTO.name。你在 messages.properties 文件中有这个吗?请参考类似的答案,例如:stackoverflow.com/a/12257303/4505142
    • 我在validation.properties 文件中有这个。尝试重命名为 messages.properties 只是为了确定,但意识到我没有在任何地方配置消息,所以我目前正在处理。
    • 我所做的只是用一个巨大的解决方法启用注释,而不是仅仅添加&lt;mvc:annotation-driven /&gt;。我现在得到的是“可能不是空的”,因为我有@NotEmpty 注释,结果应该不同,因为在messages.properties 我有NotEmpty.userForm.name.userDTO.name = Name is required! 编辑 - 我只是忘了取消注释binder.setValidator(userValidator); ,一切正常,非常感谢您的帮助。
    猜你喜欢
    • 2021-02-22
    • 1970-01-01
    • 2017-07-06
    • 1970-01-01
    • 2013-05-12
    • 2021-03-18
    • 2021-08-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多