在pom.xml添加相关依赖 — mybatis

  1. <dependencies>
  2. <dependency>
  3. <groupId>javax.servlet.jsp</groupId>
  4. <artifactId>javax.servlet.jsp-api</artifactId>
  5. <version>2.3.3</version>
  6. <scope>provided</scope>
  7. </dependency>
  8. <dependency>
  9. <groupId>javax.servlet</groupId>
  10. <artifactId>javax.servlet-api</artifactId>
  11. <version>4.0.1</version>
  12. <scope>provided</scope>
  13. </dependency>
  14. <!--json jar包-->
  15. <dependency>
  16. <groupId>com.fasterxml.jackson.core</groupId>
  17. <artifactId>jackson-annotations</artifactId>
  18. <version>2.8.6</version>
  19. </dependency>
  20. <dependency>
  21. <groupId>com.fasterxml.jackson.core</groupId>
  22. <artifactId>jackson-core</artifactId>
  23. <version>2.8.1</version>
  24. </dependency>
  25. <dependency>
  26. <groupId>com.fasterxml.jackson.core</groupId>
  27. <artifactId>jackson-databind</artifactId>
  28. <version>2.7.5</version>
  29. </dependency>
  30. <!-- Spring依赖 -->
  31. <!--1. Spring核心依赖,上面已经有日志了 -->
  32. <dependency>
  33. <groupId>org.springframework</groupId>
  34. <artifactId>spring-core</artifactId>
  35. <version>4.3.7.RELEASE</version>
  36. </dependency>
  37. <dependency>
  38. <groupId>org.springframework</groupId>
  39. <artifactId>spring-beans</artifactId>
  40. <version>4.3.7.RELEASE</version>
  41. </dependency>
  42. <dependency>
  43. <groupId>org.springframework</groupId>
  44. <artifactId>spring-context</artifactId>
  45. <version>4.3.7.RELEASE</version>
  46. </dependency>
  47. <dependency>
  48. <groupId>org.springframework</groupId>
  49. <artifactId>spring-expression</artifactId>
  50. <version>4.3.7.RELEASE</version>
  51. </dependency>
  52. <!--spring的aop jar包-->
  53. <dependency>
  54. <groupId>org.springframework</groupId>
  55. <artifactId>spring-aop</artifactId>
  56. <version>4.3.7.RELEASE</version>
  57. </dependency>
  58. <dependency>
  59. <groupId>org.springframework</groupId>
  60. <artifactId>spring-aspects</artifactId>
  61. <version>4.3.7.RELEASE</version>
  62. </dependency>
  63. <!--这两个jar包是阿帕奇的-->
  64. <dependency>
  65. <groupId>org.aspectj</groupId>
  66. <artifactId>aspectjrt</artifactId>
  67. <version>1.8.13</version>
  68. </dependency>
  69. <dependency>
  70. <groupId>org.aspectj</groupId>
  71. <artifactId>aspectjweaver</artifactId>
  72. <version>1.8.13</version>
  73. </dependency>
  74. <dependency>
  75. <groupId>aopalliance</groupId>
  76. <artifactId>aopalliance</artifactId>
  77. <version>1.0</version>
  78. </dependency>
  79. <!--2. SpringDAO层依赖 -->
  80. <dependency>
  81. <groupId>org.springframework</groupId>
  82. <artifactId>spring-jdbc</artifactId>
  83. <version>4.3.7.RELEASE</version>
  84. </dependency>
  85. <dependency>
  86. <groupId>org.springframework</groupId>
  87. <artifactId>spring-tx</artifactId>
  88. <version>4.3.7.RELEASE</version>
  89. </dependency>
  90. <!--3. Spring WEB依赖 -->
  91. <dependency>
  92. <groupId>org.springframework</groupId>
  93. <artifactId>spring-web</artifactId>
  94. <version>4.3.7.RELEASE</version>
  95. </dependency>
  96. <dependency>
  97. <groupId>org.springframework</groupId>
  98. <artifactId>spring-webmvc</artifactId>
  99. <version>4.3.7.RELEASE</version>
  100. </dependency>
  101. <!--4.Spring-test相关依赖 -->
  102. <dependency>
  103. <groupId>org.springframework</groupId>
  104. <artifactId>spring-test</artifactId>
  105. <version>4.3.7.RELEASE</version>
  106. </dependency>
  107. </dependencies>

基本思路
建立spring框架

