Struts2學習筆記NO.1------結合Hibernate完成查詢商品類別簡單案例(工具IDEA)

来源:https://www.cnblogs.com/sanmaotage/archive/2018/01/26/8361677.html
-Advertisement-
Play Games

用Struts和Hibernate完成簡單的查詢資料庫,顯示類別信息的簡單案例 ...


    Struts2學習筆記一結合Hibernate完成查詢商品類別簡單案例(工具IDEA)

1.jar包准備

Hibernate+Struts2 jar包

struts的jar比較多,可以從Struts官方提供的demo中拿到必要的jar就行. 在apps/struts2-blank項目下

 

2.資料庫準備

 1 /*
 2 Navicat MySQL Data Transfer
 3 
 4 Source Server         : GaGa
 5 Source Server Version : 50549
 6 Source Host           : localhost:3306
 7 Source Database       : day38hibernate
 8 
 9 Target Server Type    : MYSQL
10 Target Server Version : 50549
11 File Encoding         : 65001
12 
13 Date: 2018-01-26 21:04:36
14 */
15 
16 SET FOREIGN_KEY_CHECKS=0;
17 
18 -- ----------------------------
19 -- Table structure for t_category
20 -- ----------------------------
21 DROP TABLE IF EXISTS `t_category`;
22 CREATE TABLE `t_category` (
23   `cid` int(11) NOT NULL AUTO_INCREMENT,
24   `cname` varchar(255) DEFAULT NULL,
25   PRIMARY KEY (`cid`)
26 ) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8;
27 
28 -- ----------------------------
29 -- Records of t_category
30 -- ----------------------------
31 INSERT INTO `t_category` VALUES ('1', '水果');
32 INSERT INTO `t_category` VALUES ('2', '電子產品');
33 INSERT INTO `t_category` VALUES ('3', '食物');
34 
35 -- ----------------------------
36 -- Table structure for t_product
37 -- ----------------------------
38 DROP TABLE IF EXISTS `t_product`;
39 CREATE TABLE `t_product` (
40   `pid` int(11) NOT NULL AUTO_INCREMENT,
41   `pname` varchar(255) DEFAULT NULL,
42   `price` double DEFAULT NULL,
43   `cid` int(11) DEFAULT NULL,
44   PRIMARY KEY (`pid`),
45   KEY `FKq8yr5sflwtcj3jqp58x0oy7lx` (`cid`),
46   CONSTRAINT `FKq8yr5sflwtcj3jqp58x0oy7lx` FOREIGN KEY (`cid`) REFERENCES `t_category` (`cid`)
47 ) ENGINE=InnoDB AUTO_INCREMENT=121 DEFAULT CHARSET=utf8;
48 
49 -- ----------------------------
50 -- Records of t_product
51 -- ----------------------------
52 INSERT INTO `t_product` VALUES ('1', '葡萄', '8', '1');
53 INSERT INTO `t_product` VALUES ('2', '李子', '4.5', '1');
54 INSERT INTO `t_product` VALUES ('3', '柚子', '16.8', '1');
55 INSERT INTO `t_product` VALUES ('4', '櫻桃', '14.8', '1');
56 INSERT INTO `t_product` VALUES ('5', '橙子', '5.8', '1');
57 INSERT INTO `t_product` VALUES ('6', '蘋果', '6', '1');
58 INSERT INTO `t_product` VALUES ('7', '西瓜', '2', '1');
59 INSERT INTO `t_product` VALUES ('8', '梨子', '3.5', '1');
60 INSERT INTO `t_product` VALUES ('9', '藍莓', '10', '1');
61 INSERT INTO `t_product` VALUES ('10', '香蕉', '2', '1');
62 INSERT INTO `t_product` VALUES ('11', 'iPhone6s', '6500', '2');
63 INSERT INTO `t_product` VALUES ('12', 'iPhone4s', '3000', '2');
64 INSERT INTO `t_product` VALUES ('13', 'Mac', '18000', '2');
65 INSERT INTO `t_product` VALUES ('14', '戰神', '6600', '2');
66 INSERT INTO `t_product` VALUES ('15', 'iPhone5s', '4300', '2');
67 INSERT INTO `t_product` VALUES ('16', 'iPhone7', '8000', '2');
68 INSERT INTO `t_product` VALUES ('17', '拯救者', '8000', '2');
69 INSERT INTO `t_product` VALUES ('18', 'iPhone6', '5000', '2');
70 INSERT INTO `t_product` VALUES ('19', 'iPhone5', '3600', '2');
71 INSERT INTO `t_product` VALUES ('20', 'iPhone4', '2500', '2');
72 INSERT INTO `t_product` VALUES ('21', '羊肉', '56', '3');
73 INSERT INTO `t_product` VALUES ('22', '豬肉', '17', '3');
74 INSERT INTO `t_product` VALUES ('23', '魚', '7', '3');
75 INSERT INTO `t_product` VALUES ('24', '上海青', '3.5', '3');
76 INSERT INTO `t_product` VALUES ('25', '牛肉', '22', '3');
77 INSERT INTO `t_product` VALUES ('26', '白菜', '4', '3');
78 INSERT INTO `t_product` VALUES ('27', '辣條', '2', '3');
79 INSERT INTO `t_product` VALUES ('28', '麵包', '6', '3');
80 INSERT INTO `t_product` VALUES ('29', '雞肉', '8.6', '3');
81 INSERT INTO `t_product` VALUES ('30', '速食麵', '3.5', '3');
資料庫準備

