Spring+SpringWeb+MyBatis三大框架整合教程 实现先前后端交互搭建

news2024/9/21 4:21:13

目录

1. 创建项目

2. 导入所依赖的 jar 包

3. 配置MyBatis

4. 配置spring事务管理

5. 配置Spring 

 * Spring配置代码解读

6. dao层 

7. mappers映射文件

8. common层

9. service层 

10. web层

11. 测试


ssm大合体!

1. 创建项目

📍创建一个JavaEE项目

不会创建JavaEE项目的小可爱可以回家种地了~~

📍创建所要用到的包和配置文件:

2. 导入所依赖的 jar 包

📍在pom.xml配置文件中引入依赖:

        <!-- spring-context -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.2.RELEASE</version>
        </dependency>

        <!-- spring-jdbc-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.2.2.RELEASE</version>
        </dependency>

        <!--  mysql组件-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.16</version>
        </dependency>

        <!--阿里数据源 数据库连接管理组件-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.10</version>
        </dependency>

        <!-- mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.2</version>
        </dependency>

        <!-- spring集成mybatis jar-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.1</version>
        </dependency>

        <!--aspectj-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>5.2.2.RELEASE</version>
        </dependency>

        <!-- Spring Web-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.2.2.RELEASE</version>
        </dependency>

3. 配置MyBatis

📍在mybatis.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="STDOUT_LOGGING"/>
        <!-- 开启数据库列名与java属性名转换,例如user_name  userName  -->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
        <!-- 全局二级缓存开关 -->
        <setting name="cacheEnabled" value="true"/>
    </settings>

    <typeAliases>
        <!--为类配置别名-->
        <package name="com.ffyc.ssmpro.model"/>
    </typeAliases>

</configuration>

4. 配置spring事务管理

📍在webapp目录下的WEB-INF文件夹中的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">

    <servlet>
        <servlet-name>application</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring.xml</param-value>
        </init-param>
        <load-on-startup>0</load-on-startup>
    </servlet>
    <!--请求映射-->
    <servlet-mapping>
        <servlet-name>application</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

5. 配置Spring 

📍在spring.xml文件配置

<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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
       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
                           https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <context:component-scan base-package="com.ffyc.ssmpro"></context:component-scan>

    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://127.0.0.1:3306/ssmdb?serverTimezone=Asia/Shanghai"></property>
        <property name="username" value="root"></property>
        <property name="password" value="root"></property>
        <property name="initialSize" value="10"></property><!--初始化连接数量-->
        <property name="maxActive" value="20"></property><!--最大连接数量-->
    </bean>

    <!-- Spring管理生成sqlSessionFactory对象 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <property name="configLocation" value="classpath:mybatis.xml"></property>
        <property name="mapperLocations" value="classpath:mappers/*Mapper.xml">
        </property>
    </bean>

    <!-- 生成dao包下所有接口的代理对象 -->
    <bean id="mapperFactory" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.ffyc.ssmpro.dao"></property>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
    </bean>

    <!--开启自动代理-->
    <aop:aspectj-autoproxy />

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

    <!-- 开启注解事务管理 -->
    <tx:annotation-driven transaction-manager="transactionManager"/>

    <!-- 开启web层注解 -->
    <mvc:annotation-driven></mvc:annotation-driven>
</beans>

 * Spring配置代码解读

1. 如图所示:

<context:component-scan base-package="com.ffyc.ssmpro">:指示 Spring 在com.ffyc.ssmpro包及其子包中扫描带有特定注解(如@Component@Service@Repository等)的类,并将它们自动注册为 Spring 容器中的 bean。

2. 如图所示::

<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">:定义了一个名为dataSource的数据源 bean,使用阿里巴巴的 Druid 数据库连接池。配置了数据库驱动类、连接 URL、用户名、密码以及连接池的初始化连接数量和最大连接数量等属性。

3. 如图所示:

 <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">:配置 MyBatis 的SqlSessionFactory,它用于创建与数据库交互的SqlSession

dataSource属性引用了上面定义的数据源 bean,确保 MyBatis 使用正确的数据库连接。configLocation属性指定了 MyBatis 的配置文件mybatis.xml的位置。

