0

sou novo no mundo java estou com o erro springframework ao tentar enviar uma requisição via ajax. Alguém tem uma ideia do que pode estar causando o erro?

Abaixo um exemplo:

Javascrpit:

var enderecos = [];
var endereco  = {};
endereco.logradouro = "Av Moacir Miguel";
endereco.numero = "190";
endereco.complemento = "Apartamento 82";
endereco.bairro = "Centro";
endereco.cidade = "Sao Paulo";
endereco.uf = "SP";
endereco.cep = "12345678";
endereco.referencia = "Em frente ao colegio Maria Jose";

enderecos.push(endereco);

var cliente = {};
cliente.nome = "Joao Silva";
cliente.sexo = "M";
cliente.cpf = "12345678900";
cliente.dataNascimento = "03/08/1956";
cliente.profissao = "Aposentado";
cliente.fonte = "1";
cliente.email = "[email protected]";

//cliente.enderecos = enderecos;

console.log(JSON.stringify(cliente));

$.ajax({
    type: "POST",
    url: "/consultas/salvarCliente2",
    data : cliente,

    success: function(data) {
        console.log("sucesso");
        console.log(data);
    },
    statusCode: {
        404: function() {
            alert("404");
        }
    },
    error: function(xhr) {
        console.log("> error: ", xhr.responseText);
    },
    complete: function() {
        console.log("complete");
    }

   });

vejam que a atribuição cliente.enderecos = enderecos; está comentada.

No controller está assim:

@RequestMapping(value="salvarCliente2", method = RequestMethod.POST , produces = {"application/json", "application/xml"} , consumes = {"application/x-www-form-urlencoded"})
    public @ResponseBody ResponseEntity<?> salvarCliente2(Cliente cliente, BindingResult result, Locale currentLocale ) {

        System.out.println(cliente);
        return ResponseEntity.ok().build();
    }

Isso funciona perfeitamente no controller. Veja o resultado do System.out.println(cliente):

Cliente [dataCadastro=null, nome=Joao Silva, sexo=M, cpf=12345678900, dataNascimento=null, profissao=null, fonte=Cadastro [descricao=Internet, tipo=fonteCliente, ativo=S], [email protected], telefones=null, enderecos=null]

Porém quando removo o comentário do meu javascript cliente.enderecos = enderecos; inserindo o endereço do cliente no meu objeto cliente, retorna o seguinte erro no controller:

2019-08-28 12:14:57.388 ERROR 156 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.beans.InvalidPropertyException: Invalid property 'enderecos[0][bairro]' of bean class [com.vita.corpus.domain.Cliente]: Property referenced in indexed property path 'enderecos[0][bairro]' is neither an array nor a List nor a Map; returned value was [Endereco [cliente=null, logradouro=null, numero=null, complemento=null, bairro=null, cidade=null, uf=null, cep=null, referencia=null]]] with root cause

org.springframework.beans.InvalidPropertyException: Invalid property 'enderecos[0][bairro]' of bean class [com.vita.corpus.domain.Cliente]: Property referenced in indexed property path 'enderecos[0][bairro]' is neither an array nor a List nor a Map; returned value was [Endereco [cliente=null, logradouro=null, numero=null, complemento=null, bairro=null, cidade=null, uf=null, cep=null, referencia=null]]
    at org.springframework.beans.AbstractNestablePropertyAccessor.processKeyedProperty(AbstractNestablePropertyAccessor.java:375) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.beans.AbstractNestablePropertyAccessor.setPropertyValue(AbstractNestablePropertyAccessor.java:275) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.beans.AbstractNestablePropertyAccessor.setPropertyValue(AbstractNestablePropertyAccessor.java:266) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:97) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.validation.DataBinder.applyPropertyValues(DataBinder.java:848) ~[spring-context-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.validation.DataBinder.doBind(DataBinder.java:744) ~[spring-context-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.web.bind.WebDataBinder.doBind(WebDataBinder.java:197) ~[spring-web-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.web.bind.ServletRequestDataBinder.bind(ServletRequestDataBinder.java:107) ~[spring-web-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.ServletModelAttributeMethodProcessor.bindRequestParameters(ServletModelAttributeMethodProcessor.java:157) ~[spring-webmvc-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.web.method.annotation.ModelAttributeMethodProcessor.resolveArgument(ModelAttributeMethodProcessor.java:160) ~[spring-web-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:127) ~[spring-web-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:167) ~[spring-web-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:134) ~[spring-web-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104) ~[spring-webmvc-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:892) ~[spring-webmvc-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:797) ~[spring-webmvc-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1039) ~[spring-webmvc-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942) ~[spring-webmvc-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005) ~[spring-webmvc-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:908) ~[spring-webmvc-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:660) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882) ~[spring-webmvc-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:741) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.22.jar:9.0.22]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.springframework.web.servlet.resource.ResourceUrlEncodingFilter.doFilter(ResourceUrlEncodingFilter.java:63) ~[spring-webmvc-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) ~[spring-web-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:118) ~[spring-web-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:92) ~[spring-web-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:118) ~[spring-web-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93) ~[spring-web-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:118) ~[spring-web-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200) ~[spring-web-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:118) ~[spring-web-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490) [tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) [tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) [tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) [tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) [tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408) [tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:853) [tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1587) [tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-9.0.22.jar:9.0.22]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) [na:1.8.0_211]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) [na:1.8.0_211]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-9.0.22.jar:9.0.22]
    at java.lang.Thread.run(Unknown Source) [na:1.8.0_211]

