欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

SSM 框架集成

程序员文章站 2022-09-27 21:32:14
1.SSM是什么? SSM是指目前最主流的项目架构的三大框架: SpringMVC : spring的 Web层框架,是spring的一个模块 Spring :容器框架 MyBatis :持久层框架 2.spring与mybatis集成示例 我们集成mybatis和spring,主要是为了让myba ......

1.ssm是什么?

ssm是指目前最主流的项目架构的三大框架:
  springmvc : spring的 web层框架,是spring的一个模块
  spring :容器框架
  mybatis :持久层框架

 

2.spring与mybatis集成示例

  我们集成mybatis和spring,主要是为了让mybatis用spring的事务管理

  2.1 相关导入jar包

    spring依赖包:

  SSM 框架集成

    mybatis依赖包:

   SSM 框架集成

    mybatis和spring框架集成的桥梁包:

    spring自己并没有集成mybatis框架,而是有mybatis自己来集成,所以还需要spring框架集成的桥梁包

   SSM 框架集成

    

    数据库驱动包和连接池:

   SSM 框架集成

   SSM 框架集成

    mybatis支持的日志包log4j:

    SSM 框架集成

  2.2 项目整体结构

  SSM 框架集成

  2.3 mapper层

package com.gjs.ssm.mapper;

import java.util.list;
import com.gjs.ssm.pojo.user;

public interface usermapper {
    
    public    int insert(user user);
    
    public user selectbyprimarykey(integer id);
    
    public list<user> selectlist();
    