mapperLocations属性指定了 MyBatis 的 Mapper XML 文件的位置,这里是classpath:mappers/*Mapper.xml,表示在类路径下的mappers包中查找所有以Mapper.xml结尾的文件。

4.如图所示

 <bean id="mapperFactory" class="org.mybatis.spring.mapper.MapperScannerConfigurer">:使用 MyBatis-Spring 提供的MapperScannerConfigurer来自动扫描com.ffyc.ssmpro.dao包下的所有接口,并为它们生成代理对象。这些代理对象可以直接注入到其他 bean 中,方便进行数据库操作。

basePackage属性指定了要扫描的包路径。

sqlSessionFactoryBeanName属性指定了用于创建代理对象的SqlSessionFactory的 bean 名称。

 5. 如图所示

<aop:aspectj-autoproxy />:开启 AspectJ 风格的自动代理,使得可以在 Spring 中使用 AOP 进行横切关注点的分离,例如事务管理、日志记录等。

6. 如图所示:

 <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">:配置 Spring 的事务管理器,这里使用DataSourceTransactionManager,它依赖于数据源来管理事务。dataSource属性引用了前面定义的数据源 bean。

<tx:annotation-driven transaction-manager="transactionManager"/>:开启注解驱动的事务管理,使得可以使用@Transactional注解在方法上标记需要事务管理的操作。

7. 如图所示:

<mvc:annotation-driven></mvc:annotation-driven>:开启 Spring MVC 的注解驱动,使得可以在控制器类和方法上使用@Controller@RequestMapping等注解来处理 Web 请求。

6. dao层 

📍创建一个LoginDao接口

import com.ffyc.ssmpro.model.Admin;

public interface LoginDao {
    Admin login(Admin admin);
}

7. mappers映射文件

📍创建LoginMapper.xml映射文件,负责执行sql语句

<?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.ffyc.ssmpro.dao.LoginDao">


    <select id="login" parameterType="Admin" resultType="Admin">
          select * from admin where account=#{account} and password = #{password}
    </select>
</mapper>

8. common层

import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

@Component
@Aspect
public class CommonUtil {
    @AfterThrowing(value = "execution(* com.ffyc.ssmpro.web.*.*(..))",throwing="throwable")
    public void exception(Throwable throwable){
        System.out.println("系统忙"+throwable.getMessage());
    }

}

9. service层 

import com.ffyc.ssmpro.dao.LoginDao;
import com.ffyc.ssmpro.model.Admin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional(rollbackFor = Exception.class)
public class LoginService {

    @Autowired
    LoginDao loginDao;

    public Admin login(Admin admin){
        Admin admin1 = loginDao.login(admin);
        return admin1;
    }

}

10. web层

import com.ffyc.ssmpro.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping(path = "/loginCtl") //为类和方法定义地址
public class LoginController {

    @Autowired
    LoginService loginService;

    @RequestMapping(path = "/login")
    public String login(){
        System.out.println("登录");
        return "success";
    }


}

11. 测试

📍在浏览器通过后端地址访问:

📍成功访问!




 海漫浩浩,我亦苦作舟!大家一起学习,一起进步! 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2086669.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【C++ Primer Plus习题】6.7

问题: 解答: #include <iostream> #include <cctype> using namespace std;int main() {string words;int vowel 0;int consonant 0;int other0;cout << "请输入一个单词(q结束):";cin >> words;while (words!"q"){if (!isalph…

编成笔记-atan2函数学习分析

分析atan2函数 1. 前言 2. atan2函数分析 tanθy/x : 当(x,y) 在第一象限&#xff0c;0 < θ < π/2当(x,y) 在第二象限&#xff0c;π/2 < θ ≤ π当(x,y) 在第三象限&#xff0c;− π < θ < − π/2当(x,y) 在第四象限&#xff0c;− π/2 < θ <…

动态读取nacos中修改的项目配置文件

本项目用的还是springboot项目&#xff0c;咱们直接上代码 一&#xff1a;首先看下nacos中需要动态获取的属性 二&#xff1a;把需要动态读取的配置类中的属性整理一个实体类 mport lombok.Data; import org.springframework.boot.context.properties.ConfigurationPropert…

微信公众号等工具 3 — 使用 Markdown Nice 写文章

文章目录 操作步骤STEP 1. 进入微信公众号文章编辑界面STEP 2. Markdown Nice 将 3 个重要的功能嵌入到了微信公众号编辑器中STEP 3. 在 Markdown Nice 界面编辑内容STEP 4. 导入/粘贴/直接在编辑器中编辑 Markdown → 点击左下角的预览效果 操作步骤 STEP 1. 进入微信公众号文…

BUUCTF二维码1

九张撕碎二维码碎片。不会让人拼起来吧&#xff01;看了大神们得博客竟然是真的&#xff0c;这是ctf的题吗&#xff01;是考验人的耐性吧&#xff01; 我勉为其难讲一下PS怎么拼图&#xff0c;首先要把九张碎片抠图&#xff0c;背景变透明&#xff0c;ps可以但是太麻烦&#xf…

(亲测有效)spring cloud+Vue微服务项目云服务器部署(宝塔)

我的另一篇博客&#xff0c;有兴趣可以看看&#xff0c;部署思路都是一样的。 &#xff08;亲测有效&#xff09;SpringBootVue项目云服务器部署&#xff08;宝塔&#xff09;_springboot 宝塔部署-CSDN博客 目录 一、准备工作 购买云服务器 登录云服务器 安装宝塔 二、jdk…

项目技巧二

java中Date和mysql数据库datetime数据类型 数据库中的 datetime 类型&#xff1a; 大多数关系型数据库&#xff08;如 MySQL, SQL Server, PostgreSQL 等&#xff09;都提供了 datetime 类型&#xff0c;用于存储日期和时间信息。这些数据库中的 datetime 类型通常遵循 ISO 86…

金九银十跳槽季,最新自动化测试面试题合集

前言 Hello,大家好。金九银十也不远了&#xff0c;有的人盼望升职加薪&#xff0c;有的人立了新的Flag&#xff0c;有跳槽计划的该提上日程了。为解大伙的燃眉之急&#xff0c;今天分享自动化面试题预热一波&#xff0c;欢迎留言区补充评论&#xff01; 一、请描述一下自动化测…

sqli-labs靶场通关攻略(四十一到五十关)

sqli-labs-master靶场第四十一关 一&#xff0c;查看数据库 ?id-1 union select 1,2,database()-- 二&#xff0c;查看表名 ?id-1 union select 1,group_concat(table_name),3 from information_schema.tables where table_schemadatabase()-- 三&#xff0c;查看users表中…

python学习之路 - python对mysql的数据操作

目录 一、python对mysql的数据操作1、前期准备2、连接mysql3、创建表5、插入表4、查询表 一、python对mysql的数据操作 1、前期准备 使用python对mysql进行相关操作前&#xff0c;需要安装pymysql。执行pip install pymysql命令即可如果具体不知道如何操作&#xff0c;可以查…

导入pyBigWig包

今天复现论文时&#xff0c;看到了一种叫做bigwig格式的数据&#xff0c;创建和访问该格式文件需要用到pybigwig包&#xff0c;在此过程中遇到了一些问题&#xff0c;记录一下。 介绍 pybigwig的使用依赖于两个C库&#xff0c;所谓C库就是C语言编写的python库。 正如在pypi官…

聚类算法-DBSCAN

文章目录 一、DBSCAN介绍1.含义2.DBSCAN 的核心概念3.DBSCAN算法参数 二、代码实现1.数据预处理2.DBSCAN聚类3.计算轮廓系数4.全部代码 三、总结 一、DBSCAN介绍 1.含义 DBSCAN&#xff08;Density-Based Spatial Clustering of Applications with Noise&#xff09;是一种基…

llama-cpp-python编译失败,解决方案安装wheel文件

https://abetlen.github.io/llama-cpp-python/whl/cu121/llama-cpp-python/编译失败&#xff1a; 解决方案&#xff1a;使用轮子镜像

Clion/Vs中wcout输出中文不显示的解决办法

本来要写个输出所有窗口的代码&#xff0c;但是结果文字一直不输出&#xff0c;又试了试发现只是汉字不输出&#xff1a; #include <windows.h> #include <iostream> #include <vector> #include <string>std::vector<std::wstring> windowTitl…

数据结构(6.4_4)——Floyd算法

Floyd算法 第一步&#xff1a;建立两个二维数组&#xff0c;一个用来存放所有顶点&#xff0c;一个用来存放顶点之间的中转点 第二步&#xff1a;循环遍历A矩阵&#xff0c;若,则&#xff0c;&#xff1b;否则 和保持原值&#xff0c;循环完所有i&#xff0c;j后更新数组并且…

材料表面缺陷检测系统源码分享 # [一条龙教学YOLOV8标注好的数据集一键训练_70+全套改进创新点发刊_Web前端展示]

材料表面缺陷检测系统源码分享 [一条龙教学YOLOV8标注好的数据集一键训练_70全套改进创新点发刊_Web前端展示] 1.研究背景与意义 项目参考AAAI Association for the Advancement of Artificial Intelligence 项目来源AACV Association for the Advancement of Computer Vis…

【rk3588】环境搭建及系统编译

开发板&#xff1a;ROC-RK3588S-PC 官方链接&#xff1a;Welcome to ROC-RK3588S-PC Manual — Firefly Wiki (t-firefly.com) 串口调试配置 一、产品介绍 — Firefly Wiki (t-firefly.com)&#xff0c;可以按照官方链接的说明在个人PC上使用串口。这个串口会输出rk3588的日…

字典查找对应输入的字符

一、将文件放入到数据库 #include<stdio.h> #include<sqlite3.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <string.h> #include <unistd.h> int main(int agrc,char *agrv[]) {FILE *fp;fp fope…

详细介绍校园网络拓扑结构设计图

目录 需求分析 网络架构设计 拓扑图设计 安全策略 出口设计 总结 校园网络拓扑结构设计是一种对学校内计算机、网络设备和软件进行集成应用的系统化设计&#xff0c;旨在为师生提供一个高效、稳定、安全的网络平台&#xff0c;以支持教学、科研和管理的信息化需求。一个优…

RKNPU2从入门到实践 ---- 【8】借助 RKNN Toolkit lite2 在RK3588开发板上部署RKNN模型

前言 作者使用的平台为Ubuntu20.04虚拟系统&#xff0c;开发板为瑞芯微RK3588&#xff0c;开发板上的系统为Ubuntu22.04系统。 一、任务 完成RKNN模型的部署&#xff0c;RKNN模型的部署是将RKNN模型放到开发板上&#xff0c;应用程序可以加载RKNN模型&#xff0c;从而在嵌入式…