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"
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:
Complete code on Github.
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
.– Van Ribeiro
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);
– Lucas Miranda
When making the change you suggested, this error appears
An error happened during template parsing (template: "class path resource [templates/view.html]")
.– Van Ribeiro
Now I need to see how the.html view looks to understand rsrs
– Lucas Miranda
No problem... rsrs... In case you want to see the full code, I put on Github.
– Van Ribeiro
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
– Lucas Miranda
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.– Van Ribeiro
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
– Lucas Miranda
in your you do not have, so if you try to map clients/list it does not find, because there is no way
– Lucas Miranda
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 theform
. 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]")
.– Van Ribeiro
I already solved the problem of
parsing
. Thank you very much! ^_^– Van Ribeiro
nothing, sorry for the delay, anything we are there
– Lucas Miranda
Come on, imagine! Thank you!
– Van Ribeiro