3.配置文件準備

  1)Category映射文件配置

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE hibernate-mapping PUBLIC 
 3     "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
 4     "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
 5 <hibernate-mapping>
 6     <class name="com.gaga.bean.Category" table="t_category">
 7         <id name="cid" column="cid">
 8             <generator class="native"/>
 9         </id>
10         <property name="cname" column="cname"/>
11         
12         <!--配置多方(Set)
13             一,通過Set標簽配置多方
14                 1.1name屬性: 一方類裡面Set集合的變數名
15           -->
16         <set name="products" fetch="select" lazy="false">
17             <!--1.2 column: 外鍵的列名  -->
18             <key column="cid"/>
19             <!--1.3  class: 對方類的全限定名  -->
20             <one-to-many class="com.gaga.bean.Product"/>
21         </set>
22         
23     </class>
24 </hibernate-mapping>
Category映射文件配置

  2)Product映射文件配置

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE hibernate-mapping PUBLIC 
 3     "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
 4     "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
 5 <hibernate-mapping>
 6     <class name="com.gaga.bean.Product" table="t_product">
 7         <id name="pid" column="pid">
 8             <generator class="native"/>
 9         </id>
10         <property name="pname" column="pname"/>
11         <property name="price" column="price"/>
12         
13         <!--一, 配置一方
14              name屬性: 多方類裡面一方對象的屬性名
15              class屬性: 一方類的全限定名
16              column屬性: 外鍵的列名
17          -->
18         <many-to-one name="category" class="com.gaga.bean.Category" column="cid" />
19 
20     </class>
21 </hibernate-mapping>
Product映射文件配置

4.配置核心文件hebernate.cfg.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE hibernate-configuration PUBLIC
 3     "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
 4     "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
 5 <hibernate-configuration>
 6     <session-factory>
 7         <!--一, 必配(驅動, 資料庫的路徑, 用戶名, 密碼 , 方言)  -->
 8         <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
 9         <property name="hibernate.connection.url">jdbc:mysql:///day38hibernate</property>
