我有一个问题,我在 DATE 中有一些日期存储在 SQL 中,但是我无法获取日/月/年格式的日期(带 /),并且当有一个日期不存在时,我无法获取 null '不存在,它没有显示给我。
我正在使用 MySQL,查询的结果显示在一个表中。
让我们看看你能不能告诉我如何处理它。
我做的道如下:
public ArrayList<Prestamo> selectPrestamo() throws Exception {
ArrayList<Prestamo> prestamos = null;
try (Connection connection = DBConnection.get()) {
if (connection == null) {//si la conexión es nula lanza una excepción
throw new Exception("Connection is null");
}
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery("SELECT * FROM prestamo");
prestamos = new ArrayList();
while (rs.next()) {
Prestamo prestamo = new Prestamo(rs.getInt("id"), rs.getString("DNIusuario"),
rs.getString("ISBNobra"), rs.getDate("Fechasolicitud"),
rs.getDate("Fechadevolucion"));
prestamos.add(prestamo);
}
} catch (Exception ex) {
throw ex;
} finally {
DBConnection.close();
}
return prestamos;
}
这是jsp表
<%@page import="java.util.List"%>
<%@page import="Entidades.Prestamo"%>
<%@page import="DAO.DAOPrestamo"%>
<%@page import="Conexion.DBConnection"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<jsp:useBean id="prestamo" class="Entidades.Prestamo" />
<jsp:setProperty name="prestamo" property="*"/>
<%
String message = "";//por si hay que mandar un mensaje de error
List<Prestamo> prestamos = null;
DAOPrestamo dao = new DAOPrestamo();
try {
prestamos = dao.selectPrestamo();
} catch (Exception ex) {
message = ex.toString();
}
%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>formListarPrestamo</title>
<link href="../css/estilos.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div class="titulo">
<h1>BIBLIOTECA - PRESTAMOS</h1>
<div id="menu">
<div id="opciones">
<h2><a href="../Menu.jsp">Inicio</a></h2>
<h2><a href="V2HojaPrestamos.jsp">Atras</a></h2>
</div>
<form>
<%if (!message.isEmpty()) {%>
<input name="status_initial" type="text" style="width:400px" value="<%=message%>"/>
<%} else { %>
<br/><br/>
<table border="1">
<tr>
<th>id</th>
<th>DNI Usuario</th>
<th>ISBN Obra</th>
<th>Fecha Solicitud</th>
<th>Fecha Devolucion</th>
</tr>
<!--creación de una tabla para mostrar todos los objetos prestamo-->
<%
for (int i = 0; i < prestamos.size(); i++) {%>
<tr>
<td><%=prestamos.get(i).getId()%></td>
<td><%=prestamos.get(i).getDNIusuario()%></td>
<td><%=prestamos.get(i).getISBNobra()%></td>
<td><%=prestamos.get(i).getFechasolicitud()%></td>
<td><%=prestamos.get(i).getFechadevolucion()%></td>
</tr>
<%}%>
</table>
<%}%>
</form>
</div>
</div>
</body>
最初我看到它是一个非常基本的 JSP 页面,实际上你没有使用任何框架,这还不错,我想这是一个学术练习……我会沿着这条线继续。
鉴于您的代码结构,我建议您使用静态方法实现一个实用程序类,该方法允许您将日期转换为所需的格式,否则在日期为 NULL 的情况下返回一个空字符串。
要将日期转换为所需的格式,正确的做法是使用 SimpleDateFormat 类,这允许您构建一个生成日期的模式,我建议您阅读文档以便更清楚地了解它(https: //docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html )
原则上,该方法可能是这样的:
有了以上内容,只需在 JSP 中完成您的任务就足够了,您应该进行一些更改,例如导入实用程序类,另一方面,在表中使用它,如下所示:
现在,这一切都取决于你想去哪里,你可以做一些更通用的事情,甚至向实用函数添加一个参数,如下所示:
使用这种方法,您不仅可以传递日期,还可以传递所需的格式,因此您可以在其他场合重复使用此实用程序。这将是它的用途: