1. 程式人生 > >Struts2+Spring+Hibernate整合開發(Maven多模組搭建)

Struts2+Spring+Hibernate整合開發(Maven多模組搭建)

Struts2+Spring+Hibernate整合開發(Maven多模組搭建)

0.專案結構

Struts2:web層

Spring:物件的容器

Hibernate:資料庫持久化操作

 

1.父模組匯入和管理所有需要的jar包

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation
="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.ssh</groupId> <artifactId>ssh_maven</artifactId> <packaging>pom</packaging> <version>1.0-SNAPSHOT</version> <modules> <module>ssh_dao</module> <module>ssh_service</module> <module>ssh_web</module> </modules> <!-- 版本管理 --> <properties> <spring.version>4.2.4.RELEASE</spring.version> <hibernate.version>5.0.7.Final</hibernate.version> <struts.version>2.3.24</struts.version> </properties> <!-- 鎖定版本 --> <dependencyManagement> <dependencies> <!-- spring --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> </dependency> <!-- hibernate --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>${hibernate.version}</version> </dependency> <!-- struts2 --> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-core</artifactId> <version>${struts.version}</version> </dependency> <!-- 整合的jar包 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-spring-plugin</artifactId> <version>${struts.version}</version> </dependency> </dependencies> </dependencyManagement> <!-- 依賴管理,新增依賴的jar包 --> <dependencies> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jsp-api</artifactId> <version>2.0</version> <scope>provided</scope> </dependency> <!-- spring相關 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> </dependency> <!-- hibernate --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> </dependency> <!-- struts2 --> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-core</artifactId> </dependency> <!-- 整合的jar包 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> </dependency> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-spring-plugin</artifactId> </dependency> <!-- 資料庫驅動 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.29</version> </dependency> <!-- c3p0連線池 --> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.1.2</version> </dependency> <!-- 日誌 --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.5</version> </dependency> <!-- jstl --> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> </dependencies> <build> <!-- 配置外掛 --> <plugins> <!-- 配置編譯版本為jdk1.7 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.5.1</version> <configuration> <source>1.7</source> <target>1.7</target> <encoding>UTF-8</encoding> </configuration> </plugin> <!-- 配置tomcat7 --> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>2.2</version> <configuration> <!-- 配置工程路徑 --> <path>/</path> <!-- 配置埠號 --> <port>8080</port> </configuration> </plugin> </plugins> </build> </project>
父模組pom

 

2.Dao模組

1)建立Hibernate核心配置檔案(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>
        <!-- 資料庫方言,根據資料庫選擇 -->
        <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>

        <!--為了方便除錯是否在執行hibernate時在日誌中輸出sql語句 -->
        <property name="hibernate.show_sql">true
</property> <!-- 是否對日誌中輸出的sql語句進行格式化 --> <property name="hibernate.format_sql">true</property> <!-- 自動建表 --> <property name="hibernate.hbm2ddl.auto">update</property> <!-- 載入對映檔案 --> <mapping resource="com/ssh/entity/Customer.hbm.xml"/> </session-factory> </hibernate-configuration>
hibernate.cfg.xml

 

2)建立元配置檔案(Customer.hbm.xml;命名格式不能隨便取)

可以根據該配置檔案自動對映為表,該配置檔案對應一個實體類

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!-- Generated 2016-2-26 16:58:40 by Hibernate Tools 4.3.1.Final -->
<hibernate-mapping>
    <class name="com.ssh.entity.Customer" table="cst_customer"  optimistic-lock="version">
        <id name="custId" type="java.lang.Long">
            <column name="cust_id" />
            <generator class="identity" />
        </id>
        <property name="custName" type="string">
            <column name="cust_name" length="32" not-null="true"></column>
        </property>
        <property name="custUserId" type="java.lang.Long">
            <column name="cust_user_id"></column>
        </property>
        <property name="custCreateId" type="java.lang.Long">
            <column name="cust_create_id"></column>
        </property>
        <property name="custIndustry" type="string">
            <column name="cust_industry" length="32"></column>
        </property>
        <property name="custLevel" type="string">
            <column name="cust_level" length="32"></column>
        </property>
        <property name="custLinkman" type="string">
            <column name="cust_linkman" length="64"></column>
        </property>
        <property name="custPhone" type="string">
            <column name="cust_phone" length="64"></column>
        </property>
        <property name="custMobile" type="string">
            <column name="cust_mobile" length="16"></column>
        </property>
    </class>
