SSM 框架整合

环境和工具

  • maven
  • idea
  • mysql
  • tomcat

初始目录结构

.
├── pom.xml
├── src
│   ├── main
│   │   ├── java
│   │   ├── resources
│   │   └── webapp
│   │       ├── index.jsp
│   │       └── WEB-INF
│   │           └── web.xml
│   └── test
│       └── java
└── SSMDemo.iml

配置项目结构标记文件夹类型:


配置 pox.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>website.yuchen</groupId>
  <artifactId>SSHDemo</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>SSHDemo Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>https://www.yuchen.website</url>

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

    <spring.version>5.1.4.RELEASE</spring.version>
    <mysql.version>8.0.15</mysql.version>
    <servlet.version>4.0.1</servlet.version>
    <mybatis.version>3.5.0</mybatis.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</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-web</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-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>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>2.0.0</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>${mybatis.version}</version>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>${mysql.version}</version>
    </dependency>
    <dependency>
      <groupId>com.mchange</groupId>
      <artifactId>c3p0</artifactId>
      <version>0.9.5.3</version>
    </dependency>

    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>${servlet.version}</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>
  </dependencies>

</project>


web.xml 配置

配置SpringMVC的 DispatcherServlet:配置 servletservlet-mapping

<!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="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" metadata-complete="true">

  <display-name>Archetype Created Web Application</display-name>

  <servlet>
    <servlet-name>SpringMVC-Dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:config/spring/*.xml</param-value>
    </init-param>
  </servlet>

  <servlet-mapping>
    <servlet-name>SpringMVC-Dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

</web-app>

配置的init-param的内容标识了更多需要加载Spring的配置项,所以需要在 resources 资源文件夹下创建 config/spring 文件夹,关于 spring 的配置文件都放在这个文件夹下

当编译好了项目之后,配置项中的classpath就对应了 target 目录下的 classes

也就是说我们的 spring 配置文件在编译之后放在 target/classes/config/spring/(war 模式)



Spring 整合

分别创建:持久层、业务层、控制层 对应的配置文件:

持久层

dao.xml 配置整合Mybatis:

<?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:property-placeholder location="classpath:config/mybatis/jdbc.properties"/>
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}"/>
        <property name="jdbcUrl" value="${jdbc.url}"/>
        <property name="user" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>

        <property name="maxPoolSize" value="30"/>
        <property name="minPoolSize" value="10"/>
        <property name="autoCommitOnClose" value="false"/>  <!-- 关闭连接后不自动commit -->
        <property name="checkoutTimeout" value="10000"/>  <!-- 获取连接超时时间 -->
        <property name="acquireRetryAttempts" value="2"/> <!-- 当获取连接失败重试次数 -->
    </bean>

    <!--Mybatis配置整合-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="configLocation" value="classpath:config/mybatis/mybatisConfig.xml"/>
        <property name="typeAliasesPackage" value="website.yuchen.model"/>
        <property name="mapperLocations" value="classpath:mapper/*.xml"/>
    </bean>
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <property name="basePackage" value="website.yuchen.dao"/>
    </bean>

</beans>

以上使用的是 c3p0 连接池,从 jdbc.properties 文件中加载JDBC配置,所以在对应路径 config/mybatis 下创建 jdbc.properties:

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/SSMDemo?useSSL=false&useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=

注意MySQL的连接版本,这里我使用的是8.0以上的版本

以上dao.xml的配置还需要 config/mybatis/mybatisConfig.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>

</configuration>

这里就用默认 Mybatis 的默认配置

以上就完成了Spring和Mybatis的整合,由Spring来托管核心对象sqlSessionFactory


业务层

创建业务层对应的 service.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"
       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/tx
    http://www.springframework.org/schema/tx/spring-tx.xsd">

    <context:component-scan base-package="website.yuchen.service" />

    <tx:annotation-driven transaction-manager="transactionManager" />    <!--@Transactional注解-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>
</beans>


控制层

用于 Spring MVC 的配置:创建 mvc.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"
       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-3.0.xsd">

    <context:component-scan base-package="website.yuchen.controller" />

    <mvc:annotation-driven />
    <mvc:default-servlet-handler/>  <!--用于静态资源处理-->

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>
</beans>



持久层设计

创建数据库

根据之前在 jdbc.properties 中的设置:

create database SSMDemo;
use SSMDemo;

create table User (
       id int primary key auto_increment,
    name varchar(11) default "XXX",
    age int default 0,
    address varchar(21)
);

insert into User values(1, "AAA", 21, "Shanghai");
insert into User values(2, "BBB", 19, "Beijing");
insert into User values(3, "CCC", 22, "Hangzhou");

在作为Source的java文件夹下创建包website.yuchen.model,编写 User 表对应的 PO 对象UserBean

package website.yuchen.model;

public class UserBean
{
    private Integer id, age;
    private String name, address;

    public Integer getId() {return id;}
    public void setId(Integer id) {this.id = id;}

    public Integer getAge() {return age;}
    public void setAge(Integer age) {this.age = age;}

    public String getName() {return name;}
    public void setName(String name) {this.name = name;}

    public String getAddress() {return address;}
    public void setAddress(String address) {this.address = address;}
}


另外创建包website.yuchen.dao,编辑 CRUD 操作:

package website.yuchen.dao;

import website.yuchen.model.UserBean;
import org.springframework.stereotype.Repository;
import java.util.List;


@Repository
public interface UserMapper {
    public void insert(UserBean user);
    public UserBean findById(Integer id);
    public void update(UserBean user);
    public void deleteById(Integer id);
    public List<UserBean> findAll();
}

于是在resources下另外创建 mapper 文件夹并创建这些操作的配置UserMapper.xml,即 resources/mapper/UserMapper.xml:这个路径已经在之前的 dao.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="website.yuchen.dao.UserMapper">
    <insert id="insert" parameterType="UserBean">
        insert into User(id, name, age, address) 
          values(#{id}, #{name}, #{age}, #{address})
    </insert>

    <delete id="deleteById" parameterType="Integer">
        delete from User where id=#{id}
    </delete>

    <update id="update" parameterType="UserBean">
        update User set name=#{name}, age=#{age}, 
            address=#{address} where id=#{id}
    </update>

    <select id="findById" parameterType="Integer" resultType="UserBean">
        select * from User where id=#{id}
    </select>

    <select id="findAll" resultType="UserBean">
        select * from User;
    </select>

</mapper>


业务层设计

业务层主要用于对持久层提供的数据封装再处理,同样创建包 website.yuchen.service,并定义业务接口以及它的实现类:

package website.yuchen.service;

import website.yuchen.model.UserBean;
import java.util.List;

public interface IUserService {
    public void insert(UserBean user);
    public UserBean findById(Integer id);
    public void update(UserBean user);
    public void deleteById(Integer id);
    public List<UserBean> findAll();
}
package website.yuchen.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import website.yuchen.dao.UserMapper;
import website.yuchen.model.UserBean;
import java.util.List;

@Service
public class UserService implements IUserService
{
    @Autowired
    private UserMapper userMapper;

    @Override
    public void insert(UserBean user) {
        userMapper.insert(user);
    }

    @Override
    public UserBean findById(Integer id) {
        return userMapper.findById(id);
    }

    @Override
    public void update(UserBean user) {
        userMapper.update(user);
    }

    @Override
    public void deleteById(Integer id) {
        userMapper.deleteById(id);
    }

    @Override
    public List<UserBean> findAll() {
        return userMapper.findAll();
    }
}


控制层

这部分是关于Spring MVC中 Controller 的配置:创建包 website.yuchen.controller以及UserController类:

package website.yuchen.controller;

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 org.springframework.web.bind.annotation.RequestMethod;
import website.yuchen.model.UserBean;
import website.yuchen.service.UserService;

import java.util.List;

@Controller
public class UserController
{
    @Autowired
    private UserService userService;

    @RequestMapping
    public String display(Model model)
    {
        List<UserBean> userList = userService.findAll();
        model.addAttribute("userList", userList);
        return "index";
    }

    @RequestMapping("addPage")
    public String add() {
        return "addPage";
    }
    @RequestMapping(value = "add", method = RequestMethod.POST)
    public String add(UserBean user) {
        userService.insert(user);
        return "redirect:index";
    }

    @RequestMapping("deletePage")
    public String delete() {
        return "deletePage";
    }
    @RequestMapping(value = "delete", method = RequestMethod.POST)
    public String delete(Integer id) {
        userService.deleteById(id);
        return "redirect:index";
    }
}

由Spring MVC在配置的视图映射文件,在WEB-INF下新建 jsp 文件夹,视图的jsp文件都保存在这个文件夹下:

创建 index.jsp 用于展示所有的元组,借助 jstl 循环显示表格:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<html>
<head>
    <title>SSM Demo</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <meta charset="UTF-8">
</head>
<body>

<h2 class="page-header"> User表显示所有字段 </h2>

<table>
    <tr>
        <td><button type="button" class="btn btn-primary" onclick="window.location.href='addPage'">添加</button></td>
        <td><button type="button" class="btn btn-success" onclick="window.location.href='deletePage'">删除</button></td>
    </tr>
</table>

<table class="table table-hover table-striped">
    <tr>
        <th>编号</th>
        <th>名字</th>
        <th>年龄</th>
        <th>地址</th>
    </tr>
    <c:forEach var="user" items='${userList}'>
        <tr>
            <td>${user.id}</td>
            <td>${user.name}</td>
            <td>${user.age}</td>
            <td>${user.address}</td>
        </tr>
    </c:forEach>
</table>

</body>
</html>

再分别加入添加 addPage.jsp 和删除 deletePage.jsp 页面:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<html>
<head>
    <title>SSM Demo</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <meta charset="UTF-8">
</head>
<body>

    <h2 class="page-header"> User表添加字段 </h2>

    <form action="add" method="post">
        <div class="form-group">
            <label>id</label>
            <input name="id" type="text" class="form-control" placeholder="id">
        </div>
        <div class="form-group">
            <label>name</label>
            <input name="name" type="text" class="form-control" placeholder="name">
        </div>
        <div class="form-group">
            <label>age</label>
            <input name="age" type="text" class="form-control" placeholder="age">
        </div>
        <div class="form-group">
            <label>address</label>
            <input name="address" type="text" class="form-control" placeholder="address">
        </div>

        <button type="submit" class="btn btn-default">Submit</button>
    </form>

</body>
</html>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<html>
<head>
    <title>SSM Demo</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <meta charset="UTF-8">
</head>
<body>

<h2 class="page-header"> User表删除字段 </h2>

<form action="delete" method="post">
    <div class="form-group">
        <label>id</label>
        <input name="id" type="text" class="form-control" placeholder="id">
    </div>
    <button type="submit" class="btn btn-default">Submit</button>
</form>

</body>
</html>


最终目录结构

.
├── pom.xml
├── src
│   ├── main
│   │   ├── java
│   │   │   └── website
│   │   │       └── yuchen
│   │   │           ├── controller
│   │   │           │   └── UserController.java
│   │   │           ├── dao
│   │   │           │   └── UserMapper.java
│   │   │           ├── model
│   │   │           │   └── UserBean.java
│   │   │           └── service
│   │   │               ├── IUserService.java
│   │   │               └── UserService.java
│   │   ├── resources
│   │   │   ├── config
│   │   │   │   ├── mybatis
│   │   │   │   │   ├── jdbc.properties
│   │   │   │   │   └── mybatisConfig.xml
│   │   │   │   └── spring
│   │   │   │       ├── dao.xml
│   │   │   │       ├── mvc.xml
│   │   │   │       └── service.xml
│   │   │   └── mapper
│   │   │       └── UserMapper.xml
│   │   └── webapp
│   │       └── WEB-INF
│   │           ├── jsp
│   │           │   ├── addPage.jsp
│   │           │   ├── deletePage.jsp
│   │           │   └── index.jsp
│   │           └── web.xml
│   └── test
│       └── java
└── SSMDemo.iml

项目下载:SSM-Demo



参考

(超详细、适合新手入门)IDEA+Maven 整合SSM框架实现简单的增删改查
SpringMVC系列(十)(处理静态资源)和

-------------本文结束-------------