前言

从数据库读取数据的详细操作,用购物车案例作为例子


提示:以下是本篇文章正文内容,下面案例可供参考
在这里插入图片描述
在这里插入图片描述

一、第一步创建bean包

可以先写物品属性,例如商品有编号、名称、价格

private Integer id;
private String name;
private Double price;

再使用快捷键alt+shift+s 创建默认构造函数、带参数构造器、get和set方法

package javaweb.bean;

public class Goods {
	private Integer id;
	private String name;
	private Double price;
	
	public Goods() {
		super();
	}

	public Goods(Integer id, String name, Double price) {
		super();
		this.id = id;
		this.name = name;
		this.price = price;
	}
	
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Double getPrice() {
		return price;
	}
	public void setPrice(Double price) {
		this.price = price;
	}
	
}

二、第二步创建dao包


  1. 创建bean的链表,用来接收数据
  2. 3-7是使用用jdbc查询数据库数据的操作
  3. 先连上数据库
  4. 使用username ,password登录
  5. 创建sql语句
  6. 执行sql语句
  7. 取结果集
  8. 用bean创建对象,将取出来的数据封装到在里面
  9. 将封装的数据加到先前创建的list里
  10. 返回list(因为是在一个函数里面写的,所以可以返回值便于后面接收值使用)
package javaweb.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import cn.hutool.json.JSONArray;
import javaweb.bean.Goods;

public class GoodsDao {
	public List<Goods> find(){
		List<Goods> list=new ArrayList<Goods>();//创建bean的链表,用来接收数据
		Connection conn=null;//先连上数据库
		PreparedStatement pstmt=null;
		ResultSet rs=null;
		try {
			Class.forName("com.mysql.jdbc.Driver");
			String url = "jdbc:mysql://localhost:3306/javaweb?useUnicode=true&characterEcoding=utf-8";
			String username = "root";
			String password = null;
			conn=DriverManager.getConnection(url,username,password);//使用username ,password登录
			String sql="select id,name,price from t_goods";//创建sql语句
			pstmt=conn.prepareStatement(sql);//执行sql语句
			
			rs=pstmt.executeQuery();//取结果集
			while(rs.next()) {
				Goods i=new Goods();//用bean创建对象,将取出来的数据封装到在里面
				i.setId(rs.getInt(1));
				i.setName(rs.getString(2));
				i.setPrice(rs.getDouble(3));
				list.add(i);//将封装的数据加到先前创建的list里
			}
		} catch (Exception e) {
			// TODO: handle exception
		}finally {//使用完,要关闭连接
			if(pstmt!=null) {
				try {
					pstmt.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if(conn!=null) {
				try {
					conn.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return list;
	}
}

三、创建servlet

package javaweb.servlet;

import java.io.IOException;
import java.util.List;

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 cn.hutool.json.JSONArray;
import javaweb.bean.Goods;
import javaweb.dao.GoodsDao;

@WebServlet("/shopping/index")
public class ShoppingServlet extends HttpServlet {
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		GoodsDao dao=new GoodsDao();//创建GoodsDao的对象
		List<Goods> goods=dao.find();//调用find方法
		request.setAttribute("goods", goods);//放到request域中
		request.getRequestDispatcher("/shopping/index.jsp").forward(request, response);//转发给shopping/index.jsp
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}

四、创建jsp文件,用来取数据并显示

  1. 取出request域中的数据(这个数据是Goods的链表,request域中取出的object类型,需要强转一下)

  2. 使用jsp拼接语句,达到循环读取数据

<%@page import="java.util.List"%>
<%@page import="javaweb.bean.Goods"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>小红帽商城</title>
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/layui/css/layui.css">
<script type="text/javascript" src="${pageContext.request.contextPath }/layui/layui.js"></script>
</head>
<body>
<div class="layui-bg-red">
	<div class="layui-container">
		<h3 class="layui-inline ">小红帽商城</h3>
		<div class="layui-nav layui-inline layui-bg-red">
			<div class="layui-nav-item">
				<a href="${pageContext.request.contextPath}/shopping">商城首页</a>
			</div>
		</div>
	</div>
</div>
	<div class="layui-container">
		<table class="layui-table">
			<thead>
			<tr>
				<th>编号</th><th>商品名称</th><th>价格</th><th></th>
			</tr>
			</thead>
			<tbody>
				<%
            		<%--使用jsp拼接语句,达到循环读取数据--%>
					List<Goods> goods =(List<Goods>)request.getAttribute("goods");
					for(Goods i:goods){
				%>
				<tr>
					<td><%=i.getId() %></td>
					<td><%=i.getName() %></td>
					<td><%=i.getPrice()%></td>
					<td style="width:140px;text-align:center;">
						<form action="${pageContext.request.contextPath}/shopping/add" 
                    class="layui-form layui-inline">
							<input type="text" value="1" name="number" style="width:60px;" 
                       class="layui-input layui-input-inline">
							<button type="submit" class="layui-btn layui-bg-red ">
								<i class="layui-icon layui-icon-cart"></i>
							</button>						
						</form>
					</td>
				</tr>
				<%
					}
				%>
			</tbody>
		</table>
	</div>
</body>
</html>

以上为从数据库读取数据的详细操作。
欢迎访问我的个人博客http://dzyblog.xyz/有更好的阅读体验

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