1.环境要求

Eclipse 4.14.0
JDK 1.8.x
Apache Maven 3.6.1
操作系统:Windows 10

2.安装Maven

下载Apache Maven,下载地址为http://maven.apache.org/download.cgi

在空间富裕的分区新建一个maven目录(最好不要是C盘),然后将下载后的压缩包解压到该目录,并在该目录新建一个repository目录作为本地仓库目录,构建好的目录结构如图所示

修改配置文件,配置文件位于apache-maven-3.6.1/conf/settings.xml。

修改本地仓库目录为刚才新建的repository目录,修改方式如图所示

修改下载镜像源为阿里云,在配置文件mirrors节点内容新增如下内容

<mirror>
    <id>alimaven</id>
    <name>aliyun maven</name>
    <url>http://maven.aliyun.com/nexus/content/groups/public/</url>
    <mirrorOf>central</mirrorOf>
</mirror>

设置JDK默认版本,在profiles节点下新增如下所示的配置

<profile>
    <id>jdk-1.8</id>
    <activation>
        <activeByDefault>true</activeByDefault>
        <jdk>1.8</jdk>
    </activation>
    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <maven.compiler.compilerVersion>1.8</maven.compiler.compilerVersion>
    </properties>
</profile>

打开elipse安装Maven,打开首选项菜单,然后按照下面图示操作步骤完成设置

3.建立maven web项目

建立里Maven操作步骤按照下面图示步骤操作

等待项目构建完成后可以看到如下图所示的项目结构

构建完成的maven项目index.jsp会报错,此时只需要在pom.xml文件中加入servlet-api依赖即可,

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
    <scope>provided</scope>
</dependency>

修改web.xml,使用模板生成的web.xml版本是2.3的版本,它不支持jstl遍历,此时需要我们修改成3.1版本,修改后的web.xml如下所示。

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 3.1//EN"
 "http://java.sun.com/dtd/web-app_3_1.dtd" >

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    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>Archetype Created Web Application</display-name>
</web-app>

修改编译版本为1.8,将pom配置中的

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

修改为

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

加入Tomcat7插件,在pom.xml,build -> pluginManagement -> plugins节点下面加入如下配置

<!-- tomcat插件  -->
<plugin>
    <groupId>org.apache.tomcat.maven</groupId>
    <artifactId>tomcat7-maven-plugin</artifactId>
    <version>2.2</version>
    <configuration>
        <port>80</port>
        <path>/</path>
        <uriEncoding>UTF-8</uriEncoding>
        <server>tomcat7</server>
    </configuration>
</plugin>

然后按照下面图示的方式启动tomcat服务器

小提示:
tomcat7:deploy –部署一个web war包
tomcat7:reload –重新加载web war包
tomcat7:start –启动tomcat
tomcat7:stop –停止tomcat
tomcat7:undeploy–停止一个war包
tomcat7:run 启动嵌入式tomcat ,并运行当前项目

启动成功后可以在控制台中看到如下输出

在浏览器中测试服务访问,然后在浏览器中访问服务器,看到如下图所示的效果表示服务器启动成功

到此mavenweb项目构建完成了

4.导入SSM依赖jar包

下面是项目完整依赖配置

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <!-- spring版本号 -->
    <spring.version>5.1.10.RELEASE</spring.version>
    <!-- Mybatis版本号 -->
    <mybatis.version>3.4.6</mybatis.version>
    <mybatis-spring.version>1.3.2</mybatis-spring.version>
</properties>

<dependencies>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>
    <!-- Servlet Api -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.1.0</version>
        <scope>provided</scope>
    </dependency>
    <!-- JSTL -->
    <dependency>
        <groupId>org.apache.taglibs</groupId>
        <artifactId>taglibs-standard-spec</artifactId>
        <version>1.2.5</version>
    </dependency>
    <dependency>
        <groupId>org.apache.taglibs</groupId>
        <artifactId>taglibs-standard-impl</artifactId>
        <version>1.2.5</version>
    </dependency>
    <!-- MySQL -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.48</version>
    </dependency>
    <!-- 德鲁伊数据源 -->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
        <version>1.1.13</version>
    </dependency>
    <!-- Mybatis -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>${mybatis.version}</version>
    </dependency>
    <!-- Spring Mybatis -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>${mybatis-spring.version}</version>
    </dependency>
    <!-- SpringMVC -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <!-- Spring JDBC-->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <!-- Spring TX-->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-tx</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <!-- Spring Test-->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <!-- AOP aspectj -->
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>1.9.4</version>
    </dependency>
    <!-- JSON -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.9.2</version>
    </dependency>
    <!-- Log4j -->
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-core</artifactId>
        <version>2.9.1</version>
    </dependency>
