ssm框架——springMVC+spring+mybatis整合流程

概述:

  ssm框架在项目中经常使用到,应用比较广泛,下面将介绍如何在idea中搭建ssm框架,以及搭建过程中遇到的坑和爬坑的过程~项目的搭建主要思想是:采用分层的想法,对web层,service层,dao层;分别创建一个sping配置文件来管理;

  web层对应的是spring-web.xml;主要配置一些类似:处理器映射器,处理器适配器,视图解析器....解决访问静态资源的问题;

  service层对应的是spring-service.xml;主要是开启注解扫描,管理service层的bean对象即可

  dao层对应的是spring-dao.xml;需要处理的是整合mybatis框架,遵循一个原则:如果spring和mybatis都能处理的事情,让spring来处理,主要负责:扫描和管理dao层的bean对象,配置数据库,数据库连接池,配置SqlSessionFactory对象,配置事务管理器,以及配置扫描接口包对象……其中SqlsessionFactory对象和扫描接口包对象是主要用来配置mapper映射文件分离的。

  当然还有一些类似db.properties,日志配置文件等等之类的~

步骤:

  0.项目的总结构

 

  1.导入maven依赖

    使用到的技术:springMVC /spring /mybatis/ gson /c3po /mysql连接java /spring连接mybatis /以及一些依赖包common-logging log4j...

    (spring连接springMVC的时候并不需要导入类似spring连接mybatis这样的依赖包,但是要注意如何在web.xml中加载多个spring配置文件,因为是分层,每一层都有自己的spring配置文件)

  项目pom.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<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/maven-v4_0_0.xsd">

    <modelVersion>4.0.0</modelVersion>
    <packaging>war</packaging>

    <name>MybatisLearn</name>
    <groupId>com.kylin</groupId>
    <artifactId>MybatisLearn</artifactId>
    <version>1.0-SNAPSHOT</version>

    <build>
        <plugins>
            <plugin>
                <groupId>org.mortbay.jetty</groupId>
                <artifactId>maven-jetty-plugin</artifactId>
                <version>6.1.7</version>
                <configuration>
                    <connectors>
                        <connector implementation="org.mortbay.jetty.nio.SelectChannelConnector">
                            <port>8888</port>
                            <maxIdleTime>30000</maxIdleTime>
                        </connector>
                    </connectors>
                    <webAppSourceDirectory>${project.build.directory}/${pom.artifactId}-${pom.version}
                    </webAppSourceDirectory>
                    <contextPath>/</contextPath>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        <!-- junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12-beta-3</version>
            <scope>test</scope>
        </dependency>

        <!-- log4j日志部分 -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>

        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

        <!-- spring和springMVC 的基本依赖 开始 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>4.3.18.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-expression</artifactId>
            <version>4.3.18.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>4.3.18.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>4.3.18.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.3.18.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>4.3.18.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>4.3.18.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>4.3.18.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.3.18.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.3.18.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>4.3.18.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>4.3.18.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>4.3.18.RELEASE</version>
        </dependency>
        <!-- spring 的基本依赖 结束 -->

        <!-- 添加mybatis依赖 -->
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.1</version>
        </dependency>
        <!--spring连接mybats-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.1</version>
        </dependency>


        <!--servlet和jsp的依赖-->
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>javax.servlet.jsp-api</artifactId>
            <version>2.2.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>

        <!--gson处理json数据-->
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.2.4</version>
        </dependency>

        <!-- mysql 驱动 -->
        <dependency>
            <groupId>Mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.30</version>
        </dependency>

        <!--c3p0连接池-->
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.2</version>
        </dependency>


        <!-- 需要的log4j2日志包依赖 -->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.5</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-web</artifactId>
            <version>2.5</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-1.2-api</artifactId>
            <version>2.5</version>
        </dependency>

        <!--文件上传-->
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>

        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.1.1</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

    </dependencies>

