Erro ao converter a data - 11.16 Exercício: Removendo e Alterando tarefas

1 resposta
java
M

Mais uma vez estou buscando a ajuda de vocês para problemas com meus estudos em java, estou seguindo a apostila da Caelum fj21 - web e no exercício “11.16 Exercício: Removendo e Alterando tarefas”. estou tendo problemas para alterar as tarefas cadastradas. Sempre que tento aletrar uma tarefa recebo a seguinte mensagem de erro:

HTTP Status 500 - Request processing failed; nested exception is org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 2 errors

type Exception report

message Request processing failed; nested exception is org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 2 errors

description The server encountered an internal error that prevented it from fulfilling this request.

exception

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 2 errors

Field error in object tarefa on field dataFinalizacao’: rejected value [01/011111]; codes [typeMismatch.tarefa.dataFinalizacao,typeMismatch.dataFinalizacao,typeMismatch.java.util.Calendar,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [tarefa.dataFinalizacao,dataFinalizacao]; arguments []; default message [dataFinalizacao]]; default message [Failed to convert property value of type ‘java.lang.String’ to required type ‘java.util.Calendar’ for property ‘dataFinalizacao’; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type java.lang.String to type @org.springframework.format.annotation.DateTimeFormat java.util.Calendar for value ‘01/011111’; nested exception is java.lang.IllegalStateException: JodaTime library not available - @DateTimeFormat not supported]

Field error in object tarefa on field id’: rejected value [21"/]; codes [<a href="http://typeMismatch.tarefa.id">typeMismatch.tarefa.id</a>,<a href="http://typeMismatch.id">typeMismatch.id</a>,typeMismatch.int,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [<a href="http://tarefa.id">tarefa.id</a>,id]; arguments []; default message [id]]; default message [Failed to convert property value of type ‘java.lang.String’ to required type ‘int’ for property ‘id’; nested exception is java.lang.NumberFormatException: For input string: “21”/"]

org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:894)

org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:789)

javax.servlet.http.HttpServlet.service(HttpServlet.java:650)

javax.servlet.http.HttpServlet.service(HttpServlet.java:731)

org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

root cause

org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 2 errors

Field error in object tarefa on field dataFinalizacao’: rejected value [01/011111]; codes [typeMismatch.tarefa.dataFinalizacao,typeMismatch.dataFinalizacao,typeMismatch.java.util.Calendar,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [tarefa.dataFinalizacao,dataFinalizacao]; arguments []; default message [dataFinalizacao]]; default message [Failed to convert property value of type ‘java.lang.String’ to required type ‘java.util.Calendar’ for property ‘dataFinalizacao’; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type java.lang.String to type @org.springframework.format.annotation.DateTimeFormat java.util.Calendar for value ‘01/011111’; nested exception is java.lang.IllegalStateException: JodaTime library not available - @DateTimeFormat not supported]

Field error in object tarefa on field id’: rejected value [21"/]; codes [<a href="http://typeMismatch.tarefa.id">typeMismatch.tarefa.id</a>,<a href="http://typeMismatch.id">typeMismatch.id</a>,typeMismatch.int,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [<a href="http://tarefa.id">tarefa.id</a>,id]; arguments []; default message [id]]; default message [Failed to convert property value of type ‘java.lang.String’ to required type ‘int’ for property ‘id’; nested exception is java.lang.NumberFormatException: For input string: “21”/"]

org.springframework.web.method.annotation.ModelAttributeMethodProcessor.resolveArgument(ModelAttributeMethodProcessor.java:111)

org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:75)

org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:156)

org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:117)

org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:96)

org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:617)

org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:578)

org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)

org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923)

org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852)

org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)

org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:789)

javax.servlet.http.HttpServlet.service(HttpServlet.java:650)

javax.servlet.http.HttpServlet.service(HttpServlet.java:731)

org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

note The full stack trace of the root cause is available in the Apache Tomcat/7.0.75 logs.
Apache Tomcat/7.0.75

minhas classes estão dessa forma:

Classe Controladora.

public class TarefaController {

... Outros métodos
Adiciona, lista, remove...

@RequestMapping("mostraTarefa")
	public String mostra(int id, Model model){
		
		TarefaDao tarefDao = new TarefaDao();
		
		model.addAttribute("tarefa", tarefDao.buscaTarefa(id));
		
		return "tarefas/mostra";
		
	}
	
	@RequestMapping("alteraTarefa")
	public String altera(Tarefa tarefa){
		
		TarefaDao tarefDao = new TarefaDao();
		
		tarefDao.alteratarefa(tarefa);
		
		return "redirect:listaTarefas";
		
	}

}

Classe Tarefa.

public class Tarefa {
	
	private int id;
	
	@NotNull @Size(min=5)
	private String descricao;
	private boolean finalizado;
	
	@DateTimeFormat(pattern="dd/MM/yyyy")
	private Calendar dataFinalizacao;

Getters and Setters...

Classe altera tarefas.jsp

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

 <h3>Altera Tarefas - ${tarefa.id}</h3>
 
 <form action="alteraTarefa" method="post">
 
 	<input type="hidden" name="id" value=${tarefa.id}"/>
 	
 	Descrição:<br />
 	<textarea name="descricao" cols="100" rows="5" ${tarefa.descricao}></textarea>
 	<br />
 	
 	Finalizado?:<br />
 	<input type="checkbox" name="finalizado" value="true" ${tarefa.finalizado? 'checked' : ''}> <br />
 	
 	Data Finalização:<br />
 	<input type="text" name="dataFinalizacao" value="<fmt:formatDate value="${tarefa.dataFinalizacao.time}" pattern="dd/MM/yyyy"/>"/> 
 	
 	<input type="submit" value="Alterar">
 </form>

</body>
</html>

Não sei o que está ocorrendo de errado, Alguém por favor pode me dar uma dica de onde posso está errando?

Antecipadamente agradeço.

1 Resposta

M

Pessoal,
Consegui resolver meu problema usando esse código aqui. Quem estiver com o mesmo problema pode tentar essa solução.

Segue…

// Coloquei esse método no meu controlador e funcionou!

@InitBinder

public void initBinder(WebDataBinder binder) {

binder.registerCustomEditor(Calendar.class, new PropertyEditorSupport() {
@Override
    public void setAsText(String value) {

        try {
            Calendar cal = Calendar.getInstance();
            cal.setTime(new SimpleDateFormat("dd/MM/yyyy").parse(value));
            setValue(cal);

        } catch (ParseException e) {
            setValue(null);
        }
    }

    @Override
    public String getAsText() {
        if (getValue() == null) {
            return "";
        }
        return new SimpleDateFormat("dd/MM/yyyy").format(((Calendar) getValue()).getTime());
    }
});

}

Criado 8 de maio de 2017
Ultima resposta 9 de mai. de 2017
Respostas 1
Participantes 1