1.创建bean

  1. public class user implements Serializable {
  2. private Integer id;
  3. private String name;
  4. private String gender;
  5. private String email;
  6. @Override
  7. public String toString() {
  8. return "user{" +
  9. "id=" + id +
  10. ", name='" + name + '\'' +
  11. ", gender='" + gender + '\'' +
  12. ", email='" + email + '\'' +
  13. '}';
  14. }
  15. public Integer getId() {
  16. return id;
  17. }
  18. public void setId(Integer id) {
  19. this.id = id;
  20. }
  21. public String getName() {
  22. return name;
  23. }
  24. public void setName(String name) {
  25. this.name = name;
  26. }
  27. public String getGender() {
  28. return gender;
  29. }
  30. public void setGender(String gender) {
  31. this.gender = gender;
  32. }
  33. public String getEmail() {
  34. return email;
  35. }
  36. public void setEmail(String email) {
  37. this.email = email;
  38. }
  39. }

2.创建bean的dao

  1. public interface userDao {
  2. public List findAll();
  3. }

3.创建bean的userService的接口

package club.twzw.service;

import club.twzw.bean.User;
import org.springframework.stereotype.Service;

import java.util.List;

public interface UserService {
    public List<User> findAll();

}

4.实现userServiceImpl,并给userServiceImpl 起别名userService

@Service("userService")                    
public class userServiceImpl implements userService {

    @Override
    public List<user> findAll() {
        System.out.println("查询所有用户。。。");
        return null;//service.findAll();
    }
}

5.在resources文件下创建文件applicationContext.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: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/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">


    <!--只处理Service和dao -->
    <context:component-scan base-package="club.twzw">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

</beans>

7.书写测试方法

   @Test
    public void testQueryUserList() {
        ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
        userService service = (userService) ac.getBean("userService"); // 因为给service起了别名,所以通过id的方式获取class
        service.findAll();
    }

在web.xml文件中修改并配置过滤器,中文乱码过滤

<servlet>
    <servlet-name>spring-dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!--加载springmvc.xml配置文件-->
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:springmvc.xml</param-value>
    </init-param>
    <!--启动服务器时,创建该servlet-->
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>spring-dispatcher</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>

在resources文件夹下创建springmvc.xml文件,开启注解扫描,视图解析器以及过滤静态资源和springmvc注解支持

<!--开启注解扫描,只扫描controller-->
<context:component-scan base-package="club.twzw">
    <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="suffix" value=".jsp"/>
    <property name="prefix" value="/WEB-INF/views/"/>
</bean>

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


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

书写controller

package club.twzw.controller;

import club.twzw.bean.User;
import club.twzw.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
public class UserController {

    @Autowired
    private UserService service;

    @RequestMapping("/findAll")
    public String findAll(Model model){
        System.out.println("success");
        List<User> all = service.findAll();
        model.addAttribute("user",all);
        return "list";
    }
}

index.jsp
//

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
    <body>
        <a href="/findAll">查看所有用户</a>
    </body>
</html>

scuccess

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
    <head>
        <title>scuccess</title>
    </head>
    <body>
        <h1>scuccess</h1>
    </body>
</html>

SSM整合(三阶段) - 图1
页面如果做成显示,自此成功添加spring mvc 开始整合

在整合之前需要明白,我们需要在controller中调用service,最快捷的便是使用依赖注入,而至今使用Tomcat服务器只加载了springmvc.xml文件,并没有applicationContext.xml的加载(也就是spring并没有被加载),所以可以通过监听ServeltContext域对象,在创建时加载spring的配置文件(applicationContext.xml)
SSM整合(三阶段) - 图2
配置监听器

在web.xml文件下添加listener,context-param设置监听和applicationContext.xml的文件路径

<!--加载Spring-->
<!--配置监听器,默认只加载web-inf目录下的applicationContext.xml-->
<!--但是我们的文件在resources文件夹下-->                        <<<<------
<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>

<!--加载spring mvc-->
<!--配置前端控制器-->
<servlet>
    <servlet-name>spring-dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!--加载springmvc.xml配置文件-->
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:springmvc.xml</param-value>
    </init-param>
    <!--启动服务器时,创建该servlet-->
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>spring-dispatcher</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>

这样我们就可以使用依赖注入了
使用依赖注入并从新发布,如果正常,就可以在控制台看到两句话

package club.twzw.controller;
import club.twzw.service.impl.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class UserController {

    @Autowired
    private UserService service;

    @RequestMapping("/findAll")
    public String findAll(){
        System.out.println("success");
        service.findAll();
        return "success";
    }
}

SSM整合(三阶段) - 图3
这样spring mvc 就已经整合完毕了
建立mybatis环境

在UserDao中使用注解查询

package club.twzw.dao;

import club.twzw.bean.User;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;

import java.util.List;
@Repository
public interface UserDao {

    @Select("select * from user")
    public List<User> findAll();

}

创建mybatis的核心配置文件mysqlConfig.xml

