javaweb 从数据库读取数据的详细操作
生活随笔
收集整理的這篇文章主要介紹了
javaweb 从数据库读取数据的详细操作
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
文章目錄
- 前言
- 一、第一步創(chuàng)建bean包
- 二、第二步創(chuàng)建dao包
- 三、創(chuàng)建servlet
- 四、創(chuàng)建jsp文件,用來取數(shù)據(jù)并顯示
前言
從數(shù)據(jù)庫讀取數(shù)據(jù)的詳細(xì)操作,用購物車案例作為例子
提示:以下是本篇文章正文內(nèi)容,下面案例可供參考
一、第一步創(chuàng)建bean包
可以先寫物品屬性,例如商品有編號、名稱、價(jià)格
private Integer id; private String name; private Double price;再使用快捷鍵alt+shift+s 創(chuàng)建默認(rèn)構(gòu)造函數(shù)、帶參數(shù)構(gòu)造器、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;}}二、第二步創(chuàng)建dao包
三、創(chuàng)建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();//創(chuàng)建GoodsDao的對象List<Goods> goods=dao.find();//調(diào)用find方法request.setAttribute("goods", goods);//放到request域中request.getRequestDispatcher("/shopping/index.jsp").forward(request, response);//轉(zhuǎn)發(fā)給shopping/index.jsp}protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet(request, response);}}四、創(chuàng)建jsp文件,用來取數(shù)據(jù)并顯示
取出request域中的數(shù)據(jù)(這個(gè)數(shù)據(jù)是Goods的鏈表,request域中取出的object類型,需要強(qiáng)轉(zhuǎn)一下)
使用jsp拼接語句,達(dá)到循環(huán)讀取數(shù)據(jù)
以上為從數(shù)據(jù)庫讀取數(shù)據(jù)的詳細(xì)操作。
歡迎訪問我的個(gè)人博客http://dzyblog.xyz/有更好的閱讀體驗(yàn)
總結(jié)
以上是生活随笔為你收集整理的javaweb 从数据库读取数据的详细操作的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Integer的值范围-128~127
- 下一篇: LittleVGL(LVGL)学习笔记—