SSH笔记-整合Spring2、Struts2、Hibernate4

注意:一定要记得加spring-web-x.x.x.RELEASE.jar

1、整合Spring

(1)加入jar
(2)配置web.xml(配置web的contextConfigLocation和listener)
(3)加入Spring配置文件(applicationContext.xml)

2、整合Hibernate

(1)加入jar
(2)加入hibernate.cfg.xml文件(配置hibernate基本屬性)
(3)建立持久化类和对应的.hbm.xml文件
(4)Spring整合Hibernate
(5)运行项目生成数据表

3、整合Struts

(1)加入jar
(2)在web.xml配置Struts的Filter
(3)加入Struts配置文件
(4)整合

①Spring配置文件中配置Action,且scope设置为prototype
②在Struts2配置文件中配置Action时,class属性指向Action在IOC中的id

4、各种类的作用(调用顺序是1->2->3->4)

(1)Bean :数据模型
(2)Action :接收数据、调用方法的操作类
(3)Service :把操作数据库的方法实现出来,避免调用的时候看起来代码混乱,防止直接操作数据库,给action提供可调用的接口的作用
(4)Dao :数据库操作的具体方法函数

5、整合具体步骤:

(1)加入Spring2、Struts2、Hibernate4的jar
(2)创建Bean类(添加参数及get/set方法)和对应的.hbm.xml文件
(3)创建操作数据库的Dao类

①配置@Service、@Transactional
②定义SessionFactory参数及其get/set方法,并且为SessionFactory添加@Autowire
③添加对数据库操作的方法

(4)创建Service类,实例化Dao类中的方法
(5)创建Action类,调用Service中对应的方法函数(该类需要继承ActionSupport及实现RequestAware接口)
(6)src下创建并且配置hibernate.cfg.xml文件
(7)在web项目的web.xml中配置Spring的contextConfigLocation和listener和Struts的Filter
(8)创建记录数据库连接信息的properties
(9)src下创建并且配置Spring配置文件(applicationContext.xml)

①为Dao类配置context:component-scan
②导入记录数据库连接信息的资源文件
③配置C3P0数据源
④配置JdbcTemplate
⑤配置Hibernate的SessionFactory实例
⑥配置Spring的声明式事务
⑦配置bean(Dao、Service、Action的类)

(10)创建Struts配置文件(struts.xml),配置action
(11)创建页面调用action

6、Product.java

package Bean;

import com.opensymphony.xwork2.ActionSupport;

//java只能单继承,所以Product类继承ActionSupport,让Action类继承该类,方便Action中调用该类的get/set方法,同时让Action有继承ActionSupport
public class Product extends ActionSupport{

    private Integer productId;
    private String productName;
    private double productPrice;
    private Integer productQuantity;
    private String productSource;
    private String productStoreAddr;

    public Integer getProductId() {
        return productId;
    }
    public void setProductId(Integer productId) {
        this.productId = productId;
    }
    public String getProductName() {
        return productName;
    }
    public void setProductName(String productName) {
        this.productName = productName;
    }
    public double getProductPrice() {
        return productPrice;
    }
    public void setProductPrice(double productPrice) {
        this.productPrice = productPrice;
    }
    public Integer getProductQuantity() {
        return productQuantity;
    }
    public void setProductQuantity(Integer productQuantity) {
        this.productQuantity = productQuantity;
    }
    public String getProductSource() {
        return productSource;
    }
    public void setProductSource(String productSource) {
        this.productSource = productSource;
    }
    public String getProductStoreAddr() {
        return productStoreAddr;
    }
    public void setProductStoreAddr(String productStoreAddr) {
        this.productStoreAddr = productStoreAddr;
    }
}

7、ProductDao.java

package Dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import Bean.Product;

@Service
@Transactional
public class ProductDao{
    @Autowired
    private SessionFactory sessionFactory;

    private Session getSession(){
        return sessionFactory.getCurrentSession();
    }

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    //查询数据表中最大的ID,并生成比现有最大ID大1的新的ID
    public int nextID(){
        int newId = 0;
        String hql = "SELECT max(productId) FROM Product";
        List<Product> rs = getSession().createQuery(hql).list();
        if(!(rs.get(0)==null)){
            newId = Integer.parseInt(rs.get(0).toString());
        }
        newId = newId + 1;
        return newId;
    }

    //根据ID获取对应的一条记录的所有值
    public List<Product>getItem(Integer productId){
        String hql = "FROM Product p WHERE p.productId=?";
        return getSession().createQuery(hql).setInteger(0, productId).list();
    }

    //获取所有值
    public List<Product>getAll(){
        String hql = "FROM Product";
        return getSession().createQuery(hql).list();
    }

