Java com Spring MVC - Erro Failed to convert from type [java.lang.String] to type [java.lang.Long] for value 'Cris'; nested exception is java.lang.NumberFormatException: For input string: "Cris"

Olá pessoal! Não consigo corrigir um problema que ocorre ao tentar salvar uma informação. Tenho outro projeto que funciona e mesmo tentando comparar um com o outro, não descobri qual é o problema.

A mensagem de erro que aparece é a seguinte:

Failed to convert from type [java.lang.String] to type [java.lang.Long] for value 'Cris'; nested exception is java.lang.NumberFormatException: For input string: "Cris"

O código completo está no github: (GitHub - IvoLeonardo/Agenda: Projeto que continha erro, mas que foi corrigido.)

Grato.
Abaixo segue um pouco dos códigos.

    package br.com.ilsc.agenda.modelo;

    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;
    import javax.persistence.Table;

    @Entity
    @Table(name = "contatos")
    public class Contato {

    	@Id
    	@GeneratedValue(strategy = GenerationType.IDENTITY)
    	private Long id;
    	private String contato;

    	public Long getId() {
    		return id;
    	}

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

    	public String getContato() {
    		return contato;
    	}

    	public void setContato(String contato) {
    		this.contato = contato;
    	}

    }
    package br.com.ilsc.agenda.controller;

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.servlet.ModelAndView;

    import br.com.ilsc.agenda.modelo.Contato;
    import br.com.ilsc.agenda.repository.ContatoRepository;

    @Controller
    public class IndexController {

    	@Autowired
    	private ContatoRepository contatoRepository;

    	@GetMapping("/")
    	public ModelAndView inicio() {
    		ModelAndView mv = new ModelAndView("index");
    		mv.addObject("contatoObj", new Contato());
    		mv.addObject("contatos", contatoRepository.findAll());

    		return mv;
    	}

    	@PostMapping("salvarContato")
    	public ModelAndView salvar(Contato contato) {

    		contatoRepository.save(contato);

    		ModelAndView mv = new ModelAndView("index");
    		mv.addObject("contatoObj", new Contato());
    		mv.addObject("contatos", contatoRepository.findAll());

    		return mv;
    	}
    }
    <!DOCTYPE html>
    <html lang="pt-br">
    	<head>
    		<meta charset="utf-8">
    		<title>Index</title>
    	</head>
    	
    	<body>
    	
    		<form action="salvarContato" method="post" th:object="${contatoObj}">
    		
    			<input type="hidden" name="id" th:field="*{id}">
    		
    			<label>Nome</label>
    			<input type="text" name="contato" th:field="*{contato}">
    			<input type="submit" value="salvar">
    		</form>
    		
    		<table>
    			<tr>
    				<th>Código</th><th>Nome do contato</th>
    			</tr>
    			<tr th:each="c : ${contatos}">
    				<td th:text="${c.id}"></td>
    				<td th:text="${c.contato}"></td>
    			</tr>
    		</table>
    	</body>
    </html>
    package br.com.ilsc.agenda.repository;

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

    import br.com.ilsc.agenda.modelo.Contato;

    public interface ContatoRepository extends JpaRepository<Contato, Long> {

    }
    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    	<modelVersion>4.0.0</modelVersion>
    	<parent>
    		<groupId>org.springframework.boot</groupId>
    		<artifactId>spring-boot-starter-parent</artifactId>
    		<version>2.4.2</version>
    		<relativePath/> <!-- lookup parent from repository -->
    	</parent>
    	<groupId>br.com.ilsc</groupId>
    	<artifactId>agenda</artifactId>
    	<version>0.0.1-SNAPSHOT</version>
    	<name>agenda</name>
    	<description>Demo project for Spring Boot</description>
    	<properties>
    		<java.version>1.8</java.version>
    	</properties>
    	<dependencies>
    		<dependency>
    			<groupId>org.springframework.boot</groupId>
    			<artifactId>spring-boot-starter-data-jpa</artifactId>
    		</dependency>
    		<dependency>
    			<groupId>org.springframework.boot</groupId>
    			<artifactId>spring-boot-starter-thymeleaf</artifactId>
    		</dependency>
    		<dependency>
    			<groupId>org.springframework.boot</groupId>
    			<artifactId>spring-boot-starter-web</artifactId>
    		</dependency>

    		<dependency>
    			<groupId>org.springframework.boot</groupId>
    			<artifactId>spring-boot-devtools</artifactId>
    			<scope>runtime</scope>
    			<optional>true</optional>
    		</dependency>
    		<dependency>
    			<groupId>mysql</groupId>
    			<artifactId>mysql-connector-java</artifactId>
    		</dependency>
    		<dependency>
    			<groupId>org.springframework.boot</groupId>
    			<artifactId>spring-boot-starter-test</artifactId>
    			<scope>test</scope>
    		</dependency>
    	</dependencies>

    	<build>
    		<plugins>
    			<plugin>
    				<groupId>org.springframework.boot</groupId>
    				<artifactId>spring-boot-maven-plugin</artifactId>
    			</plugin>
    		</plugins>
    	</build>

    </project>

Posta o StackTrace completo

Olá, staroski.
Grato pelo contato.
Segue o erro completo:

Whitelabel Error Page

