Spring MVC 框架学习(八)---- SSM 框架整合

文章目录

  • Spring MVC 框架学习(八)---- SSM 框架整合
  • 一、准备工作导入依赖
  • 二、Spring 整合 Mybatis
  • 三、Spring 整合 Spring MVC

Spring MVC 框架学习(八)---- SSM 框架整合


一、准备工作导入依赖


导入 spring mybatis mvc 等依赖,同时过滤 xml文件和 properties 文件



<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.0modelVersion>

    <groupId>org.examplegroupId>
    <artifactId>2022-6-29artifactId>
    <version>1.0-SNAPSHOTversion>

<dependencies>

    
    <dependency>
        <groupId>org.projectlombokgroupId>
        <artifactId>lombok-maven-pluginartifactId>
        <version>1.18.12.0version>
        <scope>providedscope>
    dependency>


        
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-webmvcartifactId>
            <version>5.3.18version>
        dependency>


        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>4.12version>
            <scope>testscope>
        dependency>

        
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>8.0.16version>
        dependency>

    
    <dependency>
        <groupId>org.aspectjgroupId>
        <artifactId>aspectjweaverartifactId>
        <version>1.9.9.1version>
    dependency>


    
    <dependency>
        <groupId>org.mybatisgroupId>
        <artifactId>mybatisartifactId>
        <version>3.5.6version>
    dependency>

    
    <dependency>
        <groupId>org.mybatisgroupId>
        <artifactId>mybatis-springartifactId>
        <version>2.0.7version>
    dependency>

    
    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-jdbcartifactId>
        <version>5.3.21version>
    dependency>

    
    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-txartifactId>
        <version>5.3.21version>
    dependency>

       
    <dependency>
        <groupId>javax.servletgroupId>
        <artifactId>servlet-apiartifactId>
        <version>2.5version>
    dependency>


    
    <dependency>
        <groupId>com.fasterxml.jackson.coregroupId>
        <artifactId>jackson-databindartifactId>
        <version>2.9.3version>
    dependency>
   
    <dependency>
        <groupId>com.fasterxml.jackson.coregroupId>
        <artifactId>jackson-coreartifactId>
        <version>2.9.3version>
    dependency>
 
    <dependency>
        <groupId>com.fasterxml.jackson.coregroupId>
        <artifactId>jackson-annotationsartifactId>
        <version>2.9.3version>
    dependency>


dependencies>

    
      
    
    <build>
        <resources>
            <resource>
                <directory>src/main/resourcesdirectory>
                <includes>
                    <include>**/*.xmlinclude>
                    <include>**/*.propertiesinclude>
                includes>
                <filtering>truefiltering>
            resource>

            <resource>
                <directory>src/main/javadirectory>
                <includes>
                    <include>**/*.xmlinclude>
                    <include>**/*.propertiesinclude>
                includes>
                <filtering>truefiltering>
            resource>
        resources>
    build>

project>

总体配置文件架构

Spring MVC 框架学习(八)---- SSM 框架整合_第1张图片


建表语句,测试 mybatis 是否成功连接

create database if not exists ssm;

use ssm;

drop table if exists users;

create table users(
      id int primary key auto_increment,
      username varchar(20),
      password varchar(20)
);


总的applicationContext.xml 文件


<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop" xmlns:cache="http://www.springframework.org/schema/cache"
       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/cache http://www.springframework.org/schema/cache/spring-cache.xsd">


<import resource="classpath:spring-dao.xml"/>





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



    <aop:aspectj-autoproxy/>

beans>

二、Spring 整合 Mybatis


db.properties

jdbc.driverClassName=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/ssm?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT
jdbc.username=root
jdbc.password=123456

mybatis-config.xml,这个文件可以完全省略,但是还是留下方便做一些其他的配置


DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

    
     
    
    <typeAliases>
        <package name="com.bit.pojo"/>
    typeAliases>

configuration>

spring-dao.xml


<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       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">

    

    <context:property-placeholder location="classpath:db.properties" />

    
    <bean class="org.springframework.jdbc.datasource.DriverManagerDataSource" id="dataSource">
        <property name="driverClassName" value="${jdbc.driverClassName}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="password" value="${jdbc.password}"/>
    bean>

    
    <bean class="org.mybatis.spring.SqlSessionFactoryBean" id="sqlSessionFactory">
        <property name="dataSource" ref="dataSource"/>
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <property name="mapperLocations" value="classpath:com/bit/mapper/UserMapper.xml"/>
    bean>


   <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">

       <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
       <property name="basePackage" value="com.bit.mapper"/>


   bean>


