Maven学习笔记(二)—— 整合SSH框架

一、知识点准备

1.1 什么是依赖传递?

  我们只添加一个struts2-core的依赖,结果会发现所有关于struts2的依赖都进来了。

    

  因为我们的项目依赖struts2-core-2.3.24.jar,而struts2-core-2.3.24.jar会依赖xwork-core-2.3.24.jar等等,所以xwork-core-2.3.24.jar等jar包也出现在我们的maven工程中,这种现象我们称为依赖传递。从下图可以看到他们的关系:

    

1.2 依赖版本冲突的解决

  接着添加两个依赖

  

  我们发现这两个jar包同时依赖了spring-beans

  

  struts2-spring-plugin依赖spring-beans-3.0.5,spring-context依赖spring-beans-4.2.4,但是发现spring-beans-3.0.5加入到工程中了,而我们希望spring-beans-4.2.4加入到工程,这就造成了依赖冲突。解决依赖冲突有以下原则:

  • 第一声明者优先原则(需要用的放在前面)

  在pom文件定义依赖,以先声明的依赖为准。

  测试:如果将上面struts2-spring-plugin和spring-context顺序颠倒,系统将导入spring-beans-4.2.4。

  分析:由于spring-context在前边,以spring-context依赖的spring-beans-4.2.4为准,所以最终spring-beans-4.2.4添加到了工程中。

  • 路径近者优先原则(自己添加jar包)

  例如:A依赖spring-beans-4.2.4,A也依赖B,其中B依赖spring-beans-3.0.5,那么spring-beans-4.2.4会优先被依赖在A中,因为spring-beans-4.2.4相对spring-beans-3.0.5被A依赖的路劲最近。

  测试:在本工程中的pom文件加入赖spring-beans-4.2.4的依赖,根据路径近者优先原则,系统将导入spring-beans-4.2.4:

    

  • 排除依赖原则

  比如在依赖struts2-spring-plugin的设置中添加排除依赖,排除spring-beans

  

  • 版本锁定原则

  面对众多依赖,我们可以采用直接锁定版本的方法确定依赖构件的版本,版本锁定后则不用考虑依赖的声明顺序或依赖的路径,以锁定的版本为准添加到工程中,此方法在企业开发中最常用

  如下的配置是锁定了spring-beans和spring-context的版本

  <dependencyManagement>
        <dependencies>
            <!-- 这里锁定版本为4.2.4 -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-beans</artifactId>
                <version>4.2.4.RELEASE</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context</artifactId>
                <version>4.2.4.RELEASE</version>
            </dependency>
        </dependencies>
    </dependencyManagement>

   注意:在工程中锁定依赖的版本并不代表在工程中添加了依赖,如果工程需要添加锁定版本的依赖则需要单独添加<dependencies></dependencies>标签,如下:

    <dependencies>
        <!-- 这里是添加依赖 -->
        <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-beans</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context</artifactId>
            </dependency>
    </dependencies>

  上边添加的依赖并没有指定版本,原因是已在<dependencyManagement>中锁定了版本,所以在<dependency>下不需要再指定版本。

二、构建项目

2.1 创建一个maven工程

  打包类型为war

2.2 添加web.xml文件

  右键工程 --> Java EE Tools --> Generate Deployment Descriptor Stub

2.3 定义pom.xml

  maven工程首先要识别依赖,web工程实现SSH整合,需要依赖struts2.3.24、spring4.2.4、hibernate5.0.7等,在pom.xml添加工程如下依赖:(在实际企业开发中会有架构师专门来编写pom.xml)

  分两步:1、锁定依赖版本;2、添加依赖

<!-- 属性 -->
    <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>

    <!-- 锁定版本,struts2-2.3.24、spring4.2.4、hibernate5.0.7 -->
    <dependencyManagement>
        <dependencies>
            <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-orm</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-test</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-web</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.hibernate</groupId>
                <artifactId>hibernate-core</artifactId>
                <version>${hibernate.version}</version>
            </dependency>
            <dependency>
                <groupId>org.apache.struts</groupId>
                <artifactId>struts2-core</artifactId>
                <version>${struts.version}</version>
            </dependency>
            <dependency>
                <groupId>org.apache.struts</groupId>
                <artifactId>struts2-spring-plugin</artifactId>
                <version>${struts.version}</version>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <!-- 依赖管理 -->
    <dependencies>
        <!-- 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-orm</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
        </dependency>
        <!-- hibernate -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
        </dependency>

        <!-- 数据库驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
            <scope>runtime</scope>
        </dependency>
        <!-- c3p0 -->

        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1.2</version>
        </dependency>


        <!-- 导入 struts2 -->
        <dependency>
            <groupId>org.apache.struts</groupId>
            <artifactId>struts2-core</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.struts</groupId>
            <artifactId>struts2-spring-plugin</artifactId>
        </dependency>

        <!-- servlet jsp -->
        <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>
        <!-- 日志 -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.2</version>
        </dependency>
        <!-- junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.9</version>
            <scope>test</scope>
        </dependency>
        <!-- jstl -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <!-- 设置编译版本为1.7 -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>

            <!-- maven内置 的tomcat6插件 -->
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>tomcat-maven-plugin</artifactId>
                <version>1.1</version>
                <configuration>
                    <!-- 可以灵活配置工程路径 -->
                    <path>/ssh</path>
                    <!-- 可以灵活配置端口号 -->
                    <port>8080</port>
                </configuration>
            </plugin>
        </plugins>
    </build>