This application has no explicit mapping for /error, so you are seeing this as a fallback.
Fri Jun 11 15:11:20 AMT 2021
There was an unexpected error (type=Bad Request, status=400).
Failed to convert value of type 'java.lang.String' to required type 'br.com.ilsc.agenda.modelo.Contato'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.lang.Long] for value 'Cris'; nested exception is java.lang.NumberFormatException: For input string: "Cris"
org.springframework.beans.TypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'br.com.ilsc.agenda.modelo.Contato'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.lang.Long] for value 'Cris'; nested exception is java.lang.NumberFormatException: For input string: "Cris"
	at org.springframework.beans.TypeConverterSupport.convertIfNecessary(TypeConverterSupport.java:79)
	at org.springframework.beans.TypeConverterSupport.convertIfNecessary(TypeConverterSupport.java:53)
	at org.springframework.validation.DataBinder.convertIfNecessary(DataBinder.java:696)
	at org.springframework.web.servlet.mvc.method.annotation.ServletModelAttributeMethodProcessor.createAttributeFromRequestValue(ServletModelAttributeMethodProcessor.java:142)
	at org.springframework.web.servlet.mvc.method.annotation.ServletModelAttributeMethodProcessor.createAttribute(ServletModelAttributeMethodProcessor.java:78)
	at org.springframework.web.method.annotation.ModelAttributeMethodProcessor.resolveArgument(ModelAttributeMethodProcessor.java:142)
	at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:121)
	at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:170)
	at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
	at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106)
	at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:894)
	at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808)
	at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
	at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1060)
	at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:962)
	at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
	at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:652)
	at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:733)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
	at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
	at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
	at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
	at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
	at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542)
	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143)
	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
	at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:374)
	at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
	at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:888)
	at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1597)
	at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
	at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130)
	at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630)
	at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
	at java.base/java.lang.Thread.run(Thread.java:832)
Caused by: org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.lang.Long] for value 'Cris'; nested exception is java.lang.NumberFormatException: For input string: "Cris"
	at org.springframework.core.convert.support.ConversionUtils.invokeConverter(ConversionUtils.java:47)
	at org.springframework.core.convert.support.GenericConversionService.convert(GenericConversionService.java:192)
	at org.springframework.core.convert.support.GenericConversionService.convert(GenericConversionService.java:175)
	at org.springframework.data.repository.support.DomainClassConverter$ToEntityConverter.convert(DomainClassConverter.java:177)
	at org.springframework.data.repository.support.DomainClassConverter.lambda$convert$0(DomainClassConverter.java:85)
	at java.base/java.util.Optional.map(Optional.java:258)
	at org.springframework.data.repository.support.DomainClassConverter.convert(DomainClassConverter.java:85)
	at org.springframework.core.convert.support.ConversionUtils.invokeConverter(ConversionUtils.java:41)
	at org.springframework.core.convert.support.GenericConversionService.convert(GenericConversionService.java:192)
	at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:129)
	at org.springframework.beans.TypeConverterSupport.convertIfNecessary(TypeConverterSupport.java:73)
	... 52 more
Caused by: java.lang.NumberFormatException: For input string: "Cris"
	at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)
	at java.base/java.lang.Long.parseLong(Long.java:707)
	at java.base/java.lang.Long.valueOf(Long.java:1159)
	at org.springframework.util.NumberUtils.parseNumber(NumberUtils.java:214)
	at org.springframework.core.convert.support.StringToNumberConverterFactory$StringToNumber.convert(StringToNumberConverterFactory.java:64)
	at org.springframework.core.convert.support.StringToNumberConverterFactory$StringToNumber.convert(StringToNumberConverterFactory.java:50)
	at org.springframework.core.convert.support.GenericConversionService$ConverterFactoryAdapter.convert(GenericConversionService.java:437)
	at org.springframework.core.convert.support.ConversionUtils.invokeConverter(ConversionUtils.java:41)
	... 62 more

Tente colocar a anotação @ModelAttribute no parâmetro do método salvar:

public ModelAndView salvar(@ModelAttribute Contato contato) {

Olá, @Lucas_Camara!
Grato por contribuir.
eu acrescentei a anotação
@ModelAttribute, porém não funcionou. O mesmo erro continua.

Tente seguir e exemplo desse link: https://spring.io/guides/gs/handling-form-submission/

Olá, @Lucas_Camara! Agradeço por contribuir com o link. Vou pesquisar com calma.

Como eu disse no início, eu tenho um outro projeto que funciona. Comparei os códigos dos dois e não encontrei o erro.
Eu ainda estou nas fases iniciais de aprendizado com Spring.

Inseri os arquivos com códigos do projeto que funciona ao projeto que apresenta erro, e advinha: agora no mesmo projeto a parte antiga não funciona e o que acrescentei funciona e ainda não sei onde está a falha. Parece que fiz tudo certo, mas eu sei que não.

O @staroski pediu que eu postasse o erro completo e já está postado acima.

No navegador apresenta o erro 400:
There was an unexpected error (type=Bad Request, status=400).

E as excessões:
org.springframework.beans.TypeMismatchException,

Caused by: org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.lang.Long] for value ‘Cris’; nested exception is java.lang.NumberFormatException: For input string: “Cris”,

Caused by: java.lang.NumberFormatException: For input string: “Cris”

Estou fazendo pesquisas para resolver isso.
Se alguém puder me ajudar eu agradeço.

Olá @Lucas_Camara e @staroski resolvi o problema. Ufa!

Na classe Contato havia um atributo de classe do tipo String e com o mesmo nome da classe: contato. Alterei o nome do atributo para nomeContato e funcionou.

Agradeço pela colaboração de vocês.

1 curtida