Galera, estou com uma duvida meia chata e é o seguinte: Já consigo recuperar meu objeto da Tabela e montar no formulário, ao modifiicar e atualizar ele está criando um novo objeto. Segue meu codigo.
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Atualização de Tarefa</title>
<link href="css/jquery-ui.min.css" rel="stylesheet">
<link href="css/estilo.css" rel="stylesheet">
<script src="js/jquery.js"></script>
<script src="js/jquery-ui.min.js"></script>
</head>
<body>
<h3>Atualização de Tarefa - ${tarefa.id}</h3>
<form action="mvc?logica=AdicionaAlteraTarefaLogic" method="post">
Data: <input type="text" name="data" value="<fmt:formatDate value="${tarefa.data.time}" pattern="dd/MM/yyyy" />" /> <br />
Descricao: <textarea rows="7" cols="20" name="descricao">${tarefa.descricao}</textarea> <br>
<input type="submit" value="Atualizar">
</form>
</body>
</html>
public class AdicionaAlteraTarefaLogic implements Logica {
@Override
public String executa(HttpServletRequest request, HttpServletResponse response) {
Integer numId;
String id = request.getParameter("id");
String data = request.getParameter("data");
String descricao = request.getParameter("descricao");
Calendar dataTarefa = Calendar.getInstance();
try {
Date dataconvertida = new SimpleDateFormat("dd/MM/yyyy").parse(data);
dataTarefa.setTime(dataconvertida);
Tarefa tarefa = new Tarefa();
tarefa.setData(dataTarefa);
tarefa.setDescricao(descricao);
TarefaDAO dao = new TarefaDAO();
if(id != null){
numId = Integer.parseInt(id);
tarefa.setId(numId);
dao.atualizaTarefa(tarefa);
}else{
dao.adiciona(tarefa);
}
} catch (ParseException | SQLException e) {
e.printStackTrace();
}
return "mvc?logica=ListarTarefaLogic";
}
}
public void adiciona(Tarefa tarefa) {
String sql = "insert into tarefa(descricao,data) values (?,?) ";
try (PreparedStatement stmt = connection.prepareStatement(sql)) {
montaTarefa(tarefa, stmt);
stmt.execute();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
private void montaTarefa(Tarefa tarefa, PreparedStatement stmt) throws SQLException {
stmt.setString(1, tarefa.getDescricao());
stmt.setDate(2, new Date(tarefa.getData().getTimeInMillis()));
}
public void atualizaTarefa(Tarefa tarefa){
String sql = "update tarefa set descricao = ?, data = ? where id = ?";
try (PreparedStatement pstm = connection.prepareStatement(sql)){
pstm.setString(1, tarefa.getDescricao());
pstm.setDate(2, new Date(tarefa.getData().getTimeInMillis()));
pstm.setInt(3, tarefa.getId());
pstm.execute();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}