SSM整合简单演示(详细解析)

SSM整合

思想解析

所谓SSM(Spring+SpringMVC+MyBatis)就是由Spring、SpringMVC、MyBatis三个开源框架整合而成的框架集,常作为数据源较简单的web项目的框架。

Spring是一个轻量级的控制反转(IoC)和面向切面(AOP)的容器框架。

SpringMVC分离了控制器、模型对象、分派器以及处理程序对象的角色,这种分离让它们更容易进行定制。

MyBatis是一个支持普通SQL查询,存储过程和高级映射的优秀持久层框架。

其实其中的容器管理都由Spring技术支持。SpringMVC属于Spring的其中一个框架。而Mybatis的技术支持交由Spring容器来管理。SpringMVC技术需要另外开辟一个容器来管理和交互。所有SSM框架整合需要两个容器支持。

依赖

ssm整合的依赖其实都是之前用过的依赖,多了一个Spring与Mybatis整合的附加依赖。

 <dependencies>
        <!--        mysql数据库驱动依赖-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.9</version>
        </dependency>
        <!--        阿里数据库连接池依赖-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.12</version>
        </dependency>
        <!--        web项目依赖-->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.2.1-b03</version>
        </dependency>
        <!--        springMVC框架依赖(其中已包括部分spring依赖,jdbc与tx除外)-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.2.5.RELEASE</version>
        </dependency>

        <!--spring中jdbc的依赖-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.2.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>5.2.5.RELEASE</version>
        </dependency>

        <!--        mybatis框架依赖-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.1</version>
        </dependency>
        <!--    唯一一个新加依赖   spring与mybatis整合依赖-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.1</version>
        </dependency>
    </dependencies>

    <!--    插件-->
    <build>
        <!--        加载java文件夹中的配置文件(properties后缀与xml后缀)-->
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>
    </build>

本演示项目结构

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-MujdZvdD-1630059967025)(C:\Users\ling\Pictures\捕获.PNG)]

web文件

在web文件中需要向Tomcat声明有spring对象管理和springmvc访问容器的存在,并通过对应的配置文件加载对应的资源。

首先向web文件中加载Spring容器监听器与SpringMVC的中央调度器。

<!--    声明spring监听器-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <!--        指定Spring容器的配置文件-->
        <param-value>classpath:conf/spring-conf.xml</param-value>
    </context-param>
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
    
<!--    声明SpringMVC中央调度器-->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--        配置调度器的设置-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:conf/sprongMVC-conf.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
<!--    所有访问都得经过调度器-->
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

Spring配置文件

spring配置文件里配置了spring容器的资源,需要管理的对象都得在这里配置好。Mybatis的数据源也交给spring容器配置和管理。还有Mybatis的重要类对象SqlSessionFactoryBuilder(sql会话工厂创建类),SqlSessionFactory(sql会话工厂类),SqlSession(会话连接),dao的mapper(sql操作映射)都在spring中配置和管理。

​ 原来在Mybatis中SqlSessionFactory(SqlSession工厂)由SqlSessionFactoryBuilder来获取,有一个类SqlSessionFactoryBean,功能与SqlSession工厂一致。而这个类可以直接创建并处交由spring管理。


<!--    spring的配置文件:声明 service ,dao ,工具类 ,事物配置 -->
<!--    扫描service类-->
    <context:component-scan base-package="ling.Service"/>

<!--   加载jdbc配置信息文件-->
<context:property-placeholder location="classpath:conf/jdbc.properties"/>

<!--    加载阿里数据源,用于配置与数据库的连接信息-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
    init-method="init" destroy-method="close">
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>

<!--    sql会话工厂,Mybatis中的重要对象,用于创建Sqlsession-->
    <bean id="factory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--        数据库连接配置 -->
        <property name="dataSource" ref="dataSource"/>
<!--        加载Mybatis的配置文件用(要用里面内容时才用)-->
         <property name="configLocation" value="classpath:conf/mybatis-conf.xml"/>
    </bean>

<!--   作用是将Dao包下的所有映射加载进框架容器(MapperScannerConfigurer是一个bean注册管理器),对应的接口和接口映射要同名 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--        <property name="sqlSessionFactoryBeanName" value="factory"/>-->
        <property name="basePackage" value="ling.Dao"/>
    </bean>

