5

我知道这里有很多类似的问题,但没有一个能解决我的问题。

我正在使用 Spring 4.0.3 和 Hibernate Validator 5.1.0。当我尝试省略标签的path属性时会出现问题,因此:<form:errors/>

<form:errors path="contato.nome" />有效
<form:errors path="*" />有效
<form:errors />无效

我不知道为什么会这样。Spring javadocs(org.springframework.web.servlet.tags.form.ErrorsTag)说它应该像这样工作:

仅字段 - 将路径设置为字段名称(或路径)
仅对象错误 - 省略路径
所有错误 - 将路径设置为 *

你能帮我吗?

感兴趣的代码在“edicao.jsp”和 ContatoController.java 的“confirmarEdicao”方法中。对不起,如果我的英语不好。


ContatoController.java

@Controller
@RequestMapping("/contatos")
public class ContatoController {

    @Autowired
    private ContatoService contatoService;

    @Autowired 
    private MessageSource messageSource;

    @RequestMapping(value = "/confirmarEdicao", method = RequestMethod.POST)
    public String confirmarEdicao(@Valid Contato contato, BindingResult bindingResult) {

        if(bindingResult.hasErrors()) {
            return "contatos/edicao";
        }

        contatoService.save(contato);
        return "redirect:/contatos";
    }

    @RequestMapping(method = RequestMethod.GET)
    public ModelAndView form(HttpServletRequest request) {
        String message = messageSource.getMessage("teste", null, new Locale("pt", "BR"));
        System.out.println(message);
        return new ModelAndView("contatos/listagem")
            .addObject("contatos", contatoService.list());
    }

    @RequestMapping("/remover/{id}")
    public String remover(Contato contato) {
        contatoService.delete(contato);
        return "redirect:/contatos";
    }

    @RequestMapping("/editar/{id}")
    public ModelAndView formEdicao(Contato contato) {
        contato = contatoService.find(contato.getId());
        return new ModelAndView("contatos/edicao")
            .addObject(contato);
    }


    @RequestMapping(value = "/cadastrar")
    public String formCadastro() {
        return "contatos/cadastro";
    }

    @RequestMapping(value = "/confirmarCadastro", method = RequestMethod.POST)
    public String confirmarCadastro(@Valid Contato contato, BindingResult bindingResult, 
            RedirectAttributes redirectAttributes) {        

        if (bindingResult.hasFieldErrors()) {
            return "contatos/cadastro";
        }

        contatoService.save(contato);
        redirectAttributes.addFlashAttribute("mensagem", "Contato cadastrado com sucesso.");
        return "redirect:/contatos";
    }   

    @ResponseBody
    @RequestMapping(value = "/pesquisar/{nome}", method = RequestMethod.GET, 
        produces="application/json")
    public List<Contato> pesquisar(@PathVariable String nome) {
        return contatoService.findByName(nome);
    }

}

edicao.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> 
<!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>Editar contato</title>
</head>
<body>

<c:set var="context">${pageContext.request.contextPath}</c:set>
<script type="text/javascript">var context = "${context}";</script>
<script src="${context}/resources/js/jquery-2.1.0.min.js"></script>
<script src="${context}/resources/js/contatos/edicao.js"></script>

<form:form commandName="contato" action="${context}/contatos/confirmarEdicao" method="post">
<form:errors/>
    <table>
        <form:hidden path="id"/>
        <tr>
            <td>Nome:</td> 
            <td><form:input path="nome" /></td>
        </tr>
        <tr>
            <td>Telefone:</td>
            <td><form:input path="telefone"/></td>
        </tr>
        <tr>
            <td><input type="button" value="Voltar" id="btn_voltar"/><input type="submit" value="Salvar"/></td>         
        </tr>
    </table>
</form:form>

</body>
</html>

联系.java

package com.handson.model;

import javax.validation.constraints.Size;

import org.hibernate.validator.constraints.NotEmpty;

public class Contato {

    private Long id;

    @Size(min = 3, message = "Nome deve ter no mínimo 3 caracteres")
    @NotEmpty(message = "O nome deve ser preenchido")
    private String nome;

    private String telefone;

    public Long getId() {
        return id;
    }

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

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public String getTelefone() {
        return telefone;
    }

    public void setTelefone(String telefone) {
        this.telefone = telefone;
    }

    public Contato withId(Long id) {
        setId(id);
        return this;
    }

    public Contato withTelefone(String telefone) {
        setTelefone(telefone);
        return this;
    }

    public Contato withNome(String nome) {
        setNome(nome);
        return this;
    }

    @Override
    public String toString() {
        return "Contato [id=" + id + ", nome=" + nome + ", telefone="
                + telefone + "]";
    }

}
4

1 回答 1

14

有一些关键字需要定义:

  • path - 对象或对象字段的类 EL 路径(例如foo,foo.barfoo.bar.baz
  • 嵌套路径- 存储为请求属性的当前路径上下文nestedPath(新路径与此路径相关)
  • 对象错误- 与对象本身相关的错误(例如路径等于foo
  • 字段错误- 与对象字段相关的错误(例如路径是foo.bar

该标签<form:form commandName="foo">将嵌套路径定义为nestedPath=foo. 当您编写<form:errors path="bar">它时,它会尝试查找为 path 定义的错误foo.bar

假设您有与foo(对象错误)foo.barfoo.bar.baz(嵌套字段错误)相关的错误。这意味着什么:

  • 如果输入<form:errors>,则仅显示绑定到foo路径的错误 => 1 条消息
  • 如果输入<form:errors path="bar">,则仅显示绑定到foo.bar路径的错误 => 1 条消息
  • 如果输入<form:errors path="*">,则显示绑定到的错误foo及其子路径 => 3 条消息
  • 如果您输入<form:errors path="bar.*">,则仅显示子错误foo.bar=> 1 条消息
  • 如果您输入<form:errors path="bar*">,则会显示绑定到的错误foo.bar及其子路径 => 2 条消息

检查Errors类 JavaDoc 可能会给您额外的见解。

于 2014-04-28T11:49:52.483 回答