SSM整合

转自:http://www.cnblogs.com/HigginCui/p/5859788.html

【SSM的系统架构】


【整合概述】

第一步:

  MyBatis和Spring整合,通过Spring管理mapper接口。

  使用mapper的扫描器自动扫描mapper接口在Spring中进行注册。

第二步:

  通过Spring管理Service接口。

  使用配置方式将Service接口配置在Spring配置文件中。

  实现事务控制。

      在spring的配置文件中必须配置:

<!-- spring管理:自动搜索注解路径 在xml配置了这个标签后,spring可以自动去扫描base-pack下面或者子包下面的Java文件,如果扫描到有@Component @Controller@Service等这些注解的类,则把这些类注册为bean-->  
    <context:component-scan base-package="com.loan"></context:component-scan> 

第三步:

  由于SpringMVC是Spring的模块,无需整合这两个。

 

【工程截图】


【数据库的items】

[ 表结构 ]


 

[ 表内数据 ]


 

【1.整合dao】
将Mybatis和Spring进行整合

【1.1 sqlMapConfig.xml】MyBatis的配置文件

<?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的时候 只有 settings typeAliases mapper 三个属性有用, 其余的要在spring总配置文件中会覆盖 -->
    <settings>
        <!-- 全局映射器,是否启用缓存 -->
        <setting name="cacheEnabled" value="true" />
        <!-- 查询时,关闭关联对象即时加载以提高性能 -->
        <!-- 设置关联对象加载的形态,此处为按需加载字段(加载字段由SQL指 定),不会加载关联表的所有字段,以提高性能 -->
        <setting name="aggressiveLazyLoading" value="false" />
        <!-- 对于未知的SQL查询,允许返回不同的结果集以达到通用的效果 -->
        <setting name="multipleResultSetsEnabled" value="true" />
        <!-- 允许使用列标签代替列名 -->
        <setting name="useColumnLabel" value="true" />
        <!-- 允许使用自定义的主键值(比如由程序生成的UUID 32位编码作为键值),数据表的PK生成策略将被覆盖 -->
        <setting name="useGeneratedKeys" value="true" />
        <!-- 给予被嵌套的resultMap以字段-属性的映射支持 -->
        <setting name="autoMappingBehavior" value="FULL" />
        <!-- 对于批量更新操作缓存SQL以提高性能 -->
<!--         <setting name="defaultExecutorType" value="BATCH" /> -->
        <!-- 数据库超过25000秒仍未响应则超时 -->
        <setting name="defaultStatementTimeout" value="25000" />
    </settings>
</configuration>


【1.2 db.properties】数据库配置文件

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis
jdbc.username=root
jdbc.password=

【1.3 applicationContext-dao.xml】

需要配置:数据源、SqlSessionFactory、mapper扫描器

复制代码
<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 ">

    <!-- 加载db.properties文件中的内容,db.properties文件中key命名要有一定的特殊规则 -->
    <context:property-placeholder location="classpath:db.properties"/>

    <!-- 配置数据源,dbcp -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">
        <property name="driverClassName" value="${jdbc.driver}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
        <property name="maxActive" value="30"/>
        <property name="maxIdle" value="5"/>
    </bean>

    <!-- sqlSessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 数据库连接池 -->
        <property name="dataSource" ref="dataSource" />
        <!-- 加载mybatis的全局配置文件 -->
        <property name="configLocation" value="classpath:mybatis/sqlMapConfig.xml" />
    </bean>
    
    <!-- mapper扫描器 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 扫描包路径,如果需要扫描多个包,中间使用半角逗号隔开 -->
        <property name="basePackage" value="cn.Higgin.ssm.mapper"></property>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
    </bean>
    
</beans>
复制代码

【1.4 逆向工程生成PO类以及mapper】(对应表的增删改查)


【1.5 手动定义商品查询mapper】

针对综合查询mapper,一般情况下会有关联查询,建议 自定义 mapper。

【1.5.1 ItemsMapperCustom.java】

复制代码
package cn.Higgin.ssm.po;

/**
 *  商品信息的扩展
 */
public class ItemsCustom extends Items {
    