</hibernate-mapping>
customer.hbm.xml

 

3)建立Spring核心配置檔案(applicationContext-dao.xml)

主要配置資料庫的資料來源(資料庫連線池);

Hibernate的工廠(建立SessionFactory工廠);

配置事務管理;

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop" 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/context 
    http://www.springframework.org/schema/context/spring-context.xsd 
    http://www.springframework.org/schema/aop 
    http://www.springframework.org/schema/aop/spring-aop.xsd 
    http://www.springframework.org/schema/tx  
    http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!-- 資料庫連線池 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver" />
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/ssh_maven" />
        <property name="user" value="root" />
        <property name="password" value="admins" />
    </bean>

    <!-- 配置sessionFactory -->
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <!-- 依賴dataSource -->
        <property name="dataSource" ref="dataSource" />
        <!-- 建立工廠需要載入hibernate對映檔案 -->
        <property name="configLocations" value="classpath:hibernate.cfg.xml"></property>
    </bean>

    <bean id="customerDao" class="com.ssh.dao.impl.CustomerImpl">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>

</beans>
application-dao.xml

 

4)介面和實體類

package com.ssh.dao;

import com.ssh.entity.Customer;

public interface CustomerDao {

    /**
     * 通過id查詢使用者
     * @param CustomerId
     * @return
     */
    public Customer findCustomerById(Long CustomerId);
}
CustomerDao
package com.ssh.dao.impl;

import com.ssh.dao.CustomerDao;
import com.ssh.entity.Customer;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;

public class CustomerImpl extends HibernateDaoSupport implements CustomerDao {

    @Override
    public Customer findCustomerById(Long CustomerId) {
        return this.getHibernateTemplate().get(Customer.class, CustomerId);
    }

}
CustomerImpl
package com.ssh.entity;

public class Customer {
    private Long custId;
    private String custName;
    private Long custUserId;
    private Long custCreateId;
    private String custIndustry;
    private String custLevel;
    private String custLinkman;
    private String custPhone;
    private String custMobile;

    public Long getCustId() {
        return custId;
    }
    public void setCustId(Long custId) {
        this.custId = custId;
    }
    public String getCustName() {
        return custName;
    }
    public void setCustName(String custName) {
        this.custName = custName;
    }
    public Long getCustUserId() {
        return custUserId;
    }
    public void setCustUserId(Long custUserId) {
        this.custUserId = custUserId;
    }
    public Long getCustCreateId() {
        return custCreateId;
    }
    public void setCustCreateId(Long custCreateId) {
        this.custCreateId = custCreateId;
    }
    public String getCustIndustry() {
        return custIndustry;
    }
    public void setCustIndustry(String custIndustry) {
        this.custIndustry = custIndustry;
    }
    public String getCustLevel() {
        return custLevel;
    }
    public void setCustLevel(String custLevel) {
        this.custLevel = custLevel;
    }
    public String getCustLinkman() {
        return custLinkman;
    }
    public void setCustLinkman(String custLinkman) {
        this.custLinkman = custLinkman;
    }
    public String getCustPhone() {
        return custPhone;
    }
    public void setCustPhone(String custPhone) {
        this.custPhone = custPhone;
    }
    public String getCustMobile() {
        return custMobile;
    }
    public void setCustMobile(String custMobile) {
        this.custMobile = custMobile;
    }
    
}
Customer

 

3.Service模組

1)依賴Dao模組

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>ssh_maven</artifactId>
        <groupId>com.ssh</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>ssh_service</artifactId>

    <dependencies>
        <dependency>
            <groupId>com.ssh</groupId>
            <artifactId>ssh_dao</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>
service.pom

 

2)建立Spring核心配置檔案(applicationContext-service.xml)