Abaixo o objeto cliente:

import java.time.LocalDate;
import java.util.List;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.ForeignKey;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;

import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.format.annotation.DateTimeFormat.ISO;

@SuppressWarnings("serial")
@Entity
@Table(name = "cliente", uniqueConstraints = @UniqueConstraint(columnNames = "cpf_cgc", name = "uk_cpf_cgc"))
public class Cliente extends AbstractEntity<Long> {

    @DateTimeFormat(iso = ISO.DATE)
    @Column(name = "data_cad", columnDefinition = "DATE")
    private LocalDate dataCadastro;

    @Column(name = "nome", nullable = false, length = 100)
    private String nome;

    @Column(name = "sexo", length = 1)
    private String sexo;

    @Column(name = "cpf_cgc", length = 14)
    private String cpf;

    @DateTimeFormat(iso = ISO.DATE)
    @Column(name = "data_nasc", columnDefinition = "DATE")
    private LocalDate dataNascimento;

    @ManyToOne
    @JoinColumn(name = "id_profissao", foreignKey  = @ForeignKey(name = "fk_profissao_cliente"))
    private Cadastro profissao;

    @ManyToOne
    @JoinColumn(name = "id_fonte", foreignKey  = @ForeignKey(name = "fk_fonte_cliente"))
    private Cadastro fonte;

    @Column(name = "email", length = 100)
    private String email;

    @OneToMany(mappedBy = "cliente")
    private List<Telefone> telefones;

    @OneToMany(mappedBy = "cliente")
    private List<Endereco> enderecos;

    public LocalDate getDataCadastro() {
        return dataCadastro;
    }

    public void setDataCadastro(LocalDate dataCadastro) {
        this.dataCadastro = dataCadastro;
    }

    public String getNome() {
        return nome;
    }

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

    public String getSexo() {
        return sexo;
    }

    public void setSexo(String sexo) {
        this.sexo = sexo;
    }

    public String getCpf() {
        return cpf;
    }

    public void setCpf(String cpf) {
        this.cpf = cpf;
    }

    public LocalDate getDataNascimento() {
        return dataNascimento;
    }

    public void setDataNascimento(LocalDate dataNascimento) {
        this.dataNascimento = dataNascimento;
    }

    public Cadastro getProfissao() {
        return profissao;
    }

    public void setProfissao(Cadastro profissao) {
        this.profissao = profissao;
    }

    public Cadastro getFonte() {
        return fonte;
    }

    public void setFonte(Cadastro fonte) {
        this.fonte = fonte;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public List<Telefone> getTelefones() {
        return telefones;
    }

    public void setTelefones(List<Telefone> telefones) {
        this.telefones = telefones;
    }

    public List<Endereco> getEnderecos() {
        return enderecos;
    }

    public void setEnderecos(List<Endereco> enderecos) {
        this.enderecos = enderecos;
    }

    @Override
    public String toString() {
        return "Cliente [dataCadastro=" + dataCadastro + ", nome=" + nome + ", sexo=" + sexo + ", cpf=" + cpf
                + ", dataNascimento=" + dataNascimento + ", profissao=" + profissao + ", fonte=" + fonte + ", email="
                + email + ", telefones=" + telefones + ", enderecos=" + enderecos + "]";
    }



}

E o objeto endereço:

import javax.persistence.*;

@SuppressWarnings("serial")
@Entity
@Table(name = "endereco")
public class Endereco extends AbstractEntity<Long> {

