SSM整合

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

【SSM的系统架构】

SSM整合_第1张图片

【整合概述】

第一步:

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

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

第二步:

  通过Spring管理Service接口。

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

  实现事务控制。

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

  
     

第三步:

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

 

【工程截图】

SSM整合_第2张图片

【数据库的items】

[ 表结构 ]

SSM整合_第3张图片

 

[ 表内数据 ]

SSM整合_第4张图片

 

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

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




    
    
        
        
        
        
        
        
        
        
        
        
        
        
        
        

        
        
    


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

    
    <context:property-placeholder location="classpath:db.properties"/>

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

    
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        
        <property name="dataSource" ref="dataSource" />
        
        <property name="configLocation" value="classpath:mybatis/sqlMapConfig.xml" />
    bean>
    
    
    <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】(对应表的增删改查)

SSM整合_第5张图片

【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 id="query_items_where">
       
       
           <if test="itemsCustom!=null">
               <if test="itemsCustom.name!=null and itemsCustom.name!=''">
                   items.name LIKE '%${itemsCustom.name}%'
               if>
           if>
   sql>
      
      
      
      <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 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 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 ">
    
    
    <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 ">

        
    <bean id="transactionManager" 
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        
         <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: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 ">

    
    <context:component-scan base-package="cn.Higgin.ssm.controller">context:component-scan>
    
        
    
    <mvc:annotation-driven >mvc:annotation-driven>
    

    
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        
        <property name="prefix" value="/WEB-INF/jsp/"/>
        
        <property name="suffix" value=".jsp"/>
    bean>
    
beans>
复制代码

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

复制代码
  
  <servlet>
    <servlet-name>springmvcservlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
    <init-param>
      <param-name>contextConfigLocationparam-name>
      <param-value>classpath:spring/springmvc.xmlparam-value>
    init-param>
  servlet>
  <servlet-mapping>
    <servlet-name>springmvcservlet-name>
    <url-pattern>*.actionurl-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 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】

SSM整合_第6张图片

 

位置: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_MyBatisdisplay-name>
   
  
    <context-param>
        <param-name>contextConfigLocationparam-name>
        <param-value>/WEB-INF/classes/spring/applicationContext-*.xmlparam-value>
    context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
    listener> 
   
   
   
  <servlet>
    <servlet-name>springmvcservlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
    <init-param>
      <param-name>contextConfigLocationparam-name>
      <param-value>classpath:spring/springmvc.xmlparam-value>
    init-param>
  servlet>
  <servlet-mapping>
    <servlet-name>springmvcservlet-name>
    <url-pattern>*.actionurl-pattern>
  servlet-mapping>
  
  <welcome-file-list>
    <welcome-file>index.jspwelcome-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

 

【运行结果】

SSM整合_第7张图片

你可能感兴趣的:(框架)