SSM整合

介绍

下载SSM整合包

整合目标:

  • Spring和SpringMVC是一个整体,共用一个bean容器,所以我们不需要整合Spring和SpringMVC。
  • 让Spring管理MyBatis的SqlSessionFactory对象,生成SqlSessionFctory时,会读取MyBatis的核心配置文件。
  • mybatis和spring剩下的整合,就是通过spring管理mapper接口。使用mapper的扫描器自动扫描mapper接口在spring中进行注册生成的代理对象。生成代理对象时,需要SqlSessionFactory对象。

架构图

第一步:整合dao层
让Spring管理SqlSessionFctory对象。
mybatis和spring整合,通过spring管理mapper接口。
使用mapper的扫描器自动扫描mapper接口在spring中进行注册生成的代理对象。生成代理对象时,需要SqlSessionFactory对象。

第二步:整合service层
通过注解方式把Dao层对象注入到Service接口的实现类中。
在Servicr层中实现事务控制。

第三步:整合springmvc
由于springmvc是spring的模块,不需要整合。

整合SSM

  • 导入所有整合jar包。
  • 我们这里通过驱动式整合,我们要查询数据库里面的所有商品信息。

目录结构图

用到的基础类:

包名cn.domarvel.po:

  • Item.java:
public class Item {

    private Integer id;
    private String name;
    private Double price;
    private String detail;
    private byte[] pic;
    private Date createtime;

包名cn.domarvel.pocustom(这个是自定义po类,一般我们从数据库查数据用的就是poCustom,都是为了扩展性!!遵循这种规范比较好!!!)

  • ItemCustom.java:
public class ItemCustom extends Item{
    /*
     * 这里定义扩展属性
     */
}

包名cn.domarvel.dao

  • ItemMapper.java:
public interface ItemMapper {
    //获取所有用户
    public List<ItemCustom> findAllItems();
}
  • ItemMapper.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="cn.domarvel.pocustom.ItemCustom">
    <select id="findAllItems" resultType="cn.domarvel.po.ItemCustom">
        SELECT * FROM items
    </select>
</mapper>

包名cn.domarvel.service

  • 定义service接口
public interface ItemDaoService {
    public List<ItemCustom> findAllItems();
}

包名cn.domarvel.service.impl

  • 创建service接口的实现类
@Service("itemDaoServiceImpl")
public class ItemDaoServiceImpl implements ItemDaoService{

    @Resource(name="itemMapper")
    private ItemMapper itemMapper;

    /**
     * 查询所有的商品
     * @return
     * @author FireLang
     */
    @Override
    public List<ItemCustom> findAllItems() {
        return itemMapper.findAllItems();
    }

}

包名cn.domarvel.vo(当接受前端数据时就用这个,它一般是对pocustom或者其它类别的pocustom封装,以防止数据不够用,为什么不直接修改Item.java??因为这个Item类通常都是不修改的,你会越修改越乱。这是规范。你可以不准守都可以实现,但是准守总是有好处没坏处!)

  • ItemQueryVo.java
public class ItemQueryVo {
    /*
     * 这里封装实体类,用于前端数据查询,一般这个类可以传入到dao层。前提是你要对数据进行检查,是否有不合格的数据!!!
     */
    private ItemCustom itemCustom;

    public ItemCustom getItemCustom() {
        return itemCustom;
    }

    public void setItemCustom(ItemCustom itemCustom) {
        this.itemCustom = itemCustom;
    }
}

包名cn.domarvel.web.controller

  • ItemHandler.java
/**
 * 商品查询的控制器
 * @author FireLang
 *
 */
@Controller
public class ItemHandler {

    @Resource(name="itemDaoServiceImpl")
    private ItemDaoService itemDaoService;

    @RequestMapping("/item/showItems")
    public String showItems(Model model){
        model.addAttribute("itemsList", itemDaoService.findAllItems());
        return "/WEB-INF/content/showItems.jsp";
    }
}

WEB-INF下的content

