SSM整合教程(附代码)

SSM整合

1、引入Maven依赖

  • SpringMVC
  • Spring
  • MyBatis
  • MyBatis整合Spring适配包
  • 数据库连接池 - 数据库连接驱动
  • Servlet - api
<dependencies>
    <!--Junit-->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>
    <!--数据库驱动-->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.47</version>
    </dependency>
    <!-- 数据库连接池 -->
    <dependency>
        <groupId>com.mchange</groupId>
        <artifactId>c3p0</artifactId>
        <version>0.9.5.2</version>
    </dependency>
 
    <!--Servlet - JSP -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>servlet-api</artifactId>
        <version>2.5</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet.jsp</groupId>
        <artifactId>jsp-api</artifactId>
        <version>2.2</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>
 
    <!--Mybatis-->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.2</version>
    </dependency>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>2.0.2</version>
    </dependency>
 
    <!--Spring-->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.1.9.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>5.1.9.RELEASE</version>
    </dependency>
</dependencies>

Maven资源过滤设置

<build>
    <resources>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.properties</include>
                <include>**/*.xml</include>
            </includes>
            <filtering>false</filtering>
        </resource>
        <resource>
            <directory>src/main/resources</directory>
            <includes>
                <include>**/*.properties</include>
                <include>**/*.xml</include>
            </includes>
            <filtering>false</filtering>
        </resource>
    </resources>
</build>
  • 用于避免资源未编译加载,作用是指定需加载的资源

2、编写SSM整合关键配置文件

2.1 Src下包结构

  • controller
  • mapper
  • service
  • pojo

2.2 resource下的SSM配置文件

1.数据源文件:database.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/xxx?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai
jdbc.username=root
jdbc.password=root
  • 上述jdbc.url 设置了编码与时区
2.mybatis核心文件:mybatis-config.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>
    <!-- 类型别名 -->
    <typeAliases>
        <package name="xxx.xxx.pojo"/>
    </typeAliases>
</configuration>
  • 仅需要在此核心配置文件中配置扫描别名路径即可,数据源配置留在spring容器中配置
3.Spring容器文件:applicationContext.xml
  • 将spring-dao.xml 、 spring-service.xml 、spring-mvc.xml 串联起来
    <import resource="applicationContext-dao.xml"/>
    <import resource="applicationContext-service.xml"/>
  • 此两个配置文件将会导入到同一个文件(applicationContext.xml)中,所以他们作用域共享,类似于本质定义再一个配置文件中
4.Spring数据源文件:spring-dao.xml

操作:关联数据源配置文件 + 配置DataSource数据源 + 创建SqlSessionFactory工厂

1.关联数据源配置文件

2.配置DataSource数据源

3.创建SqlSessionFactory

spring文件头部内容:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
    
</beans>
4.1连接池配置

方式一:Spring自带原生配置

	<!-- 关联数据源配置文件 -->
    <bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
        <property name="location">
            <value>classpath:database.properties</value>
        </property>
    </bean>
    <!-- 配置DataSource数据源 -->
    <bean id="dataSource" destroy-method="close" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>

方式二 c3p0连接池配置

  • 自动化操作(自动化加载配置文件,并且自动设置至对象中)
<!-- 1.关联数据库配置文件 -->
<context:property-placeholder location="database.properties"/>
<!-- 2.配置c3p0连接池 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    <!-- 基本数据源配置 -->
	<property name="driverClass" value="${jdbc.driver}"/>
    <property name="jdbcUrl" value="${jdbc.url}"/>
    <property name="user" value="${jdbc.username}"/>
    <property name="password" value="${jdbc.password}"/>
    <!-- c3p0连接池私有属性 -->
    <property name="maxPoolSize" value="30"/>
    <property name="minPoolSize" value="10"/>
    <!-- 获取连接超时时间 -->
    <property name="checkoutTimeout" value="10000"/>
    <!-- 等等... -->
</bean>
4.2 配置SqlSessionFactory工厂对象()
  • 注入数据源
  • 绑定配置文件

方式一: sqlSessionFactoryBeanName

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
	<property name="dataSource" ref="dataSource"/>
    <property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>
<!-- 配置dao接口扫描包,动态都实现了Dao接口可以注入到Spring容器中 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
	<!-- 注入sqlSessionFactory -->
    <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    <!-- 要扫描到包 -->
    <property name="basePackage" value="com.xx.xx"/>
</bean>
5.spring-service.xml
  • 扫描service包,开启注解支持

  • 注入业务类

  • 开启声明式事务

Spring头文件

<?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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

</beans>
1.扫描service包
<context:component-scan base-package="com.xx.xx"/>
2.将业务类注入到Spring

方式一:xml注入

前提:service实现类中存在实现mapper属性并且存在set方法,类似于工厂模式,为mapper接口定义实现类

<bean id="serviceImpl" class="com.xx.xx.xxImpl">
	<property name="xxxMapper" ref="xxxMapper"/>
</bean>

方式二:注解注入

  • @Service:定义在service实现类上方,可通过(“具体实现接口名”)来进行实现注入

  • @Autowired:定义在mapper属性上方,对mapper进行装配

实现代码如下

@Service("ArticleService")
public class xxxServiceImpl implements xxxService {

    @Autowired
    private ArticleMapper xxxMapper;
}
3.声明式事务配置
<!-- 声明式事务配置 -->
<bean id="transactionMapper" class="org.springframework.jdbc.datasource.DataSourceTransactionMapper">
    <!-- 注入数据源 -->
	<property name="dataSource" ref="dataSource"/>
</bean>
4.aop事务支持
6.Spring数据源文件:spring-mvc.xml

干mvc干的事

  • 注解驱动
  • 静态资源过滤
  • 扫描包:controller
  • 视图解析器
1.注解驱动
<mvc:annotation-driven/>
2.静态资源过滤
<mvc:default-servlet-handler/>
3.扫描包:controller
<context:component-scan base-package="com.xx.controller"/>
4.视图解析器
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <!-- 前缀 -->
    <property name="prefix" value="/WEB-INF/jsp/"/>
    <!-- 后缀 -->
    <property name="suffix" value=".jsp"/>
</bean>

2.3 web.xml的配置

  • 用于配置 SpringMVC 环境
  • 编码过滤
1.配置DispactchServlet
    <!-- Spring Mvc的核心是一个Servlet,称为前端控制器 -->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!-- 加载SpringMvc配置文件 -->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc-servlet.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>
2.乱码过滤
<filter>
	<filter-name>encodingFilter</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-mapper>
	<filter-name>encodingFilter</filter-name>
    <!-- 过滤所有 -->
    <url-pattern>/*</url-pattern>
</filter-mapper>

最终目录结构:
SSM整合教程(附代码)

**需要注意:**如果访问controller发生404,那么我们需要在web-inf下新建lib包
SSM整合教程(附代码)
并且
SSM整合教程(附代码)

SSM整合教程(附代码)
全选添加

最后附上代码:

database.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/demo?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai
jdbc.username=root
jdbc.password=root

mybatis-config.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>

    <!-- 开启包扫描 -->
    <typeAliases>
        <package name="com.my.pojo"/>
    </typeAliases>

</configuration>

spring-dao.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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
        <property name="location">
            <value>classpath:database.properties</value>
        </property>
    </bean>

    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}"/>
        <property name="jdbcUrl" value="${jdbc.url}"/>
        <property name="user" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>

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

    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <property name="basePackage" value="com.my.mapper"/>
    </bean>

</beans>

spring-service.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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

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

    <bean id="serviceImpl" class="com.my.service.impl.StudentServiceImpl">
        <property name="studentMapper" ref="studentMapper"/>
    </bean>


    <!-- 声明式事务配置 -->
    <bean id="transactionMapper" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- 注入数据源 -->
        <property name="dataSource" ref="dataSource"/>
    </bean>

</beans>

spring-servlet.xml

<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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.2.xsd ">

    <mvc:annotation-driven/>

    <mvc:default-servlet-handler/>

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

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- 前缀 -->
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <!-- 后缀 -->
        <property name="suffix" value=".jsp"/>
    </bean>


</beans>

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

    <import resource="spring-dao.xml"/>
    <import resource="spring-service.xml"/>
    <import resource="springmvc-servlet.xml"/>

</beans>

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">

    <!-- Spring Mvc的核心是一个Servlet,称为前端控制器 -->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!-- 加载SpringMvc配置文件 -->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc-servlet.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>


</web-app>

Student.java

public class Student {
    private Integer id;
    private String name;
    private String sex;
    private Integer age;
    private String address;
    /** 此处省略getter setter方法 */
}