</dependencies>

修改配置后保存,就会开始自动下载各种依赖的jar包。

在配置讲解之前我们先看一下完成项目的目录结构,如下图所示:

5.配置mybatis

在src/main目录下面新建一个resources目录用于存放配置,注意目录名必须是resources

5.1 配置数据库连接配置

在resources目录下新建database.properties配置文件然后书写一下内容

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://数据库主机地址:数据库端口/数据库名
jdbc.username=用户名
jdbc.password=密码
#连接池配置,根据实际情况调整
initialSize=1
minIdle=1
maxActive=10
maxWait=60000
timeBetweenEvictionRunsMillis=2000
minEvictableIdleTimeMillis=600000
maxEvictableIdleTimeMillis=900000
validationQuery=select 1
testWhileIdle=true
testOnBorrow=false
testOnReturn=false
keepAlive=true
phyMaxUseCount=500

5.2 log42日志配置

在resources目录新建log4j2.xml配置,然后写入以下配置

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/2002/xmlspec/dtd/2.10/xmlspec.dtd">
<Configuration status="WARN">
    <Appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
        </Console>
    </Appenders>

    <Loggers>
        <Root level="debug">
            <AppenderRef ref="Console" />
        </Root>
        <!-- <logger name="org.springframework.web" level="error" ></logger> -->
    </Loggers>
</Configuration>

5.3 mybaits全局配置

在resources目录新建mybatis-config.xml配置文件,然后写入如下配置

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd" >
<configuration>
    <!--配置全局设置-->
    <settings>
        <!--配置日志实现方式-->
        <setting name="logImpl" value="LOG4J2"/>
        <!--配置列名和属性的下划线转驼峰-->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
        <!--配置主键生成策略启用-->
        <setting name="useGeneratedKeys" value="true"/>
        <!--配置缓存设置-->
        <setting name="cacheEnabled" value="true"/>
        <!--是否启用懒加载(延迟加载)-->
        <setting name="lazyLoadingEnabled" value="true"/>
        <!--是否及时加载-->
        <setting name="aggressiveLazyLoading" value="false"/>
    </settings>
    <!--配置别名映射-->
    <typeAliases>
        <package name="com.xuetang9.domain"/>
    </typeAliases>
</configuration>

5.4 spring整合mybaits配置

在resources目录下新建一个spring目录,用于存放spring配置,然后在spring目录下新建一个spring-mybatis.xml配置文件,然后写入如下配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    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
       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">
    <!--1. 配置属性文件的读取 -->
    <context:property-placeholder
        location="classpath:database.properties" file-encoding="UTF-8" />
    <!--2. 配置数据源 -->
    <bean id="dataSource"
        class="com.alibaba.druid.pool.DruidDataSource" init-method="init"
        destroy-method="close">
        <!--配置的是JDBC基础属性 -->
        <property name="driverClassName" value="${jdbc.driver}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />

        <!--配置连接池的设置 -->
        <!-- 配置初始化大小、最小、最大 -->
        <property name="initialSize" value="${initialSize}" />
        <property name="minIdle" value="${minIdle}" />
        <property name="maxActive" value="${maxActive}" />

        <!-- 配置获取连接等待超时的时间 -->
        <property name="maxWait" value="${maxWait}" />

        <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
        <property name="timeBetweenEvictionRunsMillis" value="${timeBetweenEvictionRunsMillis}" />

        <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
        <property name="minEvictableIdleTimeMillis" value="${minEvictableIdleTimeMillis}" />
        <property name="maxEvictableIdleTimeMillis" value="${maxEvictableIdleTimeMillis}" />

        <property name="validationQuery" value="${validationQuery}" />
        <property name="testWhileIdle" value="${testWhileIdle}" />
        <property name="testOnBorrow" value="${testOnBorrow}" />
        <property name="testOnReturn" value="${testOnReturn}" />

        <property name="keepAlive" value="${keepAlive}" />
        <property name="phyMaxUseCount" value="${phyMaxUseCount}" />
    </bean>

    <!--3. 配置SqlSessionFactory -->
    <bean id="sessionFactory"
        class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation"
            value="classpath:mybatis-config.xml"></property>
        <property name="mapperLocations"
            value="classpath:mapper/*.xml" />
    </bean>

    <!--4. 配置Mapper -->
    <!--使用Mapper配置扫描器 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="sqlSessionFactoryBeanName"
            value="sessionFactory" />
        <property name="basePackage" value="com.xuetang9.mapper" />
    </bean>

    <!--5. 配置事务 -->
    <bean id="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>

    <!--6. 配置扫描的业务逻辑包 -->
    <context:component-scan
        base-package="com.xuetang9.service" />

    <!--配置AOP自动代理 -->
    <aop:aspectj-autoproxy />

    <!--7. 启动事务的扫描 -->
    <tx:annotation-driven
        transaction-manager="transactionManager" proxy-target-class="true" />
