Я пытаюсь показать данные пользователя, которые я собираюсь обновить.
В моей структуре я ввожу dni, который извлекается при просмотре списка, чтобы затем показать данные пользователя, в частности, в другомформа.При отправке этой формы данные будут постоянно обновляться.
Проблема, с которой я столкнулся, заключается в том, что я не знаю, как отобразить данные пользователя, которые я искал ранее.PE: Я ищу пользователя по имени Jhon Doe с DNI 11111111E, во второй форме у меня будет новая форма с именем и фамилией Jhon Doe, теперь я пишу в эти поля формы Mike Doe и нажимаю submmit.
Проблема: я не знаю, как показать старое имя в моей форме (я не знаю, как показать Джона Доу).
Вот мой код, теперь я застрял в этомчастично, это обновление в порядке, но имя не отображается)
Я добавил свою веб-страницу jsp, чтобы посмотреть, как они работают, но в любом случае моя проблема заключается в том, как мне удается показать дату изпользователь, который будет обновлен.
Моя первая страница JSP здесь (V2formModificarUsuario1.jsp)
<%@page import="java.util.List"%>
<%@page import="Entidades.Usuario"%>
<%@page import="DAO.DAOUsuario"%>
<%@page import="Conexion.DBConnection"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<jsp:useBean id="usuario" class="Entidades.Usuario" />
<jsp:setProperty name="usuario" property="*"/>
<%
String message = "";
List<Usuario> usuarios = null;
DAOUsuario dao = new DAOUsuario();
try {
//usuarios = dao.selectUsuario("si","nombre");
usuarios = dao.selectAllUsuarios();
} catch (Exception ex) {
message = ex.toString();
}
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>V2formListarUsuariosAltaNombre</title>
<link href="../css/estilos.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div class="titulo">
<h1>BIBLIOTECA - LISTADOS USUARIOS</h1>
<div id="menu">
<div id="opciones">
<h2><a href="../Menu.jsp">Menu inicial</a></h2>
<h2><a href="V2HojaUsuarios.jsp">Atras</a></h2>
</div>
<form id="formulario" action="V2formModificarUsuario2(en obras).jsp" method="POST">
<label for="DNI">Intruduzca DNI del usuario</label><br>
DNI: <input type="text" name="DNI" required="">
<input type="submit" value="buscar">
</form>
<form>
<%if (!message.isEmpty()) {%>
<input name="status_initial" type="text" style="width:400px" value="<%=message%>"/>
<%} else { %>
<br/><br/>
<table border="1">
<tr>
<th>DNI</th>
<th>nombre</th>
<th>apellidos</th>
<th>de alta</th>
</tr>
<%for (int i = 0; i < usuarios.size(); i++) {%>
<tr>
<td><%=usuarios.get(i).getDNI()%></td>
<td><%=usuarios.get(i).getNombre()%></td>
<td><%=usuarios.get(i).getApellidos()%></td>
<td><%=usuarios.get(i).getDeAlta()%></td>
</tr>
<%}%>
</table>
<%}%>
</form>
</div>
</div>
</body>
Моя вторая страница JSP здесь (V2formModificarUsuario2.jsp)
<%@page import="java.util.ArrayList"%>
<%@page import="java.util.List"%>
<%@page import="Entidades.Usuario"%>
<%@page import="DAO.DAOUsuario"%>
<%@page import="Conexion.DBConnection"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<jsp:useBean id="usuario" class="Entidades.Usuario"></jsp:useBean>
<jsp:setProperty name="usuario" property="*"/>
<%
String message = "";
// String nameToChange = "";
String surnameToChange = "";
try {
if ((usuario.getDNI() != null) && (!usuario.getDNI().isEmpty())) {
DAOUsuario dao = new DAOUsuario();
// nameToChange=dao.selectByDNI(request.getParameter("DNI")).getNombre(); comentado por ahora
surnameToChange=dao.selectByDNI(request.getParameter("DNI")).getApellidos();
Usuario usuarios = dao.selectByDNI(usuario.getDNI());
if (usuarios != null) {
if ((usuario.getNombre() != null) && (!usuario.getNombre().isEmpty())
&& (usuario.getApellidos() != null) && (!usuario.getApellidos().isEmpty())) {
dao.update(usuario.getDNI(), usuario.getNombre(), usuario.getApellidos());
message = "User correctly updated.";
} else {
if (request.getParameter("updating") == "1") {
message = "Los campos name, surname and deAlta are required .";
}
}
} else {
message = "user do not exists.";
}
} else {
message = "DNI must not be null.";
}
} catch (Exception ex) {
message = ex.getMessage();
}
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSPformModificarUsuario2(en obras)</title>
<link href="css/estilos.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div class="titulo">
<h1>BIBLIOTECA - USUARIO</h1>
<div id="menu">
<div id="opciones">
<h2><a href="index.jsp">Inicio</a></h2>
</div>
<form method="POST" action="V2formModificarUsuario2(en obras).jsp">
<input name="updating" type="hidden" value="1"/>
<%if (!message.isEmpty()) {%>
<input name="message" type="text" style="width:400px" value="<%=message%>"/>
<%} else { %>
<br/><br/>
DNI:
<input name="DNI" type="text" style="width:200px" value="<jsp:getProperty property="DNI" name="usuario"/>" readonly=""/>
<br/><br/>
nombre:
<input name="nombre" type="text" style="width:200px" placeholder="<%=apellidoActualizar%>" value="<jsp:getProperty property="nombre" name="usuario"/>"/>
<br/><br/>
apellidos:
<input name="apellidos" type="text" style="width:200px" value="<jsp:getProperty property="apellidos" name="usuario"/>"/>
<br/><br/>
<input type="submit" value="Actualizar"/>
<%}%>
</form>
</div>
</div>
</body>
И, наконец, мой DAO здесь.
public Usuario update(String DNI, String nombre, String apellidos) throws Exception {
if ((DNI == null) || (DNI.isEmpty())) {
throw new Exception("DNI must not be null");
}
if ((nombre == null) || (nombre.isEmpty())) {
throw new Exception("name must not be null");
}
if ((apellidos == null) || (apellidos.isEmpty())) {
throw new Exception("surname must not be null");
}
Usuario usuario = selectByDNI(DNI);
if (usuario == null) {
throw new Exception("user do not exist");
}
try (Connection connection = DBConnection.get()) {
if (connection == null) {
throw new Exception("Connection is null");
}
String query = "UPDATE usuario SET nombre=?, apellidos=? WHERE DNI=?";
PreparedStatement statement = connection.prepareStatement(query);
statement.setString(1, nombre);
statement.setString(2, apellidos);
statement.setString(3, DNI);
statement.execute();
} catch (Exception ex) {
throw ex;
} finally {
DBConnection.close();
}
usuario = selectByDNI(DNI);
return usuario;
}
public Usuario selectByDNI(String DNI) throws Exception {
if ((DNI == null) || (DNI.isEmpty())) {
return null;
}
Usuario usuario = null;
try (Connection connection = DBConnection.get()) {
if (connection == null) {
throw new Exception("Connection is null");
}
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery("SELECT * FROM usuario WHERE DNI = '" + DNI + "'");
if (rs.next()) {
usuario = new Usuario(rs.getString("DNI"), rs.getString("nombre"),
rs.getString("apellidos"), rs.getString("deAlta"));
}
} catch (Exception ex) {
throw ex;
} finally {
DBConnection.close();
}
return usuario;
}