</project>

   注意:这里mybatis的版本要和spring-mybatis的版本要匹配,否则会有异常-----org.mybatis.spring.transaction.SpringManagedTransaction.getTimeout()

匹配的版本有如下:

  3.3.1版本的mybatis和1.1.1的spring-mybatis匹配,

  3.4.1版本的mybatis和1.3.1的spring-mybatis匹配

  2.在resources目录下创建一个spring目录,分别编写spring-web.xml,spring-service.xml和spring-dao.xml

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

    <!-- 4.扫描web相关的bean -->
    <context:component-scan base-package="com.kylin.controller" />
    <mvc:annotation-driven />


    <!-- 3.配置jsp 显示ViewResolver -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />-->
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>

</beans>

    2.2spring-service.xml文件(主要扫描自己层,创建和管理bean对象即可)

<?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: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
    http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx.xsd">
    <!-- 扫描service包下所有使用注解的类型 -->
    <context:component-scan base-package="com.kylin.service" />

</beans>

    2.3spring-dao.xml文件(整合mybatis框架,处理mapper映射文件和接口分离问题)

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

    <!--扫描dao层-->
    <context:component-scan base-package="com.kylin.dao" />


    <!-- 配置整合mybatis过程 -->
    <!-- 1.引入数据库配置的参数properties-->
    <context:property-placeholder location="classpath:db.properties" />

    <!-- 配置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}"/>
        <!--池参数不进行配置,使用默认池参数-->
    </bean>

    <!-- 3. 配置事务管理器,大概事务就由该bean来管理,不用我们手动的提交 -->
    <bean id="transactionManager"
          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- 注入数据库连接池 -->
        <property name="dataSource" ref="dataSource" />
    </bean>
    <!-- 4.配置基于注解的声明式事务 -->
    <!--<tx:annotation-driven transaction-manager="transactionManager" />-->


    <!-- 5.配置SqlSessionFactory对象 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 注入数据库连接池 -->
        <property name="dataSource" ref="dataSource" />

        <!-- 配置MyBaties全局配置文件:mybatis-config.xml -->
        <property name="configLocation" value="classpath:mybatis-config.xml" />
        <!-- 扫描domain包 使用别名 -->
        <!--<property name="typeAliasesPackage" value="com.blog.dao" />-->
        <!-- 扫描找到映射文件:mapper需要的xml文件 -->
        <property name="mapperLocations" value="classpath:mapper/*.xml" />
    </bean>

    <!-- 4.配置扫描Dao接口包,动态实现Dao接口,注入到spring容器中 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 注入sqlSessionFactory -->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
        <!-- 给出需要扫描Dao接口包 -->
        <property name="basePackage" value="com.kylin.dao" />
    </bean>


</beans>

  3.配置web.xml文件(加载多个spring文件,配置前端控制器等……)

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
         xmlns="http://java.sun.com/xml/ns/j2ee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
         http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">


    <!--首先是spring整合springMVC的过程-->
    <!--  ContextLoaderListener 加载IOC容器,Spring框架的底层是listener -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
         <!-- 指定Spring的配置文件的路径和名称 -->
        <param-value>classpath*:spring/spring-service.xml;classpath*:spring/spring-dao.xml</param-value>
    </context-param>
    <!-- Bootstraps the root web application context before servlet initialization -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!--配置前端控制器-->
    <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*:spring/spring-web.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>

注意:

  当需要加载多个spring配置文件的时候,使用<content-param>标签,并且如果有多个的话,中间用;来分离(具体看上面),还有那个监听器非常重要,底层就是靠的这个来加载多个spring配置文件的,而且最好把这2个标签放在最前面,接下来就是配置前端控制器,由于我们配置文件的路径不是默认的,所以也需要加上<init-param>来配置上spring-web.xml的路径。

  4.mybatis-config.xml配置文件以及db.properties文件

    4.1mybatis-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>


    <!--可以配置一些spring配置不了的东西,例如spring分页插件~~~等等之类的-->