  • showItems.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib prefix="c"  uri="http://java.sun.com/jsp/jstl/core"%>
<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    <h3>欢迎来到首页</h3>
    <c:forEach items="${requestScope.itemsList }" var="item">
        <p>商品名字=${item.name}---商品价格=${item.price }---生产日期=<fmt:formatDate value="${item.createtime}" pattern="yyyy-MM-dd HH:mm:ss"/>---描述=${item.detail }</p>
    </c:forEach>
</body>
</html>

整合Spring+MyBatis

sqlMapConfig.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>
<!-- 配置settings -->
<!-- 配置类的重命名等 -->
</configuration>
在applicationContext-dao.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"
    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-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 
        http://www.springframework.org/schema/aop 
        http://www.springframework.org/schema/aop/spring-aop-3.2.xsd 
        http://www.springframework.org/schema/tx 
        http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">

<!-- 加载数据库配置文件 -->
<context:property-placeholder location="classpath:Spring/db.properties"/>

<!-- 配置数据源,使用c3p0 -->
<!-- 所以必须设定destroy-method=”close”属性, 以便Spring容器关闭时,数据源能够正常关闭。
 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
    <property name="driverClass" value="${jdbc.driver}"/>
    <property name="jdbcUrl" value="${jdbc.url}"/>
    <property name="user" value="${jdbc.username}"/>
    <property name="password" value="${jdbc.password}"/>
    <!-- 最大连接数量,通常设置为并发数量 。Default: 15-->
    <property name="maxPoolSize" value="400"/>
    <!-- 连接池中保留的最小连接数,空闲连接处于待命状态而不被清除 。 -->
    <property name="minPoolSize" value="5" />
    <!--初始化时获取的连接数,取值应在minPoolSize与maxPoolSize之间。Default: 3 -->    
    <property name="initialPoolSize" value="10"/>
    <!--最大空闲时间,60秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 -->    
    <property name="maxIdleTime" value="60" />
    <!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 -->    
    <property name="acquireIncrement" value="5"/>
    <!--每60秒检查所有连接池中的空闲连接。Default: 0 -->    
    <property name="idleConnectionTestPeriod" value="60"/>
    <!--定义在从数据库获取新连接失败后重复尝试的次数。Default: 30 -->    
    <property name="acquireRetryAttempts" value="30"/>
     <!--获取连接失败将会引起所有等待连接池来获取连接的线程抛出异常。但是数据源仍有效    
          保留,并在下次调用getConnection()的时候继续尝试获取连接。如果设为true,那么在尝试    
          获取连接失败后该数据源将申明已断开并永久关闭。Default: false-->    
    <property name="breakAfterAcquireFailure" value="false"/>
</bean>

<!-- sqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <!-- 加载mybatis的配置文件 -->
    <property name="configLocation" value="classpath:MyBatis/sqlMapConfig.xml"/>
    <!-- 数据源 -->
    <property name="dataSource" ref="dataSource"/>
</bean>

<!-- mapper批量扫描,从Mapper包中扫描出mapper接口,自动创建代理对象,并且在spring容器中注册。
    规范遵循:将mapper.java和mapper.xml映射文件名称保持一致,且在一个目录中。
    自动扫描出来的mapper的bean的id为mapper类名(首字母小写)
 -->
 <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <!-- 指定扫描的包名
        如果扫描多个包,用这几个符号都可以分隔开",; \t\n"
     -->
     <property name="basePackage" value="cn.domarvel.dao"/>
     <!-- 不能用sqlSessionFactory,否则我们的<context:property-placeholder就不管用,最终导致数据库连不上。 -->
     <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
 </bean>

</beans>
db.properties文件内容如下:
jdbc.username=root
jdbc.password=
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?&useServerPrepStmts=true&cachePrepStmts=true
配置事务(applicationContext-tx.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"
    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-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 
        http://www.springframework.org/schema/aop 
        http://www.springframework.org/schema/aop/spring-aop-3.2.xsd 
        http://www.springframework.org/schema/tx 
        http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">
        <!-- 第一步 配置事务管理器 -->
    <bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- 注入dataSource -->
        <!-- 这里不注入dataSource,别人怎么帮你增强啊 -->
        <property name="dataSource" ref="dataSource"></property>
    </bean>

        <!-- 第二步 配置事务增强 -->
    <tx:advice id="txadvice" transaction-manager="dataSourceTransactionManager">
        <!-- 做事务操作 -->
        <tx:attributes>
            <!-- 设置进行事务操作的方法匹配规则 以及事务传播级别-->
            <tx:method name="insert*" propagation="REQUIRED"/>
            <tx:method name="delete*" propagation="REQUIRED"/>
            <tx:method name="update*" propagation="REQUIRED"/>
            <tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
            <tx:method name="select*" propagation="SUPPORTS" read-only="true"/>
            <!-- 这里的propagation属性值如果是REQUIRED就可以不用写,因为默认就是REQUIRED -->
            <!-- name属性值可以用*号来匹配方法,匹配的方法是切入点里面的方法。当然如果你只想匹配某一个切入点里面的方法,你可以就直接写方法名 -->
            <!-- 大家应该知道我们在配置切面的时候已经配置了要对哪儿些方法进行事务操作,execution(* cn.domarvel.service.MoneyService.*(..)) -->
            <!-- 为什么在method name="transfer*"这里还要进行切入点的方法选择呢?? -->
            <!-- 因为这里可以对方法进行优化,比如: -->
            <!--
                <tx:method name="*" propagation="REQUIRED" rollback-for="java.lang.Exception" isolation="DEFAULT" />
                <tx:method name="get*" read-only="true" />
                            这两种配置对于执行速度是不一样的。
                            第二种很明显速度是很快的。read-only对表是没有加锁的。
             -->
        </tx:attributes>
    </tx:advice>
    <!-- 第三步 配置切面 -->
    <aop:config>
        <!-- 切入点 -->
        <aop:pointcut expression="execution(* cn.domarvel.service.impl.*.*(..))" id="pointcut1"/>
        <!-- 切面 -->
        <aop:advisor advice-ref="txadvice" pointcut-ref="pointcut1"/>
    </aop:config>
</beans>
applicationContext.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"
    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-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 
        http://www.springframework.org/schema/aop 
        http://www.springframework.org/schema/aop/spring-aop-3.2.xsd 
        http://www.springframework.org/schema/tx 
        http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">
<!--
     注解映射器
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"></bean>
    注解适配器
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"></bean>
 -->

<!-- 使用 mvc:annotation-driven 代替上边注解映射器和注解适配器配置
    mvc:annotation-driven 默认加载很多的参数绑定方法,
    比如json转换解析器就默认加载了,如果使用 mvc:annotation-driven不用配置上边的RequestMappingHandlerMapping和RequestMappingHandlerAdapter
    实际开发时使用 mvc:annotation-driven
-->
<mvc:annotation-driven></mvc:annotation-driven>

<!-- 扫描controller,service,component等注解,多个包中间使用半角逗号分隔 -->
<context:component-scan base-package="cn.domarvel.web.controller,cn.domarvel.service.impl"/>

<!-- 视图解析器就用默认的 -->


</beans>
log4j.properties
### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.err
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

### direct messages to file mylog.log ###
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=c:\mylog.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

### set log levels - for more verbose logging change 'info' to 'debug' ###

log4j.rootLogger=info, stdout

最后就是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_3_1.xsd"
         version="3.1">
    <!-- SpringMVC前端控制器 -->
    <servlet>
        <servlet-name>SpringMVC</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!-- contextConfigLocation配置SpringMVC加载的配置文件(配置处理器映射器、适配器等等)
            如果不配置contextConfigLocation,默认加载的是/WEB-INF/servlet名称-servlet.xml(SpringMVC-servlet.xml)
        -->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:Spring/applicationContext*.xml</param-value>
        </init-param>
        <!-- 配置servlet创建的优先级 -->
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>SpringMVC</servlet-name>
        <!--
            第一种:*.action,访问以.action结尾由DispatcherServlet进行解析
            第二种:/,所以访问的地址由DispatcherServlet进行解析,对于静态文件的解析需要配置不让DispatcherServlet进行解析,对于静态文件的解析需要配置,不让DispatcherServlet进行解析。
            使用此种方式可以实现 RESTful 风格的url 。
            第三种:/*,这样配置不对,使用这种配置,最终要转发到一个jsp页面时,仍然会由DispatcherServlet解析jsp地址,不能根据jsp页面找到Handler,会报错。
        -->
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <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>
</web-app>

好了,基本配置就完成了,可以尝试运行了。

SSM整合项目代码下载

整合完毕后你可能会疑惑,为什么我只加载了SpringMVC的配置文件,而没有加载Spirng的配置文件就能够运行整个项目,成功进行bean的管理。请查看这篇博客帮你答疑!!!

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值