最詳細的SSM(Spring+Spring MVC+MyBatis)項目搭建

速覽

  • 使用Spring+Spring MVC+MyBatis搭建項目
  • 開發工具IDEA(Ecplise步驟類似,代碼完全一樣)
  • 項目類型Maven工程
  • 數據庫MySQL8.0
  • 數據庫連接池:Druid

發現不合適的出門左轉,不要浪費時間~~

數據庫信息如下:

  • 數據庫名:webtest
  • 測試表名稱user

0.png

CREATE TABLE `user` (    `username` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,    `password` varchar(16) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,    `tel` varchar(11) NOT NULL,    `email` varchar(30) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,    `name` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,    PRIMARY KEY (`username`)  ) ENGINE=InnoDB DEFAULT CHARSET=utf8;  

步驟

Step 1:創建Maven工程

  1. 新建Project,選擇Maven,選擇jdk,選擇創建模板為webapp(注意看清名稱)
    1.png
    2.填寫項目信息,然後一路next,最後finish
    2.png

Step 2:添加依賴和插件,修改pom.xml文件,主要信息如下:

  • Spring相關依賴
  • MyBatis相關依賴
  • MySQL連接相關依賴
  • Druid連接池
  • 測試依賴
  • FastJSON依賴
  • Tomcat插件
  • Maven插件
  • 資源拷貝插件(為了避免部分開發工具中不拷貝java包下的資源文件,不是所有人都會遇到這個問題,可以不配,具體請看這裡

pom.xml文件

<?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.demo</groupId>    <artifactId>ssmdemo</artifactId>    <version>1.0-SNAPSHOT</version>    <packaging>war</packaging>      <!--定義版本號-->    <properties>      <spring.version>4.2.4.RELEASE</spring.version>      <junit.version>4.9</junit.version>      <fastjson.version>1.2.28</fastjson.version>      <mybatis.version>3.2.8</mybatis.version>      <mybatis.spring.version>1.2.2</mybatis.spring.version>      <mysql.version>8.0.11</mysql.version>      <druid.version>1.0.9</druid.version>    </properties>      <!--依賴-->    <dependencies>      <!--Spring相關依賴-->      <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>      <dependency>        <groupId>org.springframework</groupId>        <artifactId>spring-webmvc</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-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>      <!--junit-->      <dependency>        <groupId>junit</groupId>        <artifactId>junit</artifactId>        <version>${junit.version}</version>        <scope>test</scope>      </dependency>      <!--fastJson-->      <dependency>        <groupId>com.alibaba</groupId>        <artifactId>fastjson</artifactId>        <version>${fastjson.version}</version>      </dependency>      <!--Servlet-->      <dependency>        <groupId>javax.servlet</groupId>        <artifactId>servlet-api</artifactId>        <version>2.5</version>        <scope>provided</scope>      </dependency>      <!--MyBatis-->      <dependency>        <groupId>org.mybatis</groupId>        <artifactId>mybatis</artifactId>        <version>${mybatis.version}</version>      </dependency>      <!--MyBatis與Spring整合的依賴-->      <dependency>        <groupId>org.mybatis</groupId>        <artifactId>mybatis-spring</artifactId>        <version>${mybatis.spring.version}</version>      </dependency>      <!-- MySql -->      <dependency>        <groupId>mysql</groupId>        <artifactId>mysql-connector-java</artifactId>        <version>${mysql.version}</version>      </dependency>      <!-- 連接池 -->      <dependency>        <groupId>com.alibaba</groupId>        <artifactId>druid</artifactId>        <version>${druid.version}</version>      </dependency>    </dependencies>      <build>      <!-- 自定義資源文件拷貝行為 -->      <resources>        <resource>          <directory>src/main/java</directory>          <includes>            <include>**/*.properties</include>            <include>**/*.xml</include>          </includes>          <filtering>false</filtering>        </resource>        <resource>          <directory>src/main/resources</directory>          <includes>            <include>**/*.properties</include>            <include>**/*.xml</include>          </includes>          <filtering>false</filtering>        </resource>      </resources>        <!--使用的插件-->      <plugins>        <!--上面的資源文件拷貝的插件-->        <plugin>          <groupId>org.apache.maven.plugins</groupId>          <artifactId>maven-resources-plugin</artifactId>          <version>2.7</version>          <configuration>            <encoding>UTF-8</encoding>          </configuration>        </plugin>          <!-- 編譯插件 -->        <plugin>          <groupId>org.apache.maven.plugins</groupId>          <artifactId>maven-compiler-plugin</artifactId>          <version>3.2</version>          <configuration>            <source>1.8</source>            <target>1.8</target>            <encoding>UTF-8</encoding>          </configuration>        </plugin>          <!--tomcat插件-->        <plugin>          <groupId>org.apache.tomcat.maven</groupId>          <artifactId>tomcat7-maven-plugin</artifactId>          <version>2.2</version>          <configuration>            <port>8080</port>            <path>/</path>            <uriEncoding>UTF-8</uriEncoding>          </configuration>        </plugin>        </plugins>    </build>        </project>    

Step 3:修改web.xml 文件(webapp/WEB-INF下),完成內容如下(所有的配置文件稍後會列出):

  • 初始化Spring容器
<!--初始化spring容器-->    <context-param>      <param-name>contextConfigLocation</param-name>      <!--讀取spring文件夾下所有applicationContext-打頭的文件-->      <param-value>classpath:spring/applicationContext-*.xml</param-value>    </context-param>  
  • 創建監聽器,監聽項目啟動的時候初始化我們的Spring容器
<!--監聽器-->    <listener>      <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>    </listener>  
  • 創建一個Fliter,解決POST請求中文亂碼問題(在pom.xml配置Tomcat插件是指定的UTF-8隻能解決GET請求的亂碼問題)
<!-- 解決post亂碼 -->    <filter>      <filter-name>CharacterEncodingFilter</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>    </filter>    <filter-mapping>      <filter-name>CharacterEncodingFilter</filter-name>      <url-pattern>/*</url-pattern>    </filter-mapping>  
  • 創建DispatcherServlet(我們可以使用SpringMVC的基礎)
  <!-- springmvc的前端控制器 -->    <servlet>      <servlet-name>ssmdemo-servlet</servlet-name>      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>      <!-- contextConfigLocation不是必須的, 如果不配置contextConfigLocation, springmvc的配置文件默認在:WEB-INF/servlet的name+"-servlet.xml" -->      <init-param>        <param-name>contextConfigLocation</param-name>        <param-value>classpath:spring/springmvc.xml</param-value>      </init-param>      <load-on-startup>1</load-on-startup>    </servlet>    <servlet-mapping>      <servlet-name>ssmdemo-servlet</servlet-name>      <url-pattern>/</url-pattern>    </servlet-mapping>  
  • 完整的web.xml
<!DOCTYPE web-app PUBLIC   "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"   "http://java.sun.com/dtd/web-app_2_3.dtd" >    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"           xmlns="http://java.sun.com/xml/ns/javaee"           xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"           version="2.5">    <display-name>Archetype Created Web Application</display-name>      <!--初始化spring容器-->    <context-param>      <param-name>contextConfigLocation</param-name>      <param-value>classpath:spring/applicationContext-*.xml</param-value>    </context-param>      <!--監聽器-->    <listener>      <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>    </listener>      <!-- 解決post亂碼 -->    <filter>      <filter-name>CharacterEncodingFilter</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>    </filter>    <filter-mapping>      <filter-name>CharacterEncodingFilter</filter-name>      <url-pattern>/*</url-pattern>    </filter-mapping>      <!-- springmvc的前端控制器 -->    <servlet>      <servlet-name>ssmdemo-servlet</servlet-name>      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>      <!-- contextConfigLocation不是必須的, 如果不配置contextConfigLocation, springmvc的配置文件默認在:WEB-INF/servlet的name+"-servlet.xml" -->      <init-param>        <param-name>contextConfigLocation</param-name>        <param-value>classpath:spring/springmvc.xml</param-value>      </init-param>      <load-on-startup>1</load-on-startup>    </servlet>      <servlet-mapping>      <servlet-name>ssmdemo-servlet</servlet-name>      <url-pattern>/</url-pattern>    </servlet-mapping>    </web-app>    

Step 4:在java下創建需要package(沒有java請創建),方便稍後寫配置文件

  • controller包
  • service包
  • mapper包
  • domain包

3.png

Step 5:在resources(沒有請創建)包下創建spring包,用來存放Spring相關的配置文件,創建springmvc.xml配置文件

  • 開啟controller的掃描
  • 開啟mvc的註解掃描
  • 配置轉換器
    4.png
<?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"         xmlns:mvc="http://www.springframework.org/schema/mvc"         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">        <!--開啟controller掃描 指定掃描的基礎包-->      <context:component-scan base-package="com.demo.controller"/>        <!--開啟註解掃描-->      <mvc:annotation-driven>          <!--指定轉換器為fastjson-->          <mvc:message-converters>              <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter"/>          </mvc:message-converters>      </mvc:annotation-driven>  </beans>  

Step 6:繼續在spring文件下創建applicationContext-service.xml配置文件,配置service層的相關配置

  • 開啟組件掃描
<?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.demo.service"/>  </beans>  

Step 7:繼續在spring文件夾下創建applicationContext-dao.xml配置文件,配置持久層相關配置

  • 在resources下創建properties文件夾,新建db.properties配置文件,配置連接數據庫相關屬性

5.png

db.properties文件內容如下:
數據庫連接驅動、url、用戶名、密碼

  jdbc.driver=com.mysql.cj.jdbc.Driver  jdbc.url=jdbc:mysql://localhost:3306/webtest?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false  jdbc.username=root  jdbc.password=root  
  • 在spring文件夾下創建applicationContext-dao.xml配置文件
    • 配置數據源
    • 配置sqlsession工廠(SqlMapConfig.xml稍後創建)
    • 配置mapper代理

applicationContext-dao.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">        <!--讀取db.properties配置文件內容-->      <context:property-placeholder location="classpath:properties/db.properties"/>        <!--配置數據源-->      <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">          <property name="url" value="${jdbc.url}"/>          <property name="username" value="${jdbc.username}" />          <property name="password" value="${jdbc.password}" />          <property name="driverClassName" value="${jdbc.driver}" />          <property name="maxActive" value="10" />          <property name="minIdle" value="5" />      </bean>        <!--配置sqlsession工廠-->      <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">          <!-- 數據源 -->          <property name="dataSource" ref="dataSource"/>          <!-- 配置文件 -->          <property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml"/>      </bean>        <!--配置mapper代理-->      <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">          <property name="basePackage" value="com.demo.mapper"/>      </bean>  </beans>  

Step 8:在resources文件夾下創建mybatis文件夾,存放mybatis相關配置,

創建SqlMapConfig.xml文件

6.png

SqlMapConfig.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>      <!--配置pojo的別名-->      <typeAliases>          <package name="com.demo.domain"/>      </typeAliases>    </configuration>  

至此,resources文件夾下的內容配置完成,回到java文件夾下

Step 9:在com.demo.domain下創建User實體類

User.java

package com.demo.domain;    import java.io.Serializable;    /**   * @author 11699   * @date 20/3/27 - 16:53   */  public class User implements Serializable {        private String username;      private String password;      private String tel;      private String email;      private String name;        //省略getter和setter方法  }    

Step 10:在mapper文件下創建接口UserMapper,同時創建同名的UserMapper.xml文件,寫一個簡單的查詢全部的方法

UserMapper接口

package com.demo.mapper;    import com.demo.domain.User;    import java.util.List;    /**   * @author 11699   * @date 20/3/27 - 16:57   */  public interface UserMapper {        List<User> findAll();  }    

UserMapper.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.demo.mapper.UserMapper">        <!--查詢全部 id必須與接口的方法名對應-->      <select id="findAll" resultType="com.demo.domain.User">          select * from user      </select>  </mapper>  

Step 11:service下創建接口UserService,同時創建impl包,在impl包下創建UserServiceImpl類,擴展UserService接口

在接口中定義個查詢全部的方法,並在實現類中實現此方法

UserService接口

package com.demo.service;    import com.demo.domain.User;    import java.util.List;    /**   * @author 11699   * @date 20/3/27 - 17:07   */  public interface UserService {        /**       * 查找全部User       * @return User       */      List<User> findAll();  }    

UserServiceImpl實現類(不要忘記@Service註解)

package com.demo.service.impl;    import com.demo.domain.User;  import com.demo.mapper.UserMapper;  import com.demo.service.UserService;  import org.springframework.beans.factory.annotation.Autowired;  import org.springframework.stereotype.Service;    import java.util.List;    /**   * @author 11699   * @date 20/3/27 - 17:08   */    //別忘了service註解哦  @Service  public class UserServiceImpl implements UserService {        //注入UserMapper對象      @Autowired      private UserMapper mapper;          @Override      public List<User> findAll() {          return mapper.findAll();      }  }    

Step 12:在controller下創建UserController類

package com.demo.controller;    import com.demo.domain.User;  import com.demo.service.UserService;  import org.springframework.beans.factory.annotation.Autowired;  import org.springframework.web.bind.annotation.RequestMapping;  import org.springframework.web.bind.annotation.RestController;    import java.util.List;    /**   * @author 11699   * @date 20/3/27 - 17:12   */  @RestController  @RequestMapping("/user")  public class UserController {        @Autowired      private UserService userService;        @RequestMapping("/all")      public List<User> findAll(){          return userService.findAll();      }  }  

運行測試配置

7.png
啟動沒有報錯的話就可以在瀏覽器中測試訪問:

http://localhost:8080/user/all  

成功返回JSON串
8.png

項目完整結構

9.png

├─.idea  │  ├─codeStyles  │  ├─dictionaries  │  └─inspectionProfiles  ├─src  │  └─main  │      ├─java  │      │  └─com  │      │      └─demo  │      │          ├─controller  │      │          ├─domain  │      │          ├─mapper  │      │          └─service  │      │              └─impl  │      ├─resources  │      │  ├─mybatis  │      │  ├─properties  │      │  └─spring  │      └─webapp  │          └─WEB-INF  └─target      ├─apache-tomcat-maven-plugin      ├─classes      │  ├─com      │  │  └─demo      │  │      ├─controller      │  │      ├─domain      │  │      ├─mapper      │  │      └─service      │  │          └─impl      │  ├─mybatis      │  ├─properties      │  └─spring      ├─generated-sources      │  └─annotations      ├─maven-status      │  └─maven-compiler-plugin      │      └─compile      │          └─default-compile      └─tomcat          ├─conf          ├─logs          ├─webapps          └─work              └─Tomcat                  └─localhost                      └─_  

源碼下載

點擊這裡下載源碼