10         <property name="hibernate.connection.username">root</property>
11         <property name="hibernate.connection.password">123</property>
12         <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
13         
14          <!--二, 選配  -->
15          <!--2.1 顯示sql語句  -->
16          <property name="hibernate.show_sql">true</property>
17          <!--2.2 格式化sql  -->
18          <property name="hibernate.format_sql">true</property>
19          <!--2.3 配置hibernate自動創建表  -->
20          <property name="hibernate.hbm2ddl.auto">update</property>
21          <!--2.4 集成c3p0  -->
22          <property name="hibernate.connection.provider_class">org.hibernate.c3p0.internal.C3P0ConnectionProvider</property>    
23          <property name="hibernate.c3p0.max_size">10</property>
24          
25           <!--2.6 打開session和本地線程綁定  -->
26         <property name="hibernate.current_session_context_class">thread</property> 
27          
28          <!--三, 導入映射文件 resource映射文件的路徑  resource屬性就是映射文件的路徑  -->
29          <mapping resource="com/gaga/bean/Category.hbm.xml"/>
30          <mapping resource="com/gaga/bean/Product.hbm.xml"/>
31     
32     </session-factory>
33 </hibernate-configuration>
核心配置文件

5.Struts2.xml配置

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 
 3 <!DOCTYPE struts PUBLIC
 4         "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
 5         "http://struts.apache.org/dtds/struts-2.3.dtd">
 6 
 7 <struts>
 8     <package name="category" extends="struts-default" namespace="/">
 9         <action name="category_*" class="com.gaga.servlet.CategoryAction" method="{1}">
10             <result name="success">list.jsp</result>
11             <result name="error">msg.jsp</result>
12         </action>
13     </package>
14 
15 </struts>
Struts2.xml

6.utils導入

package com.gaga.utils;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

/**
 *作用: 
 *1. 提供session
 *2. 保證SessionFactory全局只有一個 
 *
 */
public class HibernateUtils {
    
    private static  Configuration configuration = null;
    private static  SessionFactory sessionFactory = null;
    
    
    
    /**
     * 保證SessionFactory全局只有一個 
     */
    static{
         //1. 創建配置對象, 進行配置
         configuration = new Configuration();
         configuration.configure();
         //2. 構建session工廠(相當於連接池)  內置連接池 ---> c3p0 dbcp 阿裡druid  光連接池 
         sessionFactory = configuration.buildSessionFactory();
    }
    
    
    private HibernateUtils() {
        
    }

    //每次都是獲得的新的session,資料庫操作完成之後需要close
    public static Session openSession(){
         //3. 獲得session (相當於連接)
         Session session = sessionFactory.openSession();
        return session;
    }
    
    
     //4. 從本地線程獲得Session(前提是你已經在核心配置文件裡面配置了 <property name="hibernate.current_session_context_class">thread</property>)
    //從本地線程獲得的session(第一次沒有, 獲得新的存到本地線程裡面,下一次直接從本地線程獲得 ), 不需要close
    public static Session getCurrentSession(){
        Session session = sessionFactory.getCurrentSession();
        return session;
    }
    

}
View Code

7.編寫Action類

package com.gaga.servlet;

import com.gaga.bean.Category;
import com.gaga.service.CategoryService;
import org.apache.struts2.ServletActionContext;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

public class CategoryAction {
    public String findAll() {
        //1. 獲得請求參數
        //2. 調用業務
        try {
             System.out.println("CategoryAction接受了請求");
            CategoryService categoryService = new CategoryService();
            List<Category> list = categoryService.findAll();

            //3. 把list存到域裡面, 轉發頁面
            ServletActionContext.getRequest();

            HttpServletRequest request = ServletActionContext.getRequest();

            request.setAttribute("list", list);
            return "success";
        } catch (Exception e) {
            e.printStackTrace();
            HttpServletRequest request = ServletActionContext.getRequest();
            request.setAttribute("msg", "錯誤");
            return "error";
        }
    }
}
View Code

8.編寫service層

 1 package com.gaga.service;
 2 
 3 import com.gaga.bean.Category;
 4 import com.gaga.dao.CategoryDao;
 5 
 6 import java.util.List;
 7 
 8 public class CategoryService {
 9     public List<Category> findAll() {
10         CategoryDao categoryDao = new CategoryDao();
11 
12         return categoryDao.findAll();
13     }
14 }
View Code