<environments default="mysql">
    <!--配置mysql-->
    <environment id="mysql">
        <!--配置事务类型-->
        <transactionManager type="JDBC"/>
        <!--配置数据源/连接池-->
        <dataSource type="POOLED">
            <!--配置连接数据库的基本信息-->
            <property name="driver" value="com.mysql.jdbc.Driver"/>
            <property name="url" value="jdbc:mysql://xx.xx.xx:3306/learn?useSSL=false"/>
            <property name="username" value="learn"/>
            <property name="password" value="123456"/>
        </dataSource>
    </environment>
</environments>

<!--指定映射配置文件的位置,映射配置文件指的是每个dao独立的配置文件-->
<mappers>
    <!--使用xml进行查询-->
    <!--<mapper resource="mapper/UserDao.xml"/>-->
    <!--使用注解-->
    <!--<mapper class="club.twzw.dao.UserDao"/>-->
    <!--扫描mapper下所有注解-->
    <package name="mapper"/>
</mappers>

书写测试方法

@Test
public void test() throws IOException {
    InputStream resourceAsStream = Resources.getResourceAsStream("mysqlConfig.xml");
    SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
    SqlSessionFactory factory = builder.build(resourceAsStream);
    SqlSession session = factory.openSession(true);

    UserDao mapper = session.getMapper(UserDao.class);
    List<User> all = mapper.findAll();
    for (User user : all) {
        System.out.println(user);
    }
}

输出结果:
SSM整合(三阶段) - 图4
说明了mybatis可用,那么可以开始整合了
整理mybatis,思路相同,同样使用依赖注入,将mysqlConfig.xml添加到容器中,并自动注入

在spring的文件中整合mybatis,配置连接池,factory,dao所在的包,此时有无将mysqlConfig.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: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/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">


    <!--只处理Service和dao -->
    <context:component-scan base-package="club.twzw">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <!--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://xx.xx.xx.xx:3306/learn?useSSL=false"/>
        <property name="user" value="learn"/>
        <property name="password" value="123456"/>
    </bean>
    <!--配置sqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!--配置dao所在的包-->
    <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="club.twzw.dao"/>
    </bean>
</beans>

使用依赖注入

在dao类上添加@Repository注解

@Repository                    <<<<<--------
public interface UserDao {

    @Select("select * from user")
    public List<User> findAll();
}

在serviceimpl中注入接口

package club.twzw.service.impl;

import club.twzw.bean.User;
import club.twzw.dao.UserDao;
import club.twzw.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service("UserService")
public class UserServiceImpl implements UserService {


    @Autowired
    private UserDao dao;

    public List<User> findAll() {
        System.out.println("查询所有用户。。。");
        return dao.findAll();
    }
}

修改controllerfindAll方法

package club.twzw.controller;

import club.twzw.bean.User;
import club.twzw.service.impl.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
public class UserController {

    @Autowired
    private UserService service;


    @RequestMapping("/findAll")
    public String findAll(Model model){
        System.out.println("success");
        List<User> all = service.findAll();
        model.addAttribute("user",all);
        return "list";
    }
}

添加list.jsp

<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2019/10/29
  Time: 21:07
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <c:forEach items="${user}" var="user">
        <tr>
            <td>${user.id}</td>
            <td>${user.name}</td>
            <td>${user.gender}</td>
            <td>${user.email}</td>
        </tr>
    </c:forEach>
</body>
</html>

实现访问
SSM整合(三阶段) - 图5
实现插入

controller

@RequestMapping("/save")
public String save(Model model){
    System.out.println("success");
    User u = new User();
    u.setEmail("184611875@qq.com");
    u.setGender("男");
    u.setName("comi");
    boolean b = service.Save(u);
    System.out.println(b);
    return "success";
}

UserService

package club.twzw.service;

import club.twzw.bean.User;
import org.springframework.stereotype.Service;

import java.util.List;

public interface UserService {
    public List<User> findAll();

    public boolean Save(User u);
}
13

UserServiceImpl

package club.twzw.service.impl;

import club.twzw.bean.User;
import club.twzw.dao.UserDao;
import club.twzw.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service("UserService")
public class UserServiceImpl implements UserService {


    @Autowired
    private UserDao dao;

    public List<User> findAll() {
        System.out.println("查询所有用户。。。");
        return dao.findAll();
    }

    @Override
    public boolean Save(User u) {
        return dao.Save(u);
    }
}

dao

package club.twzw.dao;

import club.twzw.bean.User;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;

import java.util.List;
@Repository
public interface UserDao {

    @Select("select * from user")
    public List<User> findAll();

    @Insert("insert into user (name,gender,email) values(#{name},#{gender},#{email})")
    public boolean Save(User u);
}

输出:
SSM整合(三阶段) - 图6