Vue+springmvc+mybatis前后端分离学习---(二)Spring与Mybatis整合思路总结

上节单独测通了Mybatis与Spring框架,发现可以将诸如sqlSessionFactory等不是我们自己写的对象交给spring去管理以便我们使用时可以进行注入,顺着这个思路现在我们来进行整合

第一章传送门—>Spring与Mybatis单独搭建运行总结
第三章传送门—>前端搭建与跨域解决

一、Spring整合Mybatis
思路:既然在Spring中我们有个类Student拥有name与age属性时可以在spring配置文件中通过bean标签中的property标签将这两个属性赋值,那么同样我们可以将sqlSessionFactory对象所需的driver,url,username等属性也这样给他赋值,以此来解放单独使用Mybatis时的sqlMapConfig.xml文件。
1.解放sqlMapConfig,将工厂对象以及所需属性进行注入。
<?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: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
			    http://www.springframework.org/schema/context/spring-context.xsd
			    http://www.springframework.org/schema/aop
			    http://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
			    http://www.springframework.org/schema/mvc/spring-mvc.xsd">


    <!--Spring托管MyBatis -->
    <!--配置连接池 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver"/>
        <property name="jdbcUrl" value="jdbc:mysql:///tmsystem"/>
        <property name="user" value="root"/>
        <property name="password" value="123456"/>

    </bean>

    <!--配置工厂对象 -->
    <bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>

    </bean>


    <!--配置接口所在包 -->
    <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.lx.dao"/>
    </bean>


</beans>
2.接下来,我们只需要通过userDao这个名字来获取对象就可以得到Mybatis帮我们自动强化过的代理对象了,尽管我们并没有在spring的配置文件中注入一个id叫userDao的Bean。
import com.lx.dao.UserDao;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.io.IOException;

/**
 * Mybatis测试类
 */
public class Demo01 {

    @Test
    public void test() throws IOException {

        //获取applicationContext文件并加载
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");

        //获取UserDao对象
        UserDao userDao = (UserDao)applicationContext.getBean("userDao");

        //执行方法
        System.out.println(userDao.userCount());
    }
}


可以看到从SqlSessionFactory到session到getMapper全部都不用我们写了,只需要获得想获得的对象就好,当然SSM整合完之后我们的service是连上面仅剩的代码都不需要的(只靠一个@Autowired注解就可以轻松获得UserDao对象),但现在还是先手动获取以便观察变化。

3.删除sqlMapConfig文件,运行发现成功,可以看到resourses文件夹只剩下spring的配置文件,到这里Spring就成功的接管了Mabytis。

在这里插入图片描述

现在开始就进入springmvc的节奏,拦截servlet本该处理的请求,扫描各种组件,注入各种对象,王霸之气华丽溢出。

二、三位一体
1.springmvc框架正式接管并处理请求。
刚刚我们不停需要在test方法里获取applicationContext对象,再读取配置文件信息,手动获取各个bean,但我们知道web应用里不管是servlet还是controller啥时候能让写代码的人new出来自己调这调那来无理控制,所以spring这时候就该让位于springmvc了。
<!DOCTYPE web-app PUBLIC
        "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
        "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>

  <!--spring监听器 -->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>

  <!--springmvc接管原始servlet处理 -->
  <servlet>
    <servlet-name>DispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <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>

  <!--编码拦截器配置 -->
  <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>
  </filter>
  <filter-mapping>
    <filter-name>CharacterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

</web-app>

2.resources中配置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:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       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-4.0.xsd
		http://www.springframework.org/schema/mvc
		http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
		http://www.springframework.org/schema/context
		http://www.springframework.org/schema/context/spring-context-4.0.xsd
		http://www.springframework.org/schema/aop
		http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
		http://www.springframework.org/schema/tx
		http://www.springframework.org/schema/tx/spring-tx-4.0.xsd ">

    <!--只扫描controller-->
    <context:component-scan base-package="com.lx">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <!--配置视图解析器 -->
    <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

    <!--过滤静态资源 -->
    <mvc:resources mapping="/css/**" location="/css/"/>
    <mvc:resources mapping="/js/**" location="/js/"/>
    <mvc:resources mapping="/images/**" location="/images/"/>

    <!--开启注解支持 -->
    <mvc:annotation-driven />
</beans>

3.这里请先创建controller/service等包,还有WEB-INF文件夹下的pages文件夹,项目结构如图。

在这里插入图片描述

4.现在,我们来创建一个Controller,让其收到请求之后跳转的success页面。
controller、index.jsp、success.jsp的代码如下。
controller:
package com.lx.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class HelloController {

    @RequestMapping("/sayHello")
    public String sayHello(){

        return "success";
    }
}

index.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<body>
<h2>Hello World!</h2>

<a href="sayHello">点击跳转</a>
</body>
</html>


success.jsp
<%--
  Created by IntelliJ IDEA.
  User: hp
  Date: 2020/7/18
  Time: 10:46
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h1>测试一下</h1>
</body>
</html>

5.配置tomcat服务器

5.1 点击配置
在这里插入图片描述

5.2 选择自己的tomcat与浏览器等

在这里插入图片描述

6.运行并点击超链接,请求处理成功

在这里插入图片描述

在这里插入图片描述

7.到这springmvc就开始运作了,那么现在我们再看看三位一体之后的UserDao如何被使用。此处需要创建UserDao、userService以及UserServiceImpl。
UserDao:
package com.lx.dao;

/**
 * 用户
 */
public interface UserDao {

    /*
    查询user表总数
     */
    public int userCount();
}

UserService
package com.lx.service;

import org.springframework.stereotype.Service;

/**
 * 用户service
 */
public interface UserService {

    /*
    获取用户数
     */
    public int getUserCount();
}

UserServiceImpl
这里我们看到之前我们仅剩三行代码获得的userDao对象,仅仅通过一个注解就得到了,这就是三位一体的好处,先通过spring我们可以直接通过applicationContext获得dao,现在直接一个注解就获得到了。
package com.lx.service.serviceImpl;

import com.lx.dao.UserDao;
import com.lx.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 用户service实现
 */
@Service
public class UserServiceImpl implements UserService {

    //注入UserDao对象
    @Autowired
    private UserDao userDao;

    @Override
    public int getUserCount() {

        System.out.println("获取数量");
        return userDao.userCount();
    }
}

8.将该service注入到controller中,并修改为以下代码。
package com.lx.controller;

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

@Controller
public class HelloController {

    /*
    用户service注入
     */
    @Autowired
    private UserService userService;

    @RequestMapping("/sayHello")
    public String sayHello(){

        System.out.println("来到controller了");

        System.out.println("用户个数为"+userService.getUserCount());

        return "success";
    }
}

9.测试成功,控制台成功打印。

在这里插入图片描述

总结:到这我们的SSM就整合完成了,代码和配置的东西已经极简了,前两章就是想要快速搭建一个学习用的环境,以后不管在哪搭就可以迅速对照,第一章先独立搭建S与M发现可柔化点,第二章再将可柔化的点进行整合,以此为记。

“没什么难的,不要忘记呼吸”
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值