    //添加商品信息扩展的属性

}
复制代码

【1.5.2 ItemsMapperCustom.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.Higgin.ssm.mapper.ItemsMapperCustom" >

   <!-- 定义商品查询的sql片段,就是商品查询条件 -->
   <sql id="query_items_where">
       <!-- 使用动态sql,通过if判断,满足条件进行sql拼接 -->
       <!-- 商品查询条件通过ItemsQueryVo包装对象 中itemsCustom属性传递 -->
           <if test="itemsCustom!=null">
               <if test="itemsCustom.name!=null and itemsCustom.name!=''">
                   items.name LIKE '%${itemsCustom.name}%'
               </if>
           </if>
   </sql>
      
      <!-- 商品列表查询 -->
      <!-- parameterType:传入包装对象(包装了查询条件)
          resultType:建议使用扩展对象
       -->
      <select id="findItemsList" parameterType="cn.Higgin.ssm.po.ItemsQueryVo"
           resultType="cn.Higgin.ssm.po.ItemsCustom">
          SELECT items.* FROM items  
          <where>
              <include refid="query_items_where"></include>
          </where>
      </select>
      
</mapper>
复制代码

 

【2.整合service】

让spring来管理service接口。

【2.1 ItemsService.java】定义service接口

复制代码
package cn.Higgin.ssm.service;

import java.util.List;

import cn.Higgin.ssm.po.ItemsCustom;
import cn.Higgin.ssm.po.ItemsQueryVo;

public interface ItemsService {
    /**
     * 通过ItemsMapperCustomer查询数据库 
     */
    public List<ItemsCustom> findItemsList(ItemsQueryVo itemsQueryVo)throws Exception;
}
复制代码

【2.2 ItemsServiceImpl.java】service实现接口

复制代码
package cn.Higgin.ssm.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import cn.Higgin.ssm.mapper.ItemsMapperCustom;
import cn.Higgin.ssm.po.ItemsCustom;
import cn.Higgin.ssm.po.ItemsQueryVo;
import cn.Higgin.ssm.service.ItemsService;

public class ItemsServiceImpl implements ItemsService{

    @Autowired
    private ItemsMapperCustom itemsMapperCustom;
    
    //通过ItemsMapperCustom查询数据库
    public List<ItemsCustom> findItemsList(ItemsQueryVo itemsQueryVo) throws Exception {
        return itemsMapperCustom.findItemsList(itemsQueryVo);
    }
}
复制代码

【2.3 applicationContext-service.xml】

在spring容器中配置service

复制代码
<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 ">
    
    <!-- 定义商品管理的service -->
    <bean id="itemService" class="cn.Higgin.ssm.service.impl.ItemsServiceImpl" />
</beans>
复制代码

【2.4 applicationContext-transaction.xml】事务控制

在applicationContext-transaction.xml中使用spring声明 事务控制方法。

复制代码
<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 ">

    <!-- 事务管理器
        对mybatis操作数据库进行事务控制,spring使用jdbc的事务控制类 -->    
    <bean id="transactionManager" 
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- 数据源
            dataSource在applicationContext-dao.xml中已经配置
         -->
         <property name="dataSource" ref="dataSource" />
    </bean>
    <!-- 通知 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <!-- 传播行为 -->
            <tx:method name="save*" propagation="REQUIRED"/>
            <tx:method name="delete*" propagation="REQUIRED"/>
            <tx:method name="insert*" propagation="REQUIRED"/>
            <tx:method name="update*" propagation="REQUIRED"/>
            <tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
            <tx:method name="get*" propagation="SUPPORTS" read-only="true"/>
            <tx:method name="select*" propagation="SUPPORTS" read-only="true"/>
        </tx:attributes>
    </tx:advice>
    
    <!-- aop -->
    <aop:config>
    <aop:advisor advice-ref="txAdvice" pointcut="execution(* cn.Higgin.ssm.service.impl.*.*(..))"/>
</aop:config>
</beans>
复制代码

 

【3.整合springmvc】

【3.1 springmvc.xml】

在springmvc中配置 处理映射器、适配器、视图解析器

