【Web实战-Tomcat-Servlet-Thymeleaf -JDBC-MySQL】浏览器页面显示数据库数据(水果库存系统)
以下是一个简化的代码示例,展示了如何在Servlet中使用JDBC查询MySQL数据库,并通过Thymeleaf在浏览器中显示结果。
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.templatemode.TemplateMode;
import org.thymeleaf.templateresolver.ServletContextTemplateResolver;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
@WebServlet("/showData")
public class ShowDataServlet extends HttpServlet {
private TemplateEngine templateEngine;
@Override
public void init() throws ServletException {
super.init();
ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(getServletContext());
templateResolver.setTemplateMode(TemplateMode.HTML);
templateResolver.setPrefix("/WEB-INF/templates/");
templateResolver.setSuffix(".html");
templateEngine = new TemplateEngine();
templateEngine.setTemplateResolver(templateResolver);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
List<String> dataList = new ArrayList<>();
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try {
// 加载并注册JDBC驱动
Class.forName("com.mysql.cj.jdbc.Driver");
// 打开连接
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "username", "password");
// 执行查询
statement = connection.createStatement();
resultSet = statement.executeQuery("SELECT data FROM mytable");
// 遍历结果集
while (resultSet.next()) {
dataList.add(resultSet.getString("data"));
}
} catch (ClassNotFoundException | SQLException e) {
// 处理JDBC错误
e.printStackTrace();
} finally {
// 关闭资源
if (resultSet != null) resultSet.close();
if (statement != null) statement.close();
if (connection != null) connection.close();
}
// 设置请求属性,以便Thymeleaf可以处理它
评论已关闭