SpringMVC配置文件

SpringMVC并没什么变化,因为它自己开的一个容器自行管理,只是会在执行方法中用到spring容器的资源。SpringMVC只需管理控制类方法和视图解析器用于返回。

<!--    扫描Controller包下的控制器-->
    <context:component-scan base-package="ling.Controller"/>
<!--    试图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!--    视图解释器的前后缀-->
    <property name="prefix" value="/WEB-INF/jsp/"/>
    <property name="suffix" value=".jsp"/>
</bean>

Mybatis配置文件

如果要用到Mybatis配置文件的配置就得创建Mybatis的配置文件并在Spring中配置标明Mybatis的位置。(这里我使用了别名)

<!-- 设置Utility包下所有类的别名为类自身-->
    <typeAliases>
        <package name="ling.Utility"/>
    </typeAliases>

Dao,Sevice,Controller,Utility

整合的主要操作在于配置文件的整合配置,类操作中都大差不差,以下是各类的内容。

Utility

用户实现对象

public class Student {
    private String name;
    private String sex;
    private Integer age;

    public Student(String name, String sex, Integer age) {
        this.name = name;
        this.sex = sex;
        this.age = age;
    }

    public Student() {
    }

    @Override
    public String toString() {
        return "name='" + name + '\'' +
                ", sex='" + sex + '\'' +
                ", age=" + age +
                '\n';
    }
}

Dao

接口
/*
* @Repository
* 标明这是一个dao层的类,并交给Spring容器管理
* */
@Repository
public interface StudentMapper {
    //添加一个学生
    int insertStudent(Student user);
    //查看所有学生
    List<Student> selectStudets();

}
Mapper文件

映射文件必须得与被映射接口透明,因为扫描的是包下的所有,只有互相对应才会被找到。

<mapper namespace="ling.Dao.StudentMapper">
    <!-- 查询所有用户信息,返回类型resultType-->
    <select id="selectStudents" resultType="student">
        select * from student
    </select>

    <insert id="insertStudent" >
        insert into student values(#{name},#{sex},#{age})
    </insert>

</mapper>

Service

对数据进行处理

StudentService接口
@Service
public interface StudentService {
//   添加一个学生
     boolean addStuden(Student user);
//    查看所有学生
    List<Student> queryStudent();

}
StudentServiceImpl
@Service
public class StudentServiceImpl implements StudentService {

    //自动注入dao接口的实行类,Mybatis已经根据映文件把实现类创建好并交给spring管理
    @Autowired
    private StudentMapper dao;
    private String errorString = "错误代码";

    @Override
    public boolean addStuden(Student user) {

        try {
            int i = dao.insertStudent(user);
            return true;
        }catch (Exception e){
            System.out.println(e.toString());
            System.out.println(errorString+"1:添加学生失败!");
        }
        return false;
    }

    @Override
    public List<Student> queryStudent() {
        try {
            return dao.selectStudets();
        }catch (Exception e){
            System.out.println(e.toString());
            System.out.println(errorString+"2:查询所有学生失败!");
        }
        return null;
    }
}

Controller

控制层,这层是交由SpringMVC扫描管理的

@Controller
@RequestMapping("/Student")
public class StudentController {
    //自动注入业务层
    @Autowired
    private StudentService student;

    @RequestMapping(value = "/add",produces = "application/json;charset=utf-8")
    @ResponseBody
    public String addStudent(String name,String sex,Integer age){
        Student studentuser = new Student(name,sex,age);
        System.out.println(studentuser.toString());
        boolean b = this.student.addStuden(studentuser);
        if (b){
            return "添加成功!";
        }else {
        return "添加失败!";
        }
    }

    @RequestMapping(value = "/query",produces = "application/json;charset=utf-8")
    @ResponseBody
    public String queryStudent(){
        List<Student> students = student.queryStudent();

        if (students!=null){
            return students.toString();
        }else {
            return "添加失败!";
        }
    }

ssm整合到这里就可以实现添加和查询所有学生的功能了!有什么问题与错误可以评论向我提出。谢谢。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值