</beans>

6.配置springmvc

6.1 配置spring mvc servlet

在spring配置目录下面新增springmvc-servlet.xml配置,然后写入如下配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       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
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd">

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

    <!--2. 配置静态资源过滤-->
    <mvc:default-servlet-handler/>
    <!--<mvc:resources mapping="/static/" location="/static/**"/>-->

    <!--3. 配置扫描的包-->
    <context:component-scan base-package="com.xuetang9.web"/>

    <!--4. 启用MVC注解扫描-->
    <mvc:annotation-driven/>
</beans>

6.2 配置web.xml

下面是web.xml所有配置内容

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 3.1//EN"
 "http://java.sun.com/dtd/web-app_3_1.dtd" >

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
    version="3.1">

    <!--配置Spring IOC容器的创建 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring/spring-mybatis.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!--配置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:spring/springmvc-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>SpringMVC</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!--配置字符编码过滤器 -->
    <filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

7.编写java代码

在src/main目录下面新增一个java目录用于存放java源文件,注意目录名必须是java

7.1 编写测试实体类

创建java包com.xuetang9.domain,然后在domain包下面新建Test实体类,实体类代码如下

package com.xuetang9.domain;
public class Test {
    private Integer id;
    private String name;
    @Override
    public String toString() {
        return "Test [id=" + id + ", name=" + name + "]";
    }
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

7.2 编写测试Mapper接口

创建java包com.xuetang9.mapper,然后在mapper包下面新建TestMapper接口,接口代码如下

package com.xuetang9.mapper;
import java.util.List;
import com.xuetang9.domain.Test;
public interface TestMapper {
    List<Test> queryAll();
}

7.3 编写测试Mapper实现xml

在resources目录下新建一个mapper目录,用于存放mapper实现配置,然后在mapper目录下面创建TestMapper.xml,在配置文件中写入如下配置

<?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.xuetang9.mapper.TestMapper">
    <select id="queryAll" resultType="Test">
        select * from test
    </select>
</mapper>

7.4 编写测试service

创建java包com.xuetang9.service,然后在service包下面新建TestService接口,接口代码如下

package com.xuetang9.service;
import java.util.List;
import com.xuetang9.domain.Test;
public interface TestService {
    List<Test> queryAll();
}

7.5 编写测试service实现类

创建java包com.xuetang9.service.impl,然后在impl包下面新建TestServiceImpl类,实现类代码如下

package com.xuetang9.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.xuetang9.domain.Test;
import com.xuetang9.mapper.TestMapper;
import com.xuetang9.service.TestService;
@Transactional
@Service
public class TestServiceImpl implements TestService {
    @Autowired
    private TestMapper mapper;
    @Override
    public List<Test> queryAll() {
        return mapper.queryAll();
    }
}

7.6 编写测试控制器

创建java包com.xuetang9.web,然后在web包下面新建类IndexController,控制类代码如下

package com.xuetang9.web;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import com.xuetang9.service.TestService;
@Controller
public class IndexController {
    @Autowired
    private TestService service;
    @RequestMapping("/")
    public String index(Model model) {
        model.addAttribute("data", service.queryAll());
        return "index";
    }
}

8.编写视图代码

在WEB-INF下面新建一个views目录,作为所有访问页面的根目录,然后在views目录下面新建index.jsp,同时将webapp目录下面的index.jsp删除掉,index.jsp的代码如下

<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>测试数据显示页</title>
</head>
<body>
    <c:if test="${!empty data}">
        <h1>后端获取的数据如下:</h1>
        <c:forEach var="item" items="${data}">
            <p>${item.id},${item.name}</p>
        </c:forEach>
    </c:if>
    <c:if test="${empty data}">获取数据失败</c:if>
</body>
</html>

然后在数据建立test表,test表只有两个字段id和name,然后在表里面加入测试数据。
最后启动tomcat服务器进行测试,如果看到类似下图所示的效果表示,我们已经成功搭建好了SSM项目

Leave a Comment