</configuration>

    4.2db.properites

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatisdayday01?useUnicode=true&characterEncoding=utf-8&useSSL=false
jdbc.username=root
jdbc.password=root

 

  5.编写mapper映射文件和dao层的接口

  由于idea并不能解析在src下非java的文件,所以需要使mapper映射文件和接口分离,那么就不能再使用mybatis-config.xml来管理,而是用spring-dao.xml管理,具体的配置已经在上面的文件中给了~接下来介绍的是mapper的映射文件的写法

    5.1在resources下创建mapper目录,创建UserMapper.xml映射文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN"
        "http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">

<!-- mapper 为根元素节点, 一个namespace对应一个dao -->
<mapper namespace="com.kylin.dao.UserDao">

    <insert id="insertUser" parameterType="com.kylin.pojo.User">
        insert  into user (id,username,birthday,sex,address)
        values(#{id},#{username},#{birthday},#{sex},#{address})
    </insert>

    <select id="selectAllUsers" resultType="com.kylin.pojo.User">
        select * from user
    </select>
</mapper>

 注意:映射文件中的命名空间的路径指的是该映射文件对应的接口文件的路径!!!

      5.2就在src下创建相应的dao层的接口文件

package com.kylin.dao;

import com.kylin.pojo.User;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface UserDao {

    void insertUser(User user);
    List<User> selectAllUsers();
}

  6.编写service层的东西,创建service层,里面再创建一个Impl目录用来实现service层的接口

    6.1编写UserService接口

package com.kylin.service;

import com.kylin.pojo.User;

import java.util.List;

public interface UserService {

    void insertUser(User user);
    List<User>selectAllUsers();
}

    6.2编写UserService接口的实现类UserServiceImpl.java

package com.kylin.service.Impl;

import com.kylin.dao.UserDao;
import com.kylin.pojo.User;
import com.kylin.service.UserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service(value = "userServiceImpl")
public class UserServiceImpl implements UserService {

    @Resource(name = "userDao")
    private UserDao userDao;
    @Override
    public void insertUser(User user) {
        //调用dao层
        userDao.insertUser(user);
    }

    @Override
    public List<User> selectAllUsers() {
        return userDao.selectAllUsers();
    }
}

 注意:是把实现类设置成bean对象,不过可能名字使用的是接口名的

  7.2编写web层UserController

package com.kylin.controller;

import com.google.gson.Gson;
import com.kylin.pojo.User;
import com.kylin.service.Impl.UserServiceImpl;
import com.kylin.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Controller
public class UserController {
    @Resource(name = "userServiceImpl")
    private UserServiceImpl userService;
    //插入用户
    @RequestMapping(value = "/insert",method = RequestMethod.POST)
    @ResponseBody
    public String insertUser(@RequestBody String jsonStr){
        Gson gson=new Gson();
        User user=gson.fromJson(jsonStr,User.class);
        user.setBirthday(new Date());
        userService.insertUser(user);
        return "hello world";

    }
    @RequestMapping(value = "/selectAllUsers",method = RequestMethod.GET,produces = "text/html;charset=utf-8")
    @ResponseBody
    public String selectAllUsers(){
        List<User>userList=userService.selectAllUsers();
        for (User user:userList){
            System.out.println(user.getId());
        }
        return "hello world2";
    }

}

总结:

  这样就大概搭建好一个ssm框架,文章中省略了一些东西,比如数据库的创建之类的~但是那些都不是主要的内容;个人觉得是:需要处理好web.xml中加载多个spring配置文件的问题,以及mapper映射文件分离的问题~还有就是spring和springMVC的整理并不需要其他的jar包,但是spring连接mybatis框架需要额外的jar包spring-mybatis.jar,这里的版本需要对应好;不然会有异常。

 

posted @ 2018-08-22 11:50  Shan-KyLin  阅读(2577)  评论(0编辑  收藏  举报