    //删除指定ID的记录
    public void delete(Integer productId){
        String hql = "DELETE FROM Product p WHERE p.productId=?";
        getSession().createQuery(hql).setInteger(0, productId).executeUpdate();
    }

    //插入一条新纪录
    public void insert(Product product){
        Session session = getSession();
        product.setProductId(nextID());
        session.save(product);
        session.flush();
    }

    //更新指定ID的记录
    public void update(Product product){
        String hql = "UPDATE Product p SET p.productName=?,p.productPrice=?,p.productQuantity=?,productSource=?,p.productStoreAddr=? WHERE p.productId=?";
        getSession().createQuery(hql).setString(0, product.getProductName())
                                    .setDouble(1, product.getProductPrice())
                                    .setInteger(2, product.getProductQuantity())
                                    .setString(3, product.getProductSource())
                                    .setString(4, product.getProductStoreAddr())
                                    .setInteger(5, product.getProductId())
                                    .executeUpdate();
    }

}

8、ProductService.java

package Service;

import java.util.List;

import Bean.Product;
import Dao.ProductDao;

public class ProductService{

    private ProductDao productDao;

    public void setProductDao(ProductDao productDao) {
        this.productDao = productDao;
    }

    public List<Product> getItem(Integer productId){
        return productDao.getItem(productId);
    }

    public List<Product> getAll(){
        return productDao.getAll();
    }

    public void delete(Integer productId){
        productDao.delete(productId);
    }

    public void insert(Product product){
        productDao.insert(product);
    }

    public void update(Product product){
        productDao.update(product);
    }
}

9、ProductAction.java

package Action;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Map;

import org.apache.struts2.interceptor.RequestAware;

import Bean.Product;
import Service.ProductService;

//继承Product,以此方便下面的方法获取前台传过来的指定参数的值,并间接继承ActionSupport
public class ProductAction extends Product implements RequestAware {

    private ProductService productService;

    public void setProductService(ProductService productService) {
        this.productService = productService;
    }

    //定义一个集合参数及其set方法,用来返回数据给前台使用
    private Map<String, Object> request;

    public void setRequest(Map<String, Object> arg0) {
        this.request = arg0;
    }

    //查询所有值,并且方法request集合中,前台直接用EL和s:iterator读reqeust即可
    public String list() {
        request.put("product", productService.getAll());
        return "list";
    }

    //定义InputStream参数及其get/set方法,用来返回指定值给Struts配置文件的stream类型result中,通过这个stream类型的result告诉页面的ajax返回结果(执行删除操作时候用)
    private InputStream inputStream;

    public InputStream getInputStream() {
        return inputStream;
    }

    public void setInputStream(InputStream inputStream) {
        this.inputStream = inputStream;
    }

    //删除记录
    public String delete(){
        try {
            productService.delete(getProductId());
            inputStream = new ByteArrayInputStream("1".getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            try {
                inputStream = new ByteArrayInputStream("0".getBytes("UTF-8"));
            } catch (UnsupportedEncodingException e1) {
                e1.printStackTrace();
            }
        }
        return "delete_success";
    }

    //插入记录
    public String insert(){
        try {
            Product product = new Product();
            product.setProductName(getProductName());
            product.setProductPrice(getProductPrice());
            product.setProductQuantity(getProductQuantity());
            product.setProductSource(getProductSource());
            product.setProductStoreAddr(getProductStoreAddr());
            productService.insert(product);
            return "insert_success";
        } catch (Exception e) {
            e.printStackTrace();
            return "insert_fail";
        }
    }

    //查询指定ID记录中所有的值,并且方法request集合中,前台直接用EL和s:iterator读reqeust即可
    public String getItem() {
        request.put("item", productService.getItem(getProductId()));
        return "getItem";
    }

    //更新记录
    public String update(){
        try {
            Product product = new Product();
            product.setProductId(getProductId());
            product.setProductName(getProductName());
            product.setProductPrice(getProductPrice());
            product.setProductQuantity(getProductQuantity());
            product.setProductSource(getProductSource());
            product.setProductStoreAddr(getProductStoreAddr());
            if(getProductPrice()<0){
                return "update_fail";
            }else if(getProductQuantity()<0){
                return "update_fail";
            }
            productService.update(product);
            return "update_success";
        } catch (Exception e) {
            e.printStackTrace();
            return "update_fail";
        }
    }
}

10、Product.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 2018-6-20 22:31:56 by Hibernate Tools 3.5.0.Final -->
<hibernate-mapping>
    <class name="Bean.Product" table="PRODUCT">
        <id name="productId" type="java.lang.Integer">
            <column name="PRODUCTID" />
            <generator class="native" />
        </id>
        <property name="productName" type="java.lang.String">
            <column name="PRODUCTNAME" />
        </property>
        <property name="productPrice" type="double">
            <column name="PRODUCTPRICE" />
        </property>
        <property name="productQuantity" type="java.lang.Integer">
            <column name="PRODUCTQUANTITY" />
        </property>
        <property name="productSource" type="java.lang.String">
            <column name="PRODUCTSOURCE" />
        </property>
        <property name="productStoreAddr" type="java.lang.String">
            <column name="PRODUCTSTOREADDR" />
        </property>
    </class>
</hibernate-mapping>

11、applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">