StudentMapper.java

public interface StudentMapper {

    List<Student> getStudentList();

}

StudentMapper.xml

<?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.my.mapper.StudentMapper">


    <select id="getStudentList" resultType="com.my.pojo.Student">
        select * from student
    </select>
</mapper>

StudentService.java

public interface StudentService {

    List<Student> getStudentList();

}

StudentServiceImpl.java

public class StudentServiceImpl implements StudentService {
    private StudentMapper studentMapper;

    public StudentMapper getStudentMapper() {
        return studentMapper;
    }

    public void setStudentMapper(StudentMapper studentMapper) {
        this.studentMapper = studentMapper;
    }

    public List<Student> getStudentList() {
        return studentMapper.getStudentList();
    }
}

StudentController.java

@Controller
@RequestMapping("/student")
public class StudentController {

    @RequestMapping("/getInfoList")
    public ModelAndView getStudentList(ModelAndView modelAndView){
        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        StudentService studentService = (StudentService)ctx.getBean("serviceImpl");
        List<Student> studentList = studentService.getStudentList();
        modelAndView.addObject("students",studentList);
        modelAndView.setViewName("helloSSM");
        return modelAndView;
    }

}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    ${students}
</body>
</html>

最终测试:

http://localhost:8080/SSM/student/getInfoList

效果如下:

SSM整合教程(附代码)

核心概念:我们将dao、service、mvc区分为了三个xml文件,这样更便于理解与应用

上一篇:SSM之Mybatis动态SQL/动态Sql怎么用?动态SQL有什么作用?动态SQL与普通SQL语句哪里不一样


下一篇:Java项目:星月宿舍学生管理系统(java+SSM+JSP+MYSQL+Easyui)