Maven专题(三)-maven构建SSM工程

1.需求

实现 SSM工程构建,规范依赖管理。

2.准备数据库

导入以下语句
在这里插入图片描述

3.创建一个 maven 工程

1.新建一个 ssm_maven 项目,使用下图选中的骨架
在这里插入图片描述2、 填写坐标
在这里插入图片描述3、查看是否使用的自己的私服
在这里插入图片描述5、 在 main 目录下新建 java 和 resources 文件夹
在这里插入图片描述
6、把 java 和 resources 文件夹转成 source root
在这里插入图片描述7、修改编译版本,在 pom.xml 文件中添加

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

4. 知识点准备

4.1 什么是依赖传递

先添加 springmvc 的核心依赖的坐标

  <dependencies>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>4.2.4.RELEASE</version>
    </dependency>
  </dependencies>

会发现出现除了 spring-webmvc 以外的其他 jar。 因为我们的项目依赖 spring-webmvc.jar,而
spring-webmv.jar 会依赖 spring-beans.jar 等等, 所以 spring-beans.jar 这些 jar 包也出现在了我
们的 maven 工程中, 这种现象我们称为依赖传递。 从下图中可看到他们的关系:(请注意
spring-beans 的版本)
在这里插入图片描述在这里插入图片描述

4.2 依赖冲突的解决

接着添加一个依赖
在这里插入图片描述在这里插入图片描述
我们会发现这两个 jar 包同时都依赖了 spring-beans,但是spring-webmvc 依赖 spirng-beans-4.2.4, spring-context 依赖 spring-beans-5.0.2,但是发现spirng-beans-4.2.4 加入到工程中。而我们希望 spring-beans-5.0.2 加入工程。 这就造成了依赖冲突。 解决依赖冲突有以下原则:

4.2.1 依赖调解原则

maven 自动按照下边的原则调解:
1、第一声明者优先原则
在 pom 文件定义依赖,先声明的依赖为准。
测试:
如果将上边 spring-webmvc 和 spring-context 顺序颠倒,系统将导入 spring-beans-5.0.2。
分析:
由于 spring-webmvc 在前边以 spring-webmvc 依赖的 spring-beans-5.0.2 为准,所以最终spring-beans-5.0.2 添加到了工程中.
在这里插入图片描述
2、路径近者优先原则
例如: 还是上述情况, spring-contex 和 spring-webmvc 都会传递过来 spirng-beans, 那
如果直接把 spring-beans 的依赖直接写到 pom 文件中,那么项目就不会再使用其他依赖传
递来的 spring-beans,因为自己直接在 pom 中定义 spring-beans 要比其他依赖传递过来的路
径要近。
在本工程中的 pom 中加入 spirng-beans-5.0.2 的依赖,根据路径近者优先原则,系统将导入
spirng-beans-5.0.2:

  <dependencies>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>4.2.4.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.0.2.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
      <version>5.0.2.RELEASE</version>
    </dependency>

  </dependencies>

4.2.2 排除依赖

上边的问题也可以通过排除依赖方法辅助依赖调解,如下:
比如在依赖 spring-webmvc 的设置中添加排除依赖,排除 spring-beans,
下边的配置表示:依赖 spring-webmvc,但排除 spring-webmvc 所依赖的 spring-beans。

  <dependencies>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>4.2.4.RELEASE</version>
      <exclusions>
        <exclusion>
          <groupId>org.springframework</groupId>
          <artifactId>spring-beans</artifactId>
        </exclusion>
      </exclusions>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.0.2.RELEASE</version>
    </dependency>

  </dependencies>

4.2.3 锁定版本

面对众多的依赖,有一种方法不用考虑依赖路径、声明优化等因素可以采用直接锁定版
本的方法确定依赖构件的版本,版本锁定后则不考虑依赖的声明顺序或依赖的路径,以锁定
的版本的为准添加到工程中,此方法在企业开发中常用。
如下的配置是锁定了 spring-beans 和 spring-context 的版本:

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

还可以把版本号提取出来,使用标签设置成变量。

 <properties>
    <spring.version>5.0.2.RELEASE</spring.version>
 </properties>

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

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

 <dependencies>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-context</artifactId>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-beans</artifactId>
      </dependency>
</dependencies>

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