复制代码
<?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: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 ">

    <!-- 可以扫描controller、service、...
    这里让扫描controller,指定controller的包
     -->
    <context:component-scan base-package="cn.Higgin.ssm.controller"></context:component-scan>
    
        
    <!-- 使用 mvc:annotation-driven代替注解映射器和注解适配器配置
    mvc:annotation-driven默认加载很多的参数绑定方法,
    比如json转换解析器就默认加载了,如果使用mvc:annotation-driven不用配置上边的RequestMappingHandlerMapping和RequestMappingHandlerAdapter
    实际开发时使用mvc:annotation-driven
     -->
    <mvc:annotation-driven ></mvc:annotation-driven>
    

    <!-- 视图解析器
    解析jsp解析,默认使用jstl标签,classpath下的得有jstl的包
     -->
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- 配置jsp路径的前缀 -->
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <!-- 配置jsp路径的后缀 -->
        <property name="suffix" value=".jsp"/>
    </bean>
    
</beans>
复制代码

【3.2 在web.xml中】 在web.xml中配置前端控制器的代码

复制代码
  <!-- springMVC前端控制器 -->
  <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/springmvc.xml</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>*.action</url-pattern>
  </servlet-mapping>
复制代码

【3.3 ItemsController.java】

编写Controller(即Handler)

复制代码
package cn.Higgin.ssm.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import cn.Higgin.ssm.po.ItemsCustom;
import cn.Higgin.ssm.service.ItemsService;

@Controller
public class ItemsController {
    
    @Autowired
    private ItemsService itemsService;
    
    //商品查询
    @RequestMapping("/queryItems")
     public ModelAndView queryItems() throws Exception{
       //调用Service查找数据库,查询商品列表,这里使用静态数据模拟
       List<ItemsCustom> itemsList=itemsService.findItemsList(null);
      
       //返回ModelAndView
       ModelAndView modelAndView=new ModelAndView();
       //相当于request的setAttribute,在jsp页面中通过itemList来获取
       modelAndView.addObject("itemsList",itemsList);
       //指定视图
       modelAndView.setViewName("items/itemsList");
       System.out.println("注解方式:ItemsComtroller......");
       return modelAndView;
   }
}
复制代码

【4.前端jsp页面 itemsList.jsp】


 

位置:WEB-INF/jsp/items/itemsList.jsp

复制代码
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt"  prefix="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>查询商品列表</title>
</head>
<body> 
<form action="${pageContext.request.contextPath }/item/queryItem.action" method="post">
查询条件:
<table width="100%" border=1>
<tr>
<td><input type="submit" value="查询"/></td>
</tr>
</table>
商品列表:
<table width="100%" border=1>
<tr>
    <td>商品名称</td>
    <td>商品价格</td>
    <td>生产日期</td>
    <td>商品描述</td>
    <td>操作</td>
</tr>
<c:forEach items="${itemsList }" var="item">
<tr>
    <td>${item.name }</td>
    <td>${item.price }</td>
    <td><fmt:formatDate value="${item.createtime}" pattern="yyyy-MM-dd HH:mm:ss"/></td>
    <td>${item.detail }</td>
    
    <td><a href="${pageContext.request.contextPath }/item/editItem.action?id=${item.id}">修改</a></td>

</tr>
</c:forEach>
</table>
</form>
</body>
</html>
复制代码

 

【5. 加载spring容器】

将mapper、service、controller都加载到spring容器中。


建议使用通配符加载上边的配置文件。

在web.xml中,添加Spring容器监听器,加载spring容器

【web.xml完整】

复制代码
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>Spring_SpringMVC_MyBatis</display-name>
   
  <!-- 加载spring容器 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/classes/spring/applicationContext-*.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener> 
   
   
   <!-- springMVC前端控制器 -->
  <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/springmvc.xml</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>*.action</url-pattern>
  </servlet-mapping>
  
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>
复制代码

 

【日志打印 log4j.properties】

# Global logging configuration\uff0c\u5efa\u8bae\u5f00\u53d1\u73af\u5883\u4e2d\u8981\u7528debug
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

 

【运行结果】


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值