    <!-- 配置自动扫描的包 -->
    <context:component-scan base-package="Dao"></context:component-scan>

    <!-- 导入资源文件 -->
    <context:property-placeholder location="classpath:db.properties"/>

    <!-- 配置C3P0数据源 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="user" value="${jdbc.user}"></property>
        <property name="password" value="${jdbc.password}"></property>
        <property name="driverClass" value="${jdbc.driverClass}"></property>
        <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
        <property name="initialPoolSize" value="${jdbc.initialPoolSize}"></property>
        <property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property>
    </bean>

    <!-- 配置JdbcTemplate -->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!-- 配置Hibernate的SessionFactory实例 -->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
        <property name="mappingLocations" value="classpath:Bean/*.hbm.xml"></property>
    </bean>

    <!-- 配置Spring的声明式事务 -->
    <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>
    <tx:annotation-driven transaction-manager="transactionManager"/>

    <!-- 配置bean -->
    <bean id="productDao" class="Dao.ProductDao">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>
    <bean id="productService" class="Service.ProductService">
        <property name="productDao" ref="productDao"></property>
    </bean>
    <bean id="productAction" class="Action.ProductAction" scope="prototype">
        <property name="productService" ref="productService"></property>
    </bean>

</beans>

12、db.properties

jdbc.user=root
jdbc.password=
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql://localhost/SSHIntegrate
jdbc.initialPoolSize=5
jdbc.maxPoolSize=10

13、hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>

    <session-factory>

        <!-- 配置hibernate基本属性 -->
        <!-- 1、数据源配置到IOC容器,在此不许配置数据源 -->
        <!-- 2、关联的hbm.xml在IOC容器配置SeesionFactory实例时配置 -->
        <!-- 3、配置Hibernate基本属性:方言、SQL显示、生成数据表策略、二级缓存 -->
        <!-- 配置hibernate基本信息-->
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <!-- 执行操作室是否在控制台打印sql -->
        <property name="hibernate.show_sql">true</property>
        <!-- 是否对sql格式化 -->
        <property name="hibernate.format_sql">true</property>
        <!-- 指定自动生成数据表的策略 -->
        <property name="hibernate.hbm2ddl.auto">update</property>
        <!-- 启用二级缓存 -->
        <property name="hibernate.cache.use_second_level_cache">true</property>
        <!-- 配置使用的二级缓存的产品 -->
        <property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
        <!-- 配置启用查询缓存 -->
        <property name="cache.use_query_cache">true</property>

    </session-factory>

</hibernate-configuration>

14、struts.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
    "http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>

    <constant name="struts.enable.DynamicMethodInvocation" value="false"></constant>
    <constant name="struts.devMode" value="ture" />

    <package name="default" namespace="/" extends="struts-default">
        <action name="product_*" class="productAction" method="{1}">
            <result>/result.jsp</result>

            <result name="list">/result.jsp</result>

            <result type="stream" name="delete_success">
                <param name="contentType">text/html</param>
                <param name="inputName">inputStream</param>
            </result>

            <result name="insert_success" type="chain">
              <param name="actionName">product_list</param>
            </result>
            <result name="insert_fail">/insert.jsp?insert_type=product</result>

            <result name="getItem">/update.jsp</result>

            <result name="update_success" type="chain">
              <param name="actionName">product_list</param>
            </result>
            <result name="update_fail" type="chain">
              <param name="actionName">product_getItem</param>
            </result>
        </action>
    </package>
</struts>

15、web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
    version="3.1">
    <display-name>SSH_Integrate</display-name>

