SSM整合

本文涉及的产品
云数据库 RDS MySQL,集群系列 2核4GB
推荐场景:
搭建个人博客
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
云数据库 RDS MySQL,高可用系列 2核4GB
简介: SSM整合

准备工作

1、创建Maven Module

2、导入依赖

<?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.jerry.ssm</groupId>
    <artifactId>ssm</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>
    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <spring.version>5.3.1</spring.version>
    </properties>
    <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>
        <!--springmvc-->
        <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-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-test</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!-- Mybatis核心 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.7</version>
        </dependency>
        <!--mybatis和spring的整合包-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.6</version>
        </dependency>
        <!-- 连接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.9</version>
        </dependency>
        <!-- junit测试 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <!-- MySQL驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.27</version>
        </dependency>
        <!-- log4j日志 -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper -->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>5.2.0</version>
        </dependency>
        <!-- 日志 -->
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.2.3</version>
        </dependency>
        <!-- ServletAPI -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.12.1</version>
        </dependency>
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.1</version>
        </dependency>
        <!-- Spring5和Thymeleaf整合包 -->
        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf-spring5</artifactId>
            <version>3.0.12.RELEASE</version>
        </dependency>
    </dependencies>
</project>

3、添加web模块

d91fd0c266894b7dbd69013f02dca402.png

8a2374d824864ee7a2e65a34e387f622.png

4、建库建表

CREATE DATABASE ssm;
USE ssm;
CREATE TABLE `t_emp` (
`emp_id` INT(11) NOT NULL AUTO_INCREMENT,
`emp_name` VARCHAR(20) DEFAULT NULL,
`age` INT(11) DEFAULT NULL,
`sex` CHAR(1) DEFAULT NULL,
`email` VARCHAR(50) DEFAULT NULL,
PRIMARY KEY (`emp_id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8

3dd86aea4c454811bdbf51c0042b3b20.png

5、配置web.xml

<?xml version="1.0" encoding="UTF-8"?>
<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_4_0.xsd"
         version="4.0">
    <!-- 配置Spring的编码过滤器 -->
    <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>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <!-- 配置处理请求方式PUT和DELETE的过滤器 -->
    <filter>
        <filter-name>HiddenHttpMethodFilter</filter-name>
        <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>HiddenHttpMethodFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <!-- 配置SpringMVC的前端控制器 -->
    <servlet>
        <servlet-name>DispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!-- 设置SpringMVC的配置文件的位置和名称 -->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:SpringMVC.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>DispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <!-- 设置Spring的配置文件的位置和名称 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:Spring.xml</param-value>
    </context-param>
    <!-- 配置Spring的监听器 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
</web-app>

6、创建并配置 SpringMVC.xml文件

SpringMVC 管理 controller层,因此先创建EmployeeController.java

8af20b2d01c6493697aa54eba7da97c9.png

创建 SpringMVC.xml


cdea0dd7e4bf44f88fa1cab4ab7031bf.png

配置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"
       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">
    <!--扫描控制层组件-->
    <context:component-scan base-package="com.jerry.ssm.controller"></context:component-scan>
    <!--配置视图解析器-->
    <bean id="viewResolver"
          class="org.thymeleaf.spring5.view.ThymeleafViewResolver">
        <property name="order" value="1"/>
        <property name="characterEncoding" value="UTF-8"/>
        <property name="templateEngine">
            <bean class="org.thymeleaf.spring5.SpringTemplateEngine">
                <property name="templateResolver">
                    <bean
                            class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver">
                        <!-- 视图前缀 -->
                        <property name="prefix" value="/WEB-INF/templates/"/>
                        <!-- 视图后缀 -->
                        <property name="suffix" value=".html"/>
                        <property name="templateMode" value="HTML5"/>
                        <property name="characterEncoding" value="UTF-8"/>
                    </bean>
                </property>
            </bean>
        </property>
    </bean>
    <!-- 配置访问首页的视图控制 -->
    <mvc:view-controller path="/" view-name="index"></mvc:view-controller>
    <!-- 配置默认的servlet处理静态资源 -->
    <mvc:default-servlet-handler />
    <!-- 开启MVC的注解驱动 -->
    <mvc:annotation-driven />
    <!--    配置文件上传解析器-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean>
</beans>

在【WEB-INF】下新建【templates目录】–>【index.html】


942bc656547c43b7a27f2fd4c3975b43.png

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
</head>
<body>
<h1>index.html</h1>
</body>
</html>

7、导入Tomcat服务器

facee3c7f27a40b08e708e487d5f9f88.png


1666473882344b5fb658df9a1c1b87f0.png


3ec69e0633d34fc0bcee99fd1813c3fa.png


a6d62055faf0411aaa70181a3826d0c3.png

启动tomcat 会跳转到首页

9b3da6fa1560456daa01eb13f7d839f9.png



8、创建并配置Spring.xml文件

Spring 管理 service 层,因此先创建EmployeeService.java

ee2d0187fdcf4a95950289154e886f55.png

创建EmployeeServiceImpl.java

83d44004b7804549b187bea821181233.png

创建属性文件jdbc.properties

jdbc.username=root
jdbc.password=root
jdbc.url=jdbc:mysql://localhost:3306/ssm?serverTimezone=UTC
jdbc.driver=com.mysql.cj.jdbc.Driver

配置Spring.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 https://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="com.jerry.ssm">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
    <!-- 引入jdbc.properties -->
    <context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>
    <!-- 配置Druid数据源 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driver}"></property>
        <property name="url" value="${jdbc.url}"></property>
        <property name="username" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>
    <!--    配置事务管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!--
    开启事务的注解驱动
    将使用注解@Transactional标识的方法或类中所有的方法进行事务管理
    -->
    <tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
    <!-- 配置用于创建SqlSessionFactory的工厂bean,可以直接在Spring的IOC 中获取 SqlSessionFactory-->
    <bean class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 设置MyBatis配置文件的路径(可以不设置) -->
        <property name="configLocation" value="classpath:mybatis-config.xml"></property>
        <!-- 设置数据源 -->
        <property name="dataSource" ref="dataSource"></property>
        <!-- 设置类型别名所对应的包 -->
        <property name="typeAliasesPackage" value="com.jerry.ssm.pojo"></property>
        <!--设置映射文件的路径若映射文件所在路径和mapper接口所在路径一致,则不需要设置-->
        <!--<property name="mapperLocations" value="classpath:mapper/*.xml"></property>-->
    </bean>
    <!--  配置mapper接口的扫描配置由mybatis-spring提供,可以将指定包下所有的mapper接口创建动态代理并将这些动态代理作为IOC容器的bean管理-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.jerry.ssm.mapper"></property>
    </bean>
</beans>

在Service层上开启事务注解@Transactional

870577b069fa4cc082f760a1f57e5cf8.png

9、创建MyBatis的mapper接口并配置映射文件

接口


2f13cedd2993438f8bc427ea237f67ac.png


映射文件

d1b6db597e2648cbbe31ffe7d88d42ff.png

10、创建并配置MyBatis的核心配置文件mybatis-config.xml

可以先创建一下pojo实体类

d8a8c8d8d7da482bbd9ed97bc34d3e0b.png

配置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="mapUnderscoreToCamelCase" value="true"/>
    </settings>
    <plugins>
        <!--配置分页插件-->
        <plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
    </plugins>
</configuration>

CRUD

EmployeeController

package com.jerry.ssm.controller;
import com.github.pagehelper.PageInfo;
import com.jerry.ssm.pojo.Employee;
import com.jerry.ssm.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import java.util.List;
/**
 * ClassName: EmployeeController
 * Package: com.jerry.ssm.controller
 * Description:
 * 查询所有的员工信息-->/employee-->get
 * 查询员工的分页信息-->/employee/page/1-->get
 * 根据id查询员工信息-->/employee/1-->get
 * 跳转到添加页面-->/to/add --> get
 * 添加员工信息-->/employee-->post
 * 修改员工信息-->/employee-->put
 * 删除员工信息-->/employee-->delete
 *
 * @Author jerry_jy
 * @Create 2023-02-10 20:19
 * @Version 1.0
 */
@Controller
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;
    @RequestMapping(value = "/employee/{id}",method = RequestMethod.GET)
    public String selectEmployeeInfoById(@PathVariable("id") Integer id, Model model) {
        //根据id查询员工信息
        Employee employee = employeeService.selectEmployeeInfoById(id);
        //将员工信息放在请求域中共享
        model.addAttribute("employee",employee);
        //跳转到employee_list.html
        return "employee_select";
    }
    @RequestMapping(value = "/employee/page/{pageNum}", method = RequestMethod.GET)
    public String getEmployeePage(@PathVariable("pageNum") Integer pageNum, Model model) {
        //获取员工的分页信息
        PageInfo<Employee> page = employeeService.getEmployeePage(pageNum);
        //将分页数据共享在请求域中
        model.addAttribute("page", page);
        //跳转到employee_list.html
        return "employee_page";
    }
    @RequestMapping(value = "/employee", method = RequestMethod.GET)
    public String getAllEmployee(Model model) {
        //查询所有员工信息
        List<Employee> list = employeeService.getAllEmployee();
        //将员工信息放在请求域中共享
        model.addAttribute("list", list);
        //跳转到employee_list.html
        return "employee_list";
    }
}

EmployeeService

package com.jerry.ssm.service;
import com.github.pagehelper.PageInfo;
import com.jerry.ssm.pojo.Employee;
import java.util.List;
/**
 * ClassName: EmployeeService
 * Package: com.jerry.ssm.service
 * Description:
 *
 * @Author jerry_jy
 * @Create 2023-02-11 9:35
 * @Version 1.0
 */
public interface EmployeeService  {
    /**
     * 查询所有员工信息
     * @return
     */
    List<Employee> getAllEmployee();
    /**
     * 获取员工的分页信息
     * @param pageNum
     * @return
     */
    PageInfo<Employee> getEmployeePage(Integer pageNum);
    /**
     * 根据id查询员工信息
     * @return
     */
    Employee selectEmployeeInfoById(Integer id);
}

EmployeeServiceImpl

package com.jerry.ssm.service.impl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jerry.ssm.mapper.EmployeeMapper;
import com.jerry.ssm.pojo.Employee;
import com.jerry.ssm.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
 * ClassName: EmployeeServiceImpl
 * Package: com.jerry.ssm.service.impl
 * Description:
 *
 * @Author jerry_jy
 * @Create 2023-02-11 9:36
 * @Version 1.0
 */
@Service
@Transactional
public class EmployeeServiceImpl implements EmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;
    @Override
    public List<Employee> getAllEmployee() {
        return employeeMapper.getAllEmployee();
    }
    @Override
    public PageInfo<Employee> getEmployeePage(Integer pageNum) {
        //开启分页功能
        PageHelper.startPage(pageNum, 5);
        //查询所有的员工信息
        List<Employee> list = employeeMapper.getAllEmployee();
        //获取分页相关数据
        PageInfo<Employee> pageInfo = new PageInfo<>(list, 5);
        return pageInfo;
    }
    @Override
    public Employee selectEmployeeInfoById(Integer id) {
        return employeeMapper.selectEmployeeInfoById(id);
    }
}

EmployeeMapper

package com.jerry.ssm.mapper;
import com.jerry.ssm.pojo.Employee;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
 * ClassName: EmployeeMapper
 * Package: com.jerry.ssm.mapper
 * Description:
 *
 * @Author jerry_jy
 * @Create 2023-02-11 10:07
 * @Version 1.0
 */
public interface EmployeeMapper {
    /**
     * 查询所有员工信息
     * @return
     */
    List<Employee> getAllEmployee();
    /**
     * 根据id查询员工信息
     * @return
     */
    Employee selectEmployeeInfoById(@Param("id") Integer id);
}

EmployeeMapper.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.jerry.ssm.mapper.EmployeeMapper">
    <select id="getAllEmployee" resultType="com.jerry.ssm.pojo.Employee">
        select * from t_emp
    </select>
    <select id="selectEmployeeInfoById" resultType="com.jerry.ssm.pojo.Employee">
        select * from t_emp where emp_id = #{id}
    </select>
</mapper>

实际效果图

首页

http://localhost:8080/ssm/

fd581b6e7ba8429cb6ff0749e84404c2.png

查询所有的员工信息

http://localhost:8080/ssm/employee

image.png

查询员工的分页信息

http://localhost:8080/ssm/employee/page/1

网络异常,图片无法展示
|

根据id查询员工信息

http://localhost:8080/ssm/employee/2


网络异常,图片无法展示
|

Gitee项目托管

https://gitee.com/jinyang-jy/ssm.git

–end–

相关实践学习
如何在云端创建MySQL数据库
开始实验后,系统会自动创建一台自建MySQL的 源数据库 ECS 实例和一台 目标数据库 RDS。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
相关文章
|
6月前
|
前端开发 Java 应用服务中间件
SSM相关
SSM相关
|
前端开发 Java 数据库连接
SSM整合~
SSM整合~
|
5月前
|
前端开发 JavaScript Java
SSM
【6月更文挑战第6天】
30 1
|
5月前
|
Java 数据库连接 Maven
ssm整合
ssm整合
19 0
|
6月前
|
安全 数据管理 Java
基于ssm的新农大校园论坛系统
基于ssm的新农大校园论坛系统
52 1
|
6月前
|
Java 数据库连接 Spring
SSM整合
SSM整合
|
XML 存储 JSON
SSM 之 SpringMVC(下)
SSM 之 SpringMVC(下)
69 0
SSM 之 SpringMVC(下)
|
JSON 前端开发 JavaScript
SSM 之 SpringMVC(上)
SSM 之 SpringMVC(上)
73 0
|
Java 数据库连接 Spring
SSM整合(超详细)
新建一个excepition包包下创建所需各个异常类记得继承相应的异常父类,原因:程序运行时遇到相应异常后可以不处理向上抛不继承坏处:以后每个方法都要加上这个类//继承RuntimeException类 public class TestExcepition extends RuntimeException {//区别自定义异常类的编码 public TestExcepition(Integer code) {} }
135 1
SSM整合(超详细)
|
前端开发 JavaScript Java
基于SSM的家庭理财系统
该系统为原创的项目,创作于2020年12月,包含详细数据库设计。基于SSM整合,数据层为MyBatis,mysql数据库,具有完整的业务逻辑。适合于毕业设计、课程设计、数据库大作业等。
基于SSM的家庭理财系统