How to fix these and other errors: Failed to Convert from type [java.lang.String] to type [java.lang.Long] for value 'list'?

Asked

Viewed 4,449 times

0

I’m implementing an example of a book about Spring Boot, but, after executing, while trying to access the route /clientes/list or else, /clientes/view in the browser appear the following errors:

Failed to Convert value of type 'java.lang.String' to required type 'com.greendog.models.Client'; nested Exception is org.springframework.core.convert.Conversionfailedexception: Failed to Convert from type [java.lang.String] to type [java.lang.Long] for value 'list'; nested Exception is java.lang.Numberformatexception: For input string: "list"

inserir a descrição da imagem aqui

I don’t know how to fix it. Follow my codes:

Class Cliente.java:

package com.greendog.modelos;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.validation.constraints.NotNull;

import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
import org.hibernate.validator.constraints.Length;

import com.greendog.modelos.Pedido;

@Entity
public class Cliente {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Long id;

    @NotNull
    @Length(min=2, max=30, message="O tamanho do nome deve ser entre {min} e {max} caracteres.")
    private String nome;

    @NotNull
    @Length(min=2, max=300, message="O tamanho do endereçomdeve ser entre {min} e {max} caracteres.")
    private String endereco;

    @OneToMany(mappedBy = "cliente", fetch = FetchType.EAGER)
    @Cascade(CascadeType.ALL)
    private List<Pedido> pedidos;


    public Cliente(Long id, String nome, String endereco) {
        this.id = id;
        this.nome = nome;
        this.endereco = endereco;
    }

    public void novoPedido(Pedido pedido) {
        if(this.pedidos == null) pedidos = new ArrayList<Pedido>();
        pedidos.add(pedido);

    }
     /*Getter e Setter */
}

Interface ClienteRepository.java:

package com.greendog.repositories;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import com.greendog.modelos.Cliente;

@Repository
public interface ClienteRepository extends JpaRepository<Cliente, Long>{

}

Class ClienteController.java:

package com.greendog.controladores;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.greendog.modelos.Cliente;
import com.greendog.repositories.ClienteRepository;

@Controller
@RequestMapping("/clientes")
public class ClienteController {

    @Autowired
    private final ClienteRepository clienteRepository = null;

    //Exibe as lista de Clientes
    @GetMapping("/")
    public ModelAndView list() {
        Iterable<Cliente> clientes = this.clienteRepository.findAll();
        return new ModelAndView("clientes/list", "clientes", clientes);
    }

    //Exibe o detalhe de cada cliente
    @GetMapping("{id}")
    public ModelAndView view(@PathVariable("id") Cliente cliente) {
        return new ModelAndView("clientes/view", "cliente", cliente);
    }

    //Direciona para criar novo cliente
    @GetMapping("/novo")
    public String createForm(@ModelAttribute Cliente cliente) {
        return "clientes/form";
    }

    //Insere novo cliente através de um formulario
    @PostMapping(params = "form")
    public ModelAndView create(@Valid Cliente cliente, BindingResult result, RedirectAttributes redirect) {
        if(result.hasErrors()){
            return new ModelAndView("clientes/" + "form", "formErros", result.getAllErrors());
        }

        cliente = this.clienteRepository.save(cliente);
        redirect.addFlashAttribute("globalMessage", "Cliente gravado com sucesso!");

        return new ModelAndView("redirect:/" + "clientes/" + "{cliente.id}", "cliente.id", cliente.getId());
    }

    //Atualizar cliente
    @GetMapping(value = "alterar/id")
    public ModelAndView alterarForm(@PathVariable("id") Cliente cliente) {
        return new ModelAndView("cliente/form", "cliente", cliente);
    }

    //Remover Cliente
    public ModelAndView remover(@PathVariable("id") Long id, RedirectAttributes redirect) {
        this.clienteRepository.deleteById(id);
        Iterable<Cliente> clientes = this.clienteRepository.findAll();
        ModelAndView mv = new ModelAndView("clientes/list","clientes", clientes);
        mv.addObject("globalMessage", "Cliente removido com sucesso!");
        return mv;
    }
}

My folder structure of this project:

inserir a descrição da imagem aqui

Complete code on Github.

1 answer

1


it is falling into this exception because you are incorrectly calling your endpoint, when you call the path /clients/list in fact you are passing the string "list" to your view method, which causes your exception, the right would be customers/15 for example, being 15 the id of your customer, or just customers to call the list method


editing the answer here because I realized that there are several mistakes seeing your git 1° Your controllers methods, realize that you are using the Modelandview method passing in the constructor the name of the view, the name of the model and then the object of the model, your model is called client and the time to pass you ta passing clients plural in some calls, It needs to be the same because otherwise he won’t identify it. 2° your view method you are getting a model but put the id name, I think you got confused here, in my view you should exchange this Client for long id 3° still in your view method, you are passing the client with nothing, la na front will give an exception for null, changing your method he was like this for me:

@GetMapping("{id}")
    public ModelAndView view(@PathVariable("id") long id) {
        Cliente cliente = new Cliente(id, "Lucas", "123456"); //essa parte aqui você deve trocar pelo seu select
        return new ModelAndView("view", "cliente", cliente);
    }

4° in your html you put in the view that is giving error on line 10 th:if="{globalMessage}", there’s a dollar missing here and that’s why the parsing was wrong, the right one would be th:if="${globalMessage}"

  • Hi Lucas! Thank you so much for answering! I entered some data in this table for testing and when I try to access the way you told me I get this exception: Error resolving template "clientes/view", template might not exist or might not be accessible by any of the configured Template Resolvers.

  • 1

    Are you trying to return the view file from the templates folder? because look at the structure of your templates folder, the way you are suggesting that there is a folder called clients and inside them and your view file, if that’s the case you should replace your Return to Return new Modelandview("view", "client", client);

  • When making the change you suggested, this error appears An error happened during template parsing (template: "class path resource [templates/view.html]").

  • 1

    Now I need to see how the.html view looks to understand rsrs

  • No problem... rsrs... In case you want to see the full code, I put on Github.

  • I changed the answer with all minimal modifications, no longer consider giving a reread in the spring content, mainly on the question of mapping, if it all goes right please mark as correct :D

  • Okay. But take a look at book repository. It seems to work. Now the view worked here, but I still can’t access list that should allow access to all existing records in the bank.

  • 1

    note that in the template folder of your example there is a folder called clients: https://github.com/boaglio/spring-boot-greendogdelivery-casadocodigo/tree/master/src/main/resources/templates

  • 1

    in your you do not have, so if you try to map clients/list it does not find, because there is no way

  • I made the corrections and I climbed on Github. Routes work. Sorry, I really hadn’t noticed this directory issue clientes. But I still can’t find the form. When I try to access the route: http://localhost:8080/clientes/novo, get that mistake: An error happened during template parsing (template: "class path resource [templates/clientes/form.html]").

  • I already solved the problem of parsing. Thank you very much! ^_^

  • 1

    nothing, sorry for the delay, anything we are there

  • Come on, imagine! Thank you!

Show 8 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.