5. 定义 pom.xml

maven 工程首先要识别依赖, web 工程实现 SSM 整合,需要依赖 spring-webmvc5.0.2、
spring5.0.2、 mybatis3.4.5 等,在 pom.xml 添加工程如下依赖:
(在实际企业开发中会有架构师专门来编写 pom.xml)
分两步:
1)锁定依赖版本
2)添加依赖

<?xml version="1.0" encoding="UTF-8"?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one
  or more contributor license agreements.  See the NOTICE file
  distributed with this work for additional information
  regarding copyright ownership.  The ASF licenses this file
  to you under the Apache License, Version 2.0 (the
  "License"); you may not use this file except in compliance
  with the License.  You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing,
  software distributed under the License is distributed on an
  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  KIND, either express or implied.  See the License for the
  specific language governing permissions and limitations
  under the License.
-->
<!-- $Id: pom.xml 642118 2008-03-28 08:04:16Z reinhard $ -->
<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/maven-v4_0_0.xsd">

    <modelVersion>4.0.0</modelVersion>
    <packaging>war</packaging>

    <name>ssm_maven</name>
    <groupId>com.bruceliu.ssm_maven</groupId>
    <artifactId>ssm_maven</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <spring.version>5.0.2.RELEASE</spring.version>
        <springmvc.version>5.0.2.RELEASE</springmvc.version>
        <mybatis.version>3.4.5</mybatis.version>
    </properties>

    <!--锁定依赖版本-->
    <dependencyManagement>
        <dependencies>
            <!-- Mybatis -->
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>${mybatis.version}</version>
            </dependency>
            <!-- springMVC -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-webmvc</artifactId>
                <version>${springmvc.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <!-- spring -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-core</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-aop</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-web</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-expression</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-beans</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-context-support</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-jdbc</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-tx</artifactId>
                <version>${spring.version}</version>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <!--添加依赖-->
    <dependencies>
        <!-- Mybatis 和 mybatis 与 spring 的整合 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.1</version>
        </dependency>
        <!-- MySql 驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.32</version>
        </dependency>
        <!-- druid 数据库连接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.9</version>
        </dependency>
        <!-- springMVC 核心-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
        </dependency>
        <!-- spring 相关 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-expression</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
        </dependency>
        <dependency>
            <!-- junit 测试 -->
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <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>
        <!-- jstl -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
    </dependencies>


    <build>
        <plugins>
            <plugin>
                <groupId>org.mortbay.jetty</groupId>
                <artifactId>maven-jetty-plugin</artifactId>
                <version>6.1.7</version>
                <configuration>
                    <connectors>
                        <connector implementation="org.mortbay.jetty.nio.SelectChannelConnector">
                            <port>8888</port>
                            <maxIdleTime>30000</maxIdleTime>
                        </connector>
                    </connectors>
                    <webAppSourceDirectory>${project.build.directory}/${pom.artifactId}-${pom.version}
                    </webAppSourceDirectory>
                    <contextPath>/</contextPath>
                </configuration>
            </plugin>

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

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

6. Dao 层

在 src/main/java 中定义 dao 接口,实现根据 id 查询商品信息:

6.1 pojo 模型类

在 src/main/java 创建模型类
在这里插入图片描述

package com.bruceliu.pojo;


public class Employee {

  private Long id;
  private String lastName;
  private String myemail;
  private String gender;
  private Long age;

  public Long getId() {
    return id;
  }

  public void setId(Long id) {
    this.id = id;
  }

  public String getLastName() {
    return lastName;
  }

  public void setLastName(String lastName) {
    this.lastName = lastName;
  }

  public String getMyemail() {
    return myemail;
  }

  public void setMyemail(String myemail) {
    this.myemail = myemail;
  }

  public String getGender() {
    return gender;
  }

  public void setGender(String gender) {
    this.gender = gender;
  }

  public Long getAge() {
    return age;
  }

  public void setAge(Long age) {
    this.age = age;
  }
}

6.2.dao 层代码

在这里插入图片描述

6.3.配置文件

注意配置文件的位置
在这里插入图片描述内容如下

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.bruceliu.dao.EmployeeMapper" >
    <select id="findById" parameterType="int" resultType="com.bruceliu.pojo.Employee">
        select * from employee where id=#{id}
    </select>
</mapper>

在 src/main/resources 创建 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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!-- 数据库连接池 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <!-- 驱动 -->
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <!-- url -->
        <property name="url" value="jdbc:mysql://localhost:3306/ssm" />
        <!-- 用户名 -->
        <property name="username" value="root" />
        <!-- 密码 -->
        <property name="password" value="123456" />
    </bean>

    <!-- mapper 配置 -->
    <!-- 让 spring 管理 sqlsessionfactory 使用 mybatis 和 spring 整合包中的 -->
    <bean id="sqlSessionFactory"
          class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 数据库连接池 -->
        <property name="dataSource" ref="dataSource" />
        <property name="typeAliasesPackage" value="com.bruceliu.pojo"/>
    </bean>

    <!-- mapper 扫描器 :用来产生代理对象-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.bruceliu.dao"></property>
    </bean>

</beans>

在 src/main/resources 配置 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

6.4 单元测试

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

package com.bruceliu.test;

import com.bruceliu.dao.EmployeeMapper;
import com.bruceliu.pojo.Employee;
import com.sun.tools.javac.jvm.Items;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @Auther: bruceliu
 * @Date: 2020/1/10 23:42
 * @QQ:1241488705
 * @Description:
 */
public class TestMyBatis {

    @Test
    public void testFindItemsById() {
        //获取 spring 容器
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
        //获取 Mapper
        EmployeeMapper employeeMapper = applicationContext.getBean(EmployeeMapper.class);
        //调用 Mapper 方法
        Employee employee = employeeMapper.findById(2L);
        System.out.println(employee);
    }
}

7. Service层

7.1代码

/**
 * @Auther: bruceliu
 * @Date: 2020/1/13 23:10
 * @QQ:1241488705
 * @Description:
 */
@Service
@Transactional
public class EmployeeServiceImpl implements EmployeeService {

    @Resource
    EmployeeMapper employeeMapper;

    @Override
    public Employee findById(Long id) {
        return employeeMapper.findById(id);
    }
}

7.2配置文件

在 applicationContext.xml 中配置 service

 <context:component-scan base-package="com.bruceliu.service"/>

8. Web层

8.1代码

/**
 * @Auther: bruceliu
 * @Date: 2020/1/13 23:15
 * @QQ:1241488705
 * @Description:
 */
@Controller
@RequestMapping("/emplyee/")
public class EmployeeController {

    @Autowired
    EmployeeService employeeService;

    // 展示商品信息页面
    @RequestMapping("/showEmployee")
    public String showEmployee(Long id,Model model){
        Employee employee = employeeService.findById(id);
        model.addAttribute("employee", employee);
        return "employee";
    }
}

8.2配置文件

在springmvc.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:context="http://www.springframework.org/schema/context"
       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">

    <context:component-scan
            base-package="com.bruceliu.controller"></context:component-scan>

    <!-- 配置视图解析器的前缀和后缀 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>

</beans>

Web.xml
加载 spring 容器,配置 springmvc 前端控制器

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

<web-app version="2.4"
         xmlns="http://java.sun.com/xml/ns/j2ee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

    <!-- 前端控制器 加载 springmvc 容器 -->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>*.action</url-pattern>
    </servlet-mapping>

    <!-- 监听器 加载 spring 容器 -->
    <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>

</web-app>
        

9. Jsp

/WEB-INF/jsp/emplpyee.jsp 如下:

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>员工信息</title>
</head>
<body>
<form>
    <table width="100%" border=1>
        <tr>
            <td>员工编号</td>
            <td> ${employee.id } </td>
        </tr>
        <tr>
            <td>员工姓名</td>
            <td> ${employee.lastName} </td>
        </tr>
        <tr>
            <td>员工邮箱</td>
            <td>${employee.myemail}</td>
        </tr>
        <tr>
            <td>员工性别</td>
            <td>${employee.gender} </textarea>
            </td>
        </tr>
    </table>
</form>
</body>
</html>

10. 运行与调试

添加 tomcat7插件,双击右侧 tomcat7 运行
在这里插入图片描述运行结果如下:
在这里插入图片描述

发布了274 篇原创文章 · 获赞 80 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/BruceLiu_code/article/details/103927587