Struts2学习笔记NO.1------结合Hibernate完成查询商品类别简单案例(工具IDEA)

    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,结果显示

 

posted @ 2018-01-26 21:25  三毛他哥  阅读(395)  评论(0编辑  收藏  举报