beans>

建一个pojo包,创建一个实体类

package com.bit.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private int id;
    private String username;
    private String password;
}


建一个mapper 包,创建一个mapper接口以及 mapper.xml 文件


UserMapper 接口

package com.bit.mapper;

import com.bit.pojo.User;
import org.apache.ibatis.annotations.Param;
import java.util.List;

public interface UserMapper {

    int insert(User user);

    int delete(@Param("id") int id);

    int update(@Param("id") int id,User user);

    List<User>  selectAll();

    User selectById(int id);

}

UserMapper.xml 文件


DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.bit.mapper.UserMapper">
     <insert id="insert" parameterType="user">
         insert into users values(#{id},#{username},#{password})
     insert>

    <delete id="delete">
        delete from users where id=#{id}
    delete>

    <update id="update" parameterType="user">
        update  users set username=#{username},password=#{password} where id=#{id}
    update>

    <select id="selectAll" resultType="user" >
        select * from users;
    select>

    <select id="selectById" resultType="user" >
        select * from users where id=#{id};
    select>

mapper>

在service 层创建接口,对dao层进行封装

创建一个service包,写一个UserService接口 和 UserServiceImpl 实现类


UserService 接口

package com.bit.service;

import com.bit.pojo.User;

import java.util.List;

public interface UserService {

    int  addUser(User user);

    int  delteteUser(int id);

    int  updateUser(int id,User user);

    List<User> selectAllUser();

    User selectOne(int id);

}

UserServiceImpl 实现类

package com.bit.service;

import com.bit.mapper.UserMapper;
import com.bit.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService{

    @Autowired 
    private UserMapper userMapper;

    public int addUser(User user) {
        return userMapper.insert(user);
    }

    public int delteteUser(int id) {
        return userMapper.delete(id);
    }

    public int updateUser(int id, User user) {
        return userMapper.update(id,user);
    }

    public List<User> selectAllUser() {
        return userMapper.selectAll();
    }

    public User selectOne(int id) {
        return userMapper.selectById(id);
    }

    public static void main(String[] args) {

    }
}


测试是否整合mybatis成功的时候一定要看一下,是否spring的配置文件都加载上了

Spring MVC 框架学习(八)---- SSM 框架整合_第2张图片


测试是否成功整合代码

import com.bit.pojo.User;
import com.bit.service.UserService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {

    @Test
    public void test(){
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService userService = context.getBean("userServiceImpl", UserService.class);
        User user = userService.selectOne(5);
        System.out.println(user);
    }
}

测试成功

在这里插入图片描述


三、Spring 整合 Spring MVC


web.xml,配置 DispatcherServlet ,同时加载application.xml 总的spring 配置文件


<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>springmvcservlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
        <init-param>
            <param-name>contextConfigLocationparam-name>
            <param-value>classpath:applicationContext.xmlparam-value>
        init-param>
        <load-on-startup>1load-on-startup>

    servlet>

    <servlet-mapping>
        <servlet-name>springmvcservlet-name>
        <url-pattern>/url-pattern>
    servlet-mapping>

web-app>

spring-mvc.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: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/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">



    





    
    





    
    <context:component-scan base-package="com.bit.controller"/>

   
    <mvc:default-servlet-handler/>

    
    <mvc:annotation-driven/>

beans>

spring-service


<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       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/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd
    http://www.springframework.org/schema/tx
    https://www.springframework.org/schema/tx/spring-tx.xsd">



    
       <context:component-scan base-package="com.bit.service"/>


    <bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager" id="transactionManager">
        <property name="dataSource" ref="dataSource"/>
    bean>


     <aop:aspectj-autoproxy/>


beans>

在总的applicationContext 导入 spring-mvc.xml 、spring-service.xml 文件


    <import resource="classpath:spring-mvc.xml"/>

    <import resource="classpath:spring-service.xml"/>

测试mvc框架是否整合完成的代码


创建controller包,创建UserController类

package com.bit.controller;

import com.bit.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/select")
    @ResponseBody
    public Object select(){
        return userService.selectAllUser();
    }
    
}


运行项目,访问接口出现JSON格式的数据,整合mvc 成功


在这里插入图片描述


最后所有的整合三个框架的工作完成。


如果有静态资源文件(css、html、js),那么放在web目录下 的 创建的static 文件夹下面。

你可能感兴趣的:(SpringMVC,框架学习,spring,mvc,学习)