2.4 准备数据库环境

    

2.5 配置文件

  将配置文件放到 src/main/resources目录中

  • 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="cn/itcast/entity/Customer.hbm.xml"/>
        </session-factory>
    </hibernate-configuration>
  • applicationContext.xml
    <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/maven" />
            <property name="user" value="root" />
            <property name="password" value="root" />
        </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>
    
    </beans>
  • 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="cn.itcast.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>
  • 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="xxx" namespace="/" extends="struts-default">
      
        </package>
    </struts>
  • log4j.properties
    ### direct log messages to stdout ###
    log4j.appender.stdout=org.apache.log4j.ConsoleAppender
    log4j.appender.stdout.Target=System.out
    log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
    log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
    
    ### set log levels - for more verbose logging change 'info' to 'debug' ###
    #在开发阶段日志级别使用debug
    log4j.rootLogger=debug, stdout
    ### 在日志中输出sql的输入参数 ###
    log4j.logger.org.hibernate.type=TRACE

2.6 创建实体类

  在src/main/java中创建Customer类

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

  get/set...
}

2.7 定义Dao

  在src/main/java中定义CustomerDao接口,实现根据id查询客户信息

  • 接口
    public interface CustomerDao {
        public Customer getById(Long id);
    }
  • 实现类
    public class CustomerDaoImpl extends HibernateDaoSupport implements CustomerDao {
    
        @Override
        public Customer findCustomerById(Long id) {
            return this.getHibernateTemplate().get(Customer.class, id);
        }
    }
  • 在applicationContext.xml中配置dao

       <!-- dao -->
        <bean id="customerDao" class="cn.itcast.dao.impl.CustomerDaoImpl">
            <property name="sessionFactory" ref="sessionFactory"/>
        </bean>

2.8 单元测试

  在src/test/java中创建单元测试类

public class CustomerDaoImplTest {

    @Test
    public void testGetById() {
        // 获取spring容器
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
        // 获取dao
        CustomerDao customerDao = (CustomerDao) applicationContext.getBean("customerDao");
        // 调用dao方法
        Customer customer = customerDao.findCustomerById((long) 1);
        System.out.println(customer);
    }

}

2.9 完成service

  • 接口
    public interface CustomerService {
        public Customer findCustomerById(Long id);
    }
  • 实现类
    public class CustomerServiceImpl implements CustomerService{
        
        private CustomerDao customerDao;
        public void setCustomerDao(CustomerDao customerDao) {
            this.customerDao = customerDao;
        }
    
        @Override
        public Customer findCustomerById(Long id) {
            return customerDao.findCustomerById(id);
        }
    }
  • 在applicationContext.xml中配置service
       <!-- service -->
        <bean id="customerService" class="cn.itcast.service.impl.CustomerServiceImpl">
            <property name="customerDao" ref="customerDao"/>
        </bean>

2.10 完成action

public class CustomerAction extends ActionSupport {
    // 客户信息
    private Customer customer;
    // 客户id
    private Long custId;
    // 依赖注入
    private CustomerService customerService;

    public String findById(){
        customer = customerService.findCustomerById(custId);
        return SUCCESS;
    }
    
    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;
    }

    public void setCustomerService(CustomerService customerService) {
        this.customerService = customerService;
    }
}

在applicationContext.xml中配置action

<!-- action -->
    <bean id="customerAction" class="cn.itcast.action.CustomerAction" scope="prototype">
        <property name="customerService" ref="customerService"/>
    </bean>

在struts.xml中配置action

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

        <action name="findCustomerById" class="customerAction" method="findCustomerById">
            <result name="success">/jsp/test.jsp</result>
        </action>

    </package>

web.xml(加载spring容器,配置struts2前端控制器)

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

2.11 添加jsp页面

   在src/main/webapp/jsp目录下创建test.jsp页面:

<%@ 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>测试</title>
</head>
<body>
    <!-- 从模型对象中获取属性值 -->
    ${customer.custName }
</body>
</html>
原文地址:https://www.cnblogs.com/yft-javaNotes/p/10231604.html