    public int deltebyprimarykey(integer id);
}

  mapper.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.gjs.ssm.mapper.usermapper">
    
    <insert id="insert" parametertype="com.gjs.ssm.pojo.user">
        insert into user (name,password,age)values(#{name},#{password},#{age})
    </insert>
    
    <select id="selectbyprimarykey" parametertype="integer" resulttype="com.gjs.ssm.pojo.user">
        select * from user where id = #{id}
    </select>
    
    <select id="selectlist"  resulttype="com.gjs.ssm.pojo.user">
        select * from user
    </select>
      
      <delete id="deltebyprimarykey" parametertype="int">
          delete from user where id = #{id}
      </delete>
      
</mapper>

  2.4 service层

package com.gjs.ssm.service.impl;

import java.util.list;

import org.springframework.beans.factory.annotation.autowired;
import org.springframework.stereotype.service;

import com.gjs.ssm.mapper.usermapper;
import com.gjs.ssm.pojo.user;
import com.gjs.ssm.service.userservice;

@service
public class userserivceimpl implements userservice{
    @autowired
    usermapper usermapper;
    
    @override
    public int inset(user user) {
        return usermapper.insert(user);
    }

    @override
    public user selectbyprimarykey(integer id) {
        return usermapper.selectbyprimarykey(id);
    }

    @override
    public list<user> selectlist() {
        return usermapper.selectlist();
    }

    @override
    public int deltebyprimarykey(integer id) {
        return usermapper.deltebyprimarykey(id);
    }

}

 

 

  2.5层与层之间(mapper和service)spring对象的创建和依赖关系的维护(a)

  之前我们mapper对象的创建是通过sqlsession对象创建的,sqlsession对象又是sqlsessionfactory对象创建出来的,而sqlsessionfactory对象是通过读取配置文件中的相关配置创建的。
  所谓的spring与mybatis集成,说白了就是把这些对象的创建都交给spring来处理。那怎么让spring自己创建这些对象呢?
  spring-mybatis桥梁包中提供的org.mybatis.spring.sqlsessionfactorybean类可以创建sqlsessionfactory对象,org.mybatis.spring.mapper.mapperscannerconfigurer类可以用来创建 mapper接口的代理对象。所以只要在spring中配置这两个对象并注入依赖即可。具体配置如下:

spring.xml:

<?xml version="1.0" encoding="utf-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:p="http://www.springframework.org/schema/p"
    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:xsi="http://www.w3.org/2001/xmlschema-instance"
    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
        ">
        
    <!-- 开启注解包扫描 -->
    <context:component-scan base-package="com.gjs.ssm"/>
    
    <!-- 读取db.properties 配置文件 -->
    <context:property-placeholder location="classpath:db.properties"/>
    
    
    <!-- 配置druid连接池 -->
    <bean id="datasource" class="com.alibaba.druid.pool.druiddatasource">
        <property name="driverclassname" value="${jdbc.driverclassname}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        <property name="maxactive" value="${jdbc.maxactive}"/>
    </bean>
    
    <!-- 配置sqlsessionfactorybean对象 -->
    <bean name="sqlsessionfactory" class="org.mybatis.spring.sqlsessionfactorybean">
        <!-- 注入数据源 -->
        <property name="datasource" ref="datasource"/>
        
        <!-- 配置映射文件 -->
        <property name="mapperlocations">
            <array>
                <value>classpath:com/gjs/ssm/mapper/*mapper.xml</value>
            </array>
        </property>

        <!-- 配置包扫描的别名 -->
        <property name="typealiasespackage" value="com.gjs.ssm.pojo"/>
    
        <!-- 
        如果需要读取mybatis框架的配置文件mybat-config.xml可使用:
        <property name="configlocation" value="classpath:mybatis-config.xml"/>
        不过一般不需要
         -->
         
    </bean>
    
    <!-- sqlsession对象的创建只需通过sqlsessionfactory对象调用opensession()方法即可,spring会自动创建 -->
    
    <!-- 使用包扫描批量创建 mapper接口对应的代理对象 -->
    <bean class="org.mybatis.spring.mapper.mapperscannerconfigurer">
        <!-- 配置包扫描创建代理对象的位置 -->
        <property name="basepackage" value="com.gjs.ssm.mapper"/>
        
        <!-- 注入sqlsessionfactory bean的名称 -->
        <property name="sqlsessionfactorybeanname" value="sqlsessionfactory"/>
    </bean>
    
    
    
    <!-- 配置事务管理器 -->
    <bean id="txmanager"  class="org.springframework.jdbc.datasource.datasourcetransactionmanager">
        <!-- 注入数据源 -->
        <property name="datasource" ref="datasource"/>
    </bean>
    
    
    <!-- 配置事务通知 -->
    
    <tx:advice id="txadvice" transaction-manager="txmanager">
        <tx:attributes>
            <!-- dql -->
            <tx:method name="select*" read-only="true" isolation="repeatable_read" propagation="required"/>
            <tx:method name="get*" read-only="true" isolation="repeatable_read" propagation="required"/>
            <tx:method name="find*" read-only="true" isolation="repeatable_read" propagation="required"/>
            <tx:method name="query*" read-only="true" isolation="repeatable_read" propagation="required"/>
            <!-- 非dql  -->
            <tx:method name="*" read-only="false" isolation="repeatable_read" propagation="required"/>        </tx:attributes>
    </tx:advice>
    
    
    
    <!-- 使用aop将事务切入到service层 -->
    <aop:config >
        <!-- 切入点 -->
        <aop:pointcut expression="execution(* com.gjs.ssm.service..*.*(..))" id="pt"/>
        
        <!-- 切面 = 切入点+通知-->
        <aop:advisor advice-ref="txadvice" pointcut-ref="pt"/>
        
        <!-- spring 负责织入 -->
    </aop:config>

</beans>

  下面这段代码是其中的关键

<!-- 配置sqlsessionfactorybean对象 -->
    <bean name="sqlsessionfactory" class="org.mybatis.spring.sqlsessionfactorybean">
        <!-- 注入数据源 -->
        <property name="datasource" ref="datasource"/>
        
        <!-- 配置映射文件 -->
        <property name="mapperlocations">
            <array>
                <value>classpath:com/gjs/ssm/mapper/*mapper.xml</value>
            </array>
        </property>

        <!-- 配置包扫描的别名 -->
        <property name="typealiasespackage" value="com.gjs.ssm.pojo"/>
    
        <!-- 
        如果需要读取mybatis框架的配置文件mybat-config.xml可使用:
        <property name="configlocation" value="classpath:mybatis-config.xml"/>
        不过一般不需要
         -->
         
    </bean>
    
    <!-- sqlsession对象的创建只需通过sqlsessionfactory对象调用opensession()方法即可,spring会自动创建 -->
    
    <!-- 使用包扫描批量创建 mapper接口对应的代理对象 -->
    <bean class="org.mybatis.spring.mapper.mapperscannerconfigurer">
        <!-- 配置包扫描创建代理对象的位置 -->
        <property name="basepackage" value="com.gjs.ssm.mapper"/>
        
        <!-- 注入sqlsessionfactory bean的名称 -->
        <property name="sqlsessionfactorybeanname" value="sqlsessionfactory"/>
    </bean>

  2. 5 测试代码

package com.gjs.ssm.test;

import java.util.list;

import org.junit.test;
import org.junit.runner.runwith;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.test.context.contextconfiguration;
import org.springframework.test.context.junit4.springjunit4classrunner;

import com.gjs.ssm.pojo.user;
import com.gjs.ssm.service.userservice;


@runwith(springjunit4classrunner.class)
@contextconfiguration("classpath:spring.xml")
public class userserivceimpltest {

    @autowired
    private userservice userservice;
    
    @test
    public void testinset() {
        user user = new user(null, "张三", "123", 30);
        int row = userservice.inset(user);
        system.out.println(row);
    }
    
    @test
    public void testselectbyprimarykey() {
        user user = userservice.selectbyprimarykey(3);
        system.out.println(user);
    }

    @test
    public void testselectlist() {
        list<user> selectlist = userservice.selectlist();
        system.out.println(selectlist);
    }

    @test
    public void testdeltebyprimarykey() {
        int row = userservice.deltebyprimarykey(3);
        system.out.println(row);
    }

}

3.springmvc的集成

  3.1 导入相关jar包  

  springmvc依赖包:

  SSM 框架集成

  jstl标签库依赖包:

  SSM 框架集成

  3.2 项目整体结构

   SSM 框架集成

  3.3 springmvc.xml配置文件

<?xml version="1.0" encoding="utf-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    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.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        ">
    <!-- 开启springmvc注解驱动 -->
    <mvc:annotation-driven/>
        
</beans>

  3.4 编写控制器

package com.gjs.ssm.controller;

import java.util.list;

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 com.gjs.ssm.pojo.user;
import com.gjs.ssm.service.userservice;

@controller
@requestmapping("/user")
public class usercontroller {
     
    @autowired
    private userservice userservice;
    
    @requestmapping("/list")
    public string list(model model) {
         
        list<user> users = userservice.selectlist();
        model.addattribute("users", users);
         
        return "/web-inf/view/user_list.jsp";
    }
}

  3.5 在web.xml配置springmvc的前端控制器(关键)

  web.xml是整个web项目的入口,其他配置文件都需要通过web.xml直接或间接读取。所以springmvc和spring集成的关键就在于在web.xml中配置读取spring和springmvc的配置文件。

<?xml version="1.0" encoding="utf-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemalocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1">
  <display-name>ssm集成</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  
  <!-- 配置字符编码过滤器 -->
  <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>
  
  <!-- 配置前端控制器 (分发器)-->
  <servlet>
      <servlet-name>mvc</servlet-name>
      <servlet-class>org.springframework.web.servlet.dispatcherservlet</servlet-class>
      
      <init-param>
          <!-- 读取配置文件 用通配符 *可以读取多个有相同前缀和后缀的文件-->
          <param-name>contextconfiglocation</param-name>
          <param-value>classpath:spring*.xml</param-value>
      </init-param>
      <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
      <servlet-name>mvc</servlet-name>
      <url-pattern>*.do</url-pattern>
  </servlet-mapping>
</web-app>

  3.6 编写jsp页面测试

<%@ page language="java" contenttype="text/html; charset=utf-8"
pageencoding="utf-8"%>
<!-- 引入jstl标签库  -->
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <title>insert title here</title>
    </head>
<body>
    <h3>用户列表</h3>
 
    <table border="1" style="width: 500px;" cellspacing="0">
        <tr>
            <th>id</th>
            <th>名称</th>
            <th>密码</th>
            <th>年龄</th>
        </tr>
 
 
    <c:foreach items="${users}" var="user">
        <tr>
            <td>${user.id}</td>
            <td>${user.name}</td>
            <td>${user.password}</td>
            <td>${user.age}</td>
        </tr>
    </c:foreach>
    </table>

</body>
</html>