主要用於管理Service

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop" 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/context 
    http://www.springframework.org/schema/context/spring-context.xsd 
    http://www.springframework.org/schema/aop 
    http://www.springframework.org/schema/aop/spring-aop.xsd 
    http://www.springframework.org/schema/tx  
    http://www.springframework.org/schema/tx/spring-tx.xsd">

    <import resource="classpath:applicationContext-dao.xml"/>

    <bean id="customerService" class="com.ssh.service.impl.CustomerServiceImpl">
        <property name="customerDao" ref="customerDao"></property>
    </bean>

</beans>
application-service.xml

 

3)介面與實現

CustomerService CustomerServiceImpl

 

4.Web模組

1)依賴Service模組

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>ssh_maven</artifactId>
        <groupId>com.ssh</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>ssh_web</artifactId>
    <packaging>war</packaging>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>com.ssh</groupId>
            <artifactId>ssh_service</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
    </dependencies>

</project>
web.pom

 

2)建立Spring核心配置檔案(applicationContext-action.xml)

主要用於管理Action

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop" 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/context 
    http://www.springframework.org/schema/context/spring-context.xsd 
    http://www.springframework.org/schema/aop 
    http://www.springframework.org/schema/aop/spring-aop.xsd 
    http://www.springframework.org/schema/tx  
    http://www.springframework.org/schema/tx/spring-tx.xsd">

    <import resource="classpath:applicationContext-service.xml"/>

    <bean id="customerAction" class="com.ssh.action.CustomerAction" scope="prototype">
        <property name="customerService" ref="customerService"></property>
    </bean>

</beans>
application-action.xml

 

3)建立Struts2核心配置檔案(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.i18n.encoding" value="UTF-8"></constant>
    <!-- 開發模式 -->
    <constant name="struts.devMode" value="true"></constant>
    <!-- 主題 -->
    <constant name="struts.ui.theme" value="simple"></constant>
    <!-- 副檔名 -->
<!--     <constant name="struts.action.extension" value="action"></constant> -->

    <!-- 通用package -->
    <package name="customer" namespace="/" extends="struts-default">

        <action name="customerAction_*" class="customerAction" method="{1}">
            <result name="success">/info.jsp</result>
        </action>

    </package>
</struts>
struts.xml

 

4)Action

package com.ssh.action;

import com.opensymphony.xwork2.ActionSupport;
import com.ssh.entity.Customer;
import com.ssh.service.CustomerService;

public class CustomerAction extends ActionSupport {

    //注入service
    private CustomerService customerService;
    
    //屬性封裝到custId
    private Long custId;//客戶id
    
    //存放到值棧(get方式)
    private Customer customer;//客戶資訊

    public CustomerService getCustomerService() {
        return customerService;
    }
    public void setCustomerService(CustomerService customerService) {
        this.customerService = customerService;
    }
    public Long getCustId() {
        return custId;
    }
    public void setCustId(Long custId) {
        this.custId = custId;
    }
    public Customer getCustomer() {
        return customer;
    }
    public void setCustomer(Customer customer) {
        this.customer = customer;
    }

    //action方法
    public String queryCustomer(){
        customer=customerService.findCustomerById(custId);
        return "success";
    }

}
CustomerAction

 

5.Web.xml中的配置

配置監聽器讀取applicationContext-*.xml

配置Struts2的核心攔截器(過濾器)

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">

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

    <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>

    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>index.jsp</welcome-file>
        <welcome-file>default.html</welcome-file>
        <welcome-file>default.htm</welcome-file>
        <welcome-file>default.jsp</welcome-file>
    </welcome-file-list>

</web-app>
web.xml

 

6.其他一些配置

1)返回的頁面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
訪問網址:http://localhost:8080/ssh/customerAction_queryCustomer.action?custId=1
這是一個資訊頁面
${customer.custName }
</body>
</html>
info.jsp

 

2)資料庫連線池

#加jdbc字首的目的是為了避免後面的名字與其他地方名字衝突
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssh_maven?characterEncoding=utf-8
jdbc.username=root
jdbc.password=admins

 

3)日誌

#日誌檔案
log4j.rootLogger=DEBUG,stdout
log4j.logger.org.mybatis=DEBUG
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p %d %C: %m%n

 

至此SSH分模組整合完畢