    @ManyToOne
    @JoinColumn(name = "id_cliente", foreignKey  = @ForeignKey(name = "fk_cliente_endereco"))
    private Cliente cliente;

    @Column(nullable = false)
    private String logradouro;

    @Column(name="numero", nullable = false, length = 5)
    private Integer numero;

    @Column(name="complemento")
    private String complemento;

    @Column(name="bairro", nullable = false)
    private String bairro;

    @Column(name="cidade", nullable = false)
    private String cidade;

    @Column(name="uf", nullable = false, length = 2)
    @Enumerated(EnumType.STRING)
    private UF uf;

    @Column(name="cep", nullable = false, length = 9)
    private String cep;

    @Column(name="referencia")
    private String referencia;



    public Cliente getCliente() {
        return cliente;
    }

    public void setCliente(Cliente cliente) {
        this.cliente = cliente;
    }

    public String getLogradouro() {
        return logradouro;
    }

    public void setLogradouro(String logradouro) {
        this.logradouro = logradouro;
    }

    public String getBairro() {
        return bairro;
    }

    public void setBairro(String bairro) {
        this.bairro = bairro;
    }

    public String getCidade() {
        return cidade;
    }

    public void setCidade(String cidade) {
        this.cidade = cidade;
    }

    public UF getUf() {
        return uf;
    }

    public void setUf(UF uf) {
        this.uf = uf;
    }

    public String getCep() {
        return cep;
    }

    public void setCep(String cep) {
        this.cep = cep;
    }

    public Integer getNumero() {
        return numero;
    }

    public void setNumero(Integer numero) {
        this.numero = numero;
    }

    public String getComplemento() {
        return complemento;
    }

    public void setComplemento(String complemento) {
        this.complemento = complemento;
    }

    public String getReferencia() {
        return referencia;
    }

    public void setReferencia(String referencia) {
        this.referencia = referencia;
    }

    @Override
    public String toString() {
        return "Endereco [cliente=" + cliente + ", logradouro=" + logradouro + ", numero=" + numero + ", complemento="
                + complemento + ", bairro=" + bairro + ", cidade=" + cidade + ", uf=" + uf + ", cep=" + cep
                + ", referencia=" + referencia + "]";
    }
}

Agradeço se alguém puder ajudar.

1
  • Tenta instaciar as listas da sua classe cliente Commented 29/08/2019 às 12:11

1 Resposta 1

0

Valeu Rafael..

Além de instanciar as listas na classe Cliente alterei o formato de envio do ajax e o método no controller.

O Controller ficou assim:

@RequestMapping(value = "salvarCliente2", 
                    method = RequestMethod.POST, 
                    produces = MediaType.APPLICATION_JSON_VALUE, 
                    consumes = MediaType.APPLICATION_JSON_VALUE)
    public @ResponseBody ResponseEntity<?> salvarCliente2(@RequestBody Cliente cliente, BindingResult result, Locale currentLocale ) {

        System.out.println(cliente);
        return ResponseEntity.ok().build();
    }

O Ajax:

$.ajax({
            type: "POST",
            url: "/consultas/salvarCliente2",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            data : JSON.stringify(cliente),

            success: function(data) {
                console.log("sucesso");
                console.log(data);
            },
            statusCode: {
                404: function() {
                    alert("404");
                }
            },
            error: function(xhr) {
                console.log("> error: ", xhr.responseText);
            },
            complete: function() {
                console.log("complete");
            }

           });

Resultado no sysout:

Cliente [dataCadastro=null, nome=Joao Silva, sexo=M, cpf=12345678900, dataNascimento=null, profissao=Cadastro [descricao=null, tipo=null, ativo=null], fonte=Cadastro [descricao=null, tipo=null, ativo=null], [email protected], telefones=null, enderecos=[Endereco [cliente=null, logradouro=Av Moacir Miguel, numero=190, complemento=Apartamento 82, bairro=Centro, cidade=Sao Paulo, uf=SP, cep=12345678, referencia=Em frente ao colegio Maria Jose]]]

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .