SSM 整合(Spring + MyBatis;Spring + Spring MVC)

1. SSM 整合(Spring + MyBatis;Spring + Spring MVC)

文章目录

  • [1. SSM 整合(Spring + MyBatis;Spring + Spring MVC)](#1. SSM 整合(Spring + MyBatis;Spring + Spring MVC))
  • [2. 引入相关依赖](#2. 引入相关依赖)
  • [3. SSM 整合](#3. SSM 整合)
    • [3.1 创建包结构](#3.1 创建包结构)
  • [4. Spring 整合 + MyBatis](#4. Spring 整合 + MyBatis)
    • [4.1 编写 jdbc.properties](#4.1 编写 jdbc.properties)
    • [4.2 编写 DataSourceConfig 数据源配置](#4.2 编写 DataSourceConfig 数据源配置)
    • [4.3 编写 MyBatisConfig 的配置类(替换 mybatis的xml配置文件)](#4.3 编写 MyBatisConfig 的配置类(替换 mybatis的xml配置文件))
    • [4.4 编写 SpringConfig 的配置类(替换spring的xml配置文件)](#4.4 编写 SpringConfig 的配置类(替换spring的xml配置文件))
  • [5. Spring 整合 Spring MVC](#5. Spring 整合 Spring MVC)
    • [5.1 编写WebAppInitializer(替换 web.xml 文件)](#5.1 编写WebAppInitializer(替换 web.xml 文件))
    • [5.2 编写 SpringMvcConfig 类(替换spring mvc 的xml 配置文件)](#5.2 编写 SpringMvcConfig 类(替换spring mvc 的xml 配置文件))
    • [5.3 添加事务控制](#5.3 添加事务控制)
  • [6. 实现功能测试ssm整合](#6. 实现功能测试ssm整合)
    • [6.1 准备数据表](#6.1 准备数据表)
    • [6.2 pojo类编写](#6.2 pojo类编写)
    • [6.3 dao编写](#6.3 dao编写)
    • [6.4 service编写](#6.4 service编写)
    • [6.5 handler编写](#6.5 handler编写)
    • [6.6 前端发送ajax](#6.6 前端发送ajax)
      • [6.6.1 引入 js 文件](#6.6.1 引入 js 文件)
      • [6.6.2 开启静态资源处理](#6.6.2 开启静态资源处理)
      • [6.6.3 视图控制器](#6.6.3 视图控制器)
      • [6.6.4 编写ajax](#6.6.4 编写ajax)
  • [7. 运行启动 Tomcat 测试](#7. 运行启动 Tomcat 测试)
  • [8. 最后:](#8. 最后:)

2. 引入相关依赖

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>
    <packaging>war</packaging>

    <groupId>com.rainbowsea</groupId>
    <artifactId>ssm-annotation</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
    </properties>

    <dependencies>
        <!--springmvc-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>6.1.4</version>
        </dependency>
        <!--spring jdbc-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>6.1.4</version>
        </dependency>
        <!--mybatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.15</version>
        </dependency>
        <!--mybatis spring-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>3.0.3</version>
        </dependency>
        <!--mysql驱动-->
        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <version>8.3.0</version>
        </dependency>
        <!--德鲁伊连接池-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.22</version>
        </dependency>
        <!--jackson-->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.17.0</version>
        </dependency>
        <!--servlet api-->
        <dependency>
            <groupId>jakarta.servlet</groupId>
            <artifactId>jakarta.servlet-api</artifactId>
            <version>6.0.0</version>
            <scope>provided</scope>
        </dependency>
        <!--logback-->
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.5.3</version>
        </dependency>
        <!--thymeleaf和spring6的整合依赖-->
        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf-spring6</artifactId>
            <version>3.1.2.RELEASE</version>
        </dependency>
    </dependencies>

</project>

3. SSM 整合

3.1 创建包结构


SSM:包括 Spring ,MyBatis,Spring MVC

SSM 的整合:可以大致分为两部分:

  • Spring + MyBatis 的整合
  • Spring + Spring MVC 的整合

4. Spring 整合 + MyBatis

4.1 编写 jdbc.properties

在类根路径下创建属性配置文件,配置连接数据库的信息:jdbc.properties

properties 复制代码
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/springmvc
jdbc.username=root
jdbc.password=MySQL123

4.2 编写 DataSourceConfig 数据源配置

java 复制代码
package com.rainbowsea.ssm.config;


import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;


/**
 * 数据源配置
 */
@Configuration
public class DataSourceConfig {

    @Value("${jdbc.driver}")
    private String driver;


    @Value("${jdbc.url}")
    private String url;


    @Value("${jdbc.username}")
    private String username;


    @Value("${jdbc.password}")
    private String password;

    public DataSourceConfig() {
    }

    public DataSourceConfig(String driver, String url, String username, String password) {
        this.driver = driver;
        this.url = url;
        this.username = username;
        this.password = password;
    }


    @Bean
    public DataSource dataSource() {
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setDriverClassName(driver);
        druidDataSource.setUrl(url);
        druidDataSource.setUsername(username);
        druidDataSource.setPassword(password);
        return druidDataSource;
    }
}

4.3 编写 MyBatisConfig 的配置类(替换 mybatis的xml配置文件)

java 复制代码
package com.rainbowsea.ssm.config;

import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

@Configuration
public class MyBatisConfig {


    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource) {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        sqlSessionFactoryBean.setTypeAliasesPackage("com.rainbowsea.ssm.bean");
        return sqlSessionFactoryBean;
    }


    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer() {
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        mapperScannerConfigurer.setBasePackage("com.rainbowsea.ssm.dao");
        return mapperScannerConfigurer;
    }
}

4.4 编写 SpringConfig 的配置类(替换spring的xml配置文件)

java 复制代码
package com.rainbowsea.ssm.config;


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

// 标注该类式一个配置文件类
@Configuration
// 组件扫描
@ComponentScan("com.rainbowsea.ssm.service")
// 属性配置文件位置
@PropertySource("classpath:jdbc.properties")
// 导入其他配置到Spring 配置
@Import({MyBatisConfig.class,DataSourceConfig.class})
// 开启事务管理器
@EnableTransactionManagement
public class SpringConfig {


    // 在 DataSourceConfig中添加事务管理器对象
    @Bean
    public PlatformTransactionManager platformTransactionManager(DataSource dataSource){
        DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
        dataSourceTransactionManager.setDataSource(dataSource);
        return dataSourceTransactionManager;
    }
}

5. Spring 整合 Spring MVC

5.1 编写WebAppInitializer(替换 web.xml 文件)

java 复制代码
package com.rainbowsea.ssm.config;

import jakarta.servlet.Filter;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.filter.HiddenHttpMethodFilter;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

@Configuration
public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
    /**
     * Spring的配置
     *
     * @return
     */
    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[]{SpringConfig.class};
    }

    /**
     * SpringMVC的配置
     *
     * @return
     */
    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[]{SpringMvcConfig.class};
    }

    /**
     * 用来配置DispatcherServlet的 <url-pattern>
     *
     * @return
     */
    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }

    /**
     * 配置过滤器
     *
     * @return
     */
    @Override
    protected Filter[] getServletFilters() {
        // 配置字符编码过滤器
        CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
        characterEncodingFilter.setEncoding("UTF-8");
        characterEncodingFilter.setForceResponseEncoding(true);
        characterEncodingFilter.setForceRequestEncoding(true);
        // 配置HiddenHttpMethodFilter
        HiddenHttpMethodFilter hiddenHttpMethodFilter = new HiddenHttpMethodFilter();
        return new Filter[]{characterEncodingFilter, hiddenHttpMethodFilter};
    }
}

5.2 编写 SpringMvcConfig 类(替换spring mvc 的xml 配置文件)

java 复制代码
package com.rainbowsea.ssm.config;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.thymeleaf.spring6.SpringTemplateEngine;
import org.thymeleaf.spring6.templateresolver.SpringResourceTemplateResolver;
import org.thymeleaf.spring6.view.ThymeleafViewResolver;
import org.thymeleaf.templatemode.TemplateMode;
import org.thymeleaf.templateresolver.ITemplateResolver;

import java.util.List;

@Configuration  // 标志是配置文件类
@ComponentScan("com.rainbowsea.ssm.handler")
@EnableWebMvc
public class SpringMvcConfig implements WebMvcConfigurer {
    // 以下三个方法合并起来就是开启视图解析器

    @Bean
    public ThymeleafViewResolver getViewResolver(SpringTemplateEngine springTemplateEngine) {
        ThymeleafViewResolver resolver = new ThymeleafViewResolver();
        resolver.setTemplateEngine(springTemplateEngine);
        resolver.setCharacterEncoding("UTF-8");
        resolver.setOrder(1);
        return resolver;
    }

    @Bean
    public SpringTemplateEngine templateEngine(ITemplateResolver iTemplateResolver) {
        SpringTemplateEngine templateEngine = new SpringTemplateEngine();
        templateEngine.setTemplateResolver(iTemplateResolver);
        return templateEngine;
    }

    @Bean
    public ITemplateResolver templateResolver(ApplicationContext applicationContext) {
        SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
        resolver.setApplicationContext(applicationContext);
        resolver.setPrefix("/WEB-INF/thymeleaf/");
        resolver.setSuffix(".html");
        resolver.setTemplateMode(TemplateMode.HTML);
        resolver.setCharacterEncoding("UTF-8");
        resolver.setCacheable(false);//开发时关闭缓存,改动即可生效.发布时,打开
        return resolver;
    }

    // 开启静态资源处理,开启默认的Servlet处理
    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }

    // 视图控制器
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("index");
    }

    // 配置异常处理器
    @Override
    public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) {
    }

    // 配置拦截器
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
    }
}

5.3 添加事务控制

第一步:在SpringConfig中开启事务管理器

java 复制代码
@EnableTransactionManagement
public class SpringConfig {
}

第二步:在DataSourceConfig中添加事务管理器对象

java 复制代码
@Bean
public PlatformTransactionManager platformTransactionManager(DataSource dataSource){
    DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
    dataSourceTransactionManager.setDataSource(dataSource);
    return dataSourceTransactionManager;
}

第三步:在service类上添加如下注解:(如果有的话)

java 复制代码
@Transactional
public class UserService {}

6. 实现功能测试ssm整合

6.1 准备数据表

6.2 pojo类编写

java 复制代码
package com.rainbowsea.ssm.bean;


import org.springframework.stereotype.Controller;

@Controller
public class User {

    private Long id;

    private String name;

    private String password;

    private String email;


    public User() {
    }

    public User(Long id, String name, String password, String email) {
        this.id = id;
        this.name = name;
        this.password = password;
        this.email = email;
    }


    public Long getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}

6.3 dao编写

java 复制代码
package com.rainbowsea.ssm.dao;

import com.rainbowsea.ssm.bean.User;
import org.apache.ibatis.annotations.Select;




public interface UserDao {

    @Select("select * from tbl_user where id = #{id}")
    User selectById(Long id);

}

6.4 service编写

java 复制代码
package com.rainbowsea.ssm.service;

import com.rainbowsea.ssm.bean.User;




public interface UserService {

    /**
     * 根据用户id获取用户信息
     */

    User getById(Long id);
}
java 复制代码
package com.rainbowsea.ssm.service.impl;

import com.rainbowsea.ssm.bean.User;
import com.rainbowsea.ssm.dao.UserDao;
import com.rainbowsea.ssm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;
    @Override
    public User getById(Long id) {
        return userDao.selectById(id);
    }
}

6.5 handler编写

java 复制代码
package com.rainbowsea.ssm.handler;

import com.rainbowsea.ssm.bean.User;
import com.rainbowsea.ssm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/users")
public class UserHandler {

    @Autowired
    private UserService userService;

    @GetMapping("/{id}")
    public User detail(@PathVariable("id") Long id){
        User user = userService.getById(id);
        return user;
    }
}

6.6 前端发送ajax

6.6.1 引入 js 文件

6.6.2 开启静态资源处理

java 复制代码
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
    configurer.enable();
}

6.6.3 视图控制器

java 复制代码
public void addViewControllers(ViewControllerRegistry registry) {
    registry.addViewController("/").setViewName("index");
}

6.6.4 编写ajax

html 复制代码
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title>ssm整合</title>
  <!--引入vue-->
  <script th:src="@{/static/js/vue3.4.21.js}"></script>
  <!--引入axios-->
  <script th:src="@{/static/js/axios.min.js}"></script>
</head>
<body>
<div id="app">
  <button @click="getMessage">查看id=1的用户信息</button>
  <h1>{{message}}</h1>
</div>
<script th:inline="javascript">
  Vue.createApp({
    data(){
      return {
        message : ''
      }
    },
    methods : {
      async getMessage(){
        let response = await axios.get([[@{/}]] + 'users/1')
          this.message = response.data
      }
      }
    }).mount("#app")
</script>
</body>
</html>

7. 运行启动 Tomcat 测试

8. 最后:

"在这个最后的篇章中,我要表达我对每一位读者的感激之情。你们的关注和回复是我创作的动力源泉,我从你们身上吸取了无尽的灵感与勇气。我会将你们的鼓励留在心底,继续在其他的领域奋斗。感谢你们,我们总会在某个时刻再次相遇。"

相关推荐
xlsw_2 小时前
java全栈day20--Web后端实战(Mybatis基础2)
java·开发语言·mybatis
黄油饼卷咖喱鸡就味增汤拌孜然羊肉炒饭4 小时前
SpringBoot如何实现缓存预热?
java·spring boot·spring·缓存·程序员
李小白664 小时前
Spring MVC(上)
java·spring·mvc
Lojarro6 小时前
【Spring】Spring框架之-AOP
java·mysql·spring
zjw_rp7 小时前
Spring-AOP
java·后端·spring·spring-aop
cmdch201710 小时前
Mybatis加密解密查询操作(sql前),where要传入加密后的字段时遇到的问题
数据库·sql·mybatis
王ASC10 小时前
SpringMVC的URL组成,以及URI中对/斜杠的处理,解决IllegalStateException: Ambiguous mapping
java·mvc·springboot·web
撒呼呼10 小时前
# 起步专用 - 哔哩哔哩全模块超还原设计!(内含接口文档、数据库设计)
数据库·spring boot·spring·mvc·springboot
天使day11 小时前
SpringMVC
java·spring·java-ee
秋恬意13 小时前
什么是MyBatis
mybatis