    <!-- 配置Spring的contextConfigLocation和listener -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext*.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- 配置Struts的Filter -->
    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

17、result.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page language="java" import="java.net.*,java.io.*,java.text.*, java.util.*"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<%request.setCharacterEncoding("UTF-8");%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="js/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
$(function(){
    //1. 点击 delete 时, 弹出 确定是要删除 xx 的信息吗 ? 若确定, 执行删除, 若不确定, 则取消
    $(".delete").click(function(){
        var lastName = $(this).next(":hidden").val();
        var flag = confirm("确定要删除" + lastName + "的信息吗?");
        if(flag){
            var $tr = $(this).parent().parent();
            //删除, 使用 ajax 的方式
            var url = this.href;
            var args = {"time":new Date()};
            $.post(url, args, function(data){
                //若 data 的返回值为 1, 则提示 删除成功, 且把当前行删除
                if(data == "1"){
                    alert("删除成功!");
                    $tr.remove();
                }else{
                    //若 data 的返回值不是 1, 提示删除失败. 
                    alert("删除失败!");
                }
            }); 
        }

        //取消超链接的默认行为
        return false;
    });     
})
</script>
</head>
<body>
    <s:if test="#request.product==null||#request.product.size()==0">
        <a href="insert.jsp?insert_type=product">Insert Product</a><br>
        <s:if test="#request.product.size()==0">
            no product
        </s:if>
    </s:if>
    <s:else>
        <a href="insert.jsp?insert_type=product">Insert Product</a><br>
        <table border='1'>
            <tr>
                <td>productId</td>
                <td>productName</td>
                <td>productPrice</td>
                <td>productQuantity</td>
                <td>productSource</td>
                <td>productStoreAddr</td>
                <td>Delete</td>
                <td>Update</td>
            </tr>
            <s:iterator value="#request.product">
                <tr>
                    <td>${productId}</td>
                    <td>${productName}</td>
                    <td>${productPrice}</td>
                    <td>${productQuantity}</td>
                    <td>${productSource}</td>
                    <td>${productStoreAddr}</td>
                    <td>
                        <a href="product_delete?productId=${productId}" class="delete">Delete</a>
                        <input type="hidden" value="${productName }"/>
                    </td>
                    <td>
                        <a href="product_getItem?productId=${productId}">Update</a>
                    </td>
                </tr>
            </s:iterator>
        </table>
    </s:else>
    <br>
    <br>
</body>
</html>

18、insert.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page language="java" import="java.net.*,java.io.*,java.text.*, java.util.*"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<%request.setCharacterEncoding("UTF-8");%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    Insert product
    <br>
    <form action="product_insert" method="POST">
        <table border='1'>
            <tr>
                <td>param</td>
                <td>value</td>
            </tr>
            <tr>
                <td>ProductName</td>
                <td><input type="text" id="productName" name="productName"></td>
            </tr>
            <tr>
                <td>ProductPrice</td>
                <td><input type="text" id="productPrice" name="productPrice"></td>
            </tr>
            <tr>
                <td>ProductQuantity</td>
                <td><input type="text" id="productQuantity"
                    name="productQuantity"></td>
            </tr>
            <tr>
                <td>ProductSource</td>
                <td><input type="text" id="productSource" name="productSource"></td>
            </tr>
            <tr>
                <td>ProductStoreAddr</td>
                <td><input type="text" id="productStoreAddr"
                    name="productStoreAddr"></td>
            </tr>
            <tr>
                <td>submit</td>
                <td><input type="submit" id="submit" naem="submit"
                    value="submit"></td>
            </tr>
        </table>
    </form>
    <br>
    <s:debug></s:debug>
    <br>
</body>
</html>

19、update.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page language="java" import="java.net.*,java.io.*,java.text.*, java.util.*"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<%request.setCharacterEncoding("UTF-8");%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    Update product
    <br>
    <form action="product_update" method="POST">

        <table border='1'>
            <tr>
                <td>param</td>
                <td>value</td>
            </tr>
            <s:iterator value="#request.item">
            <tr>
                <td>ProductId</td>
                <td><input type="text" id="productId" name="productId" value="${productId}" readonly="readonly"></td>
            </tr>
            <tr>
                <td>ProductName</td>
                <td><input type="text" id="productName" name="productName" value="${productName}"></td>
            </tr>
            <tr>
                <td>ProductPrice</td>
                <td><input type="text" id="productPrice" name="productPrice" value="${productPrice}"></td>
            </tr>
            <tr>
                <td>ProductQuantity</td>
                <td><input type="text" id="productQuantity" name="productQuantity" value="${productQuantity}"></td>
            </tr>
            <tr>
                <td>ProductSource</td>
                <td><input type="text" id="productSource" name="productSource" value="${productSource}"></td>
            </tr>
            <tr>
                <td>ProductStoreAddr</td>
                <td><input type="text" id="productStoreAddr" name="productStoreAddr" value="${productStoreAddr}"></td>
            </tr>
            </s:iterator>
            <tr>
                <td>submit</td>
                <td><input type="submit" id="submit" naem="submit" value="submit"></td>
            </tr>
        </table>
    </form>
    <br>
    <s:debug></s:debug>
    <br>
</body>
</html>

20、index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page language="java" import="java.net.*,java.io.*,java.text.*, java.util.*"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<%request.setCharacterEncoding("UTF-8");%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    <a href="product_list">List product</a>
</body>
</html>

21、项目目录
项目目录

22、demo
https://download.csdn.net/download/qq_22778717/10512067

猜你喜欢

转载自blog.csdn.net/qq_22778717/article/details/80875611