9.編寫dao層

 1 package com.gaga.dao;
 2 
 3 import com.gaga.bean.Category;
 4 import com.gaga.utils.HibernateUtils;
 5 import org.hibernate.Session;
 6 import org.hibernate.Transaction;
 7 
 8 import java.util.List;
 9 
10 public class CategoryDao {
11     public List<Category> findAll() {
12         Session session = HibernateUtils.getCurrentSession();
13         Transaction transaction = session.beginTransaction();
14         List<Category> list = null;
15 
16         list = session.createCriteria(Category.class).list();
17 
18         transaction.commit();
19 
20         System.out.println("CategoryDao結果list:---"+list);
21         return list;
22     }
23 }
View Code

10.前端jsp頁面佈置

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- saved from url=(0044)http://localhost:8080/day41C_Product/product -->
<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>Insert title here</title>
<style>#BAIDU_DSPUI_FLOWBAR,.adsbygoogle,.ad,div[class^="ad-widsget"],div[id^="div-gpt-ad-"],a[href*="cpro.baidu.com"],a[href*="@"][href*=".exe"],a[href*="/?/"][href*=".exe"],.adpushwin{display:none!important;max-width:0!important;max-height:0!important;overflow:hidden!important;}</style></head>
<body>
	<center>
		<h1>類別信息</h1>
		<table border="1px" width="500px" cellspacing="0">
			
				<tbody>
			<c:forEach items="${list }" var="c">
				<tr>
					<td colspan="3" style="color: red; font-size: 30px">分類名稱:${c.cname }</td >
				</tr>
				<tr>
					<td>商品ID</td>
					<td>商品名稱</td>
					<td>商品價格</td>
				</tr>
				
				 <c:forEach items="${c.products}" var="p">
					<tr>
						<td>${p.pid }</td>
						<td>${p.pname }</td>
						<td>${p.price }</td>
					</tr>
				</c:forEach>
					
			</c:forEach>
			
				
			
		</tbody></table>
	</center>

</body></html>
View Code

11.發佈到Tomcat,結果顯示

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • ———————————————————————————————————————————————————————— 在 rootkit 與惡意軟體開發中有一項基本需求,那就是 hook Windows 內核的系統服務描述符表(下稱 SSDT),把該表中的 特定系統服務函數替換成我們自己實現的惡意常式; ...
  • 1. 指針 1.1 一個指針包含兩方面:a) 地址值;b) 所指向的數據類型。 1.2 解引用操作符(dereference operator)會根據指針當前的地址值,以及所指向的數據類型,訪問一塊連續的記憶體空間(大小由指針所指向的數據類型決定),將這塊空間的內容轉換成相應的數據類型,並返回左值。 ...
  • ...
  • 數組檢索函數 格式:array array_keys(array arr[, mixed searchValue]);以數組的形式返回arr數組中的“鍵名”,如果指定了可選參數searchValue,則只返回searchValue值的鍵名,否則arr數組中的所有鍵名都會被返回。 註意:若search ...
  • 複習默寫猜數字小代碼,出現的問題。 While語句下的條件。應為result==false和answer=input()時。如果answer=input()寫在while的外邊,就會像昨天那樣一直輸出too small。 還有就是if語句,語法錯誤,百度了一下,看起來縮進了,其實是並沒有縮進。 1、 ...
  • 1.org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.mybatis.spring.mapper.MapperScannerConfigurer#0' defined ...
  • 作者:[email protected]本文為作者原創,轉載請註明出處:https://www.cnblogs.com/oucbl/p/5940556.html 今天學習SSM框架整合,完成Spring和mybatis這兩大框架的整合做測試時候出來很多問題,主要來自於配置文件。 我這裡重點說一下Mysql數據 ...
  • 最基本命令 查看埠號:netstar -aon 殺死進程:tskill PID PHP基礎 查看埠號:netstar -aon 殺死進程:tskill PID PHP基礎 PHP程式的數據採集(獲取數據) $_GET["要獲取的名稱"]; PHP數據的輸出 echo或print:輸出的是沒有經過 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...