zoukankan      html  css  js  c++  java
  • SSM整合1(springMVC+mybatis)

    整合目标:控制层采用springmvc、持久层使用mybatis实现

    整合思路:

    Dao层:

    1、SqlMapConfig.xml,空文件即可,但是需要文件头。

    2、applicationContext-dao.xml

    a)        数据库连接池

    b)        SqlSessionFactory对象,需要spring和mybatis整合包下的。

    c)        配置mapper文件扫描器。

     

    Service层:

    1、applicationContext-service.xml包扫描器,扫描@service注解的类。

    2、applicationContext-trans.xml配置事务。

     

    Controller层:

    1、Springmvc.xml

    a)        包扫描器,扫描@Controller注解的类。

    b)        配置注解驱动

    c)        配置视图解析器

     

    Web.xml文件:

    1、配置spring

    2、配置前端控制器。

     详细配置如下:

    一、SSM框架整合

          1.1、整合思路

            从底层整合起,也就是先整合mybatis与spring,然后在编写springmvc。

          1.2、开发需求

            查询商品列表(从数据库中查询)

          1.3、创建web工程

              

            现在ssm的工程创建就有区别于原先的dao、service、web这样的三层目录了,现在是mapper、service、controller这样的目录,mapper就相当于以前的dao、controller相当于以前的web,改变了名称而已。不要因此看不懂了。

          1.4、添加jar包

    导包

    • spring(包括springmvc)
    • mybatis
    • mybatis-spring整合包
    • 数据库驱动
    • 第三方连接池。

              

          1.5、开始整合mapper(mybatis与spring的整合)

            直接上代码。

            1.5.1、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>
    
        <!-- 取别名,或者别的其他全局配置信息,就在这里编写 -->(逆向工程不需要起别名)
        <typeAliases>
            <!-- 别名为类名首字母大小写都可以 -->
            <package name="com.wuhao.ms.domain"/>
        </typeAliases>
        <!-- 原先这里还有连接数据库的一些配置,与spring整合后,都交由spring来管理 -->
    
        <!-- 加载mapper映射文件,使用通用的配置 -->    
    <mappers>
        <package name="com.wuhao.ssm.mapper"/>
    </mappers>
    </configuration>

            1.5.2、applicationContext-dao.xml的配置

                   

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
        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-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd 
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.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="10" /> <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"> <!-- 配置Mapper扫描包 --> <property name="basePackage" value="cn.itcast.ssm.mapper" /> </bean> </beans>

              这里需要注意一点,在指定mybatis的全局配置文件的路径的时候,也就是在value="classpath:SqlMapConfig.xml"时,如果在创建的config的配置文件目录下还有层级目录,则这里需要加上,比如,config下面分为了mybatis和spring,那么这里就需要写value="classpath:mybatis/SqlMapConfig.xml",看根据你自己的需求来编写

                              

            1.5.3、db.properties配置

                

    jdbc.driver=com.mysql.jdbc.Driver
    jdbc.url=jdbc:mysql://localhost:3306/springmvc?characterEncoding=utf-8
    jdbc.username=root
    jdbc.password=root

            1.5.4、开发mapper,将逆向工程生成的添加进来

                

              注意:Mapper开发时,先要根据需求进行分析,是否匹配逆向工程生成的代码,如果匹配成功,则不需要再开发mapper;如果不匹配,再去扩展一个新的mapper接口和mapper映射文件来处理该需求,通俗点讲,就是逆向工程生成的mapper接口中的定义的功能是否满足我们开发的需求,因为逆向工程生成的都是对于单表进行操作的,而我们有时候需要的是更复杂的查询,所以如果有需要我们在自己创建mapper接口和mapper映射文件,其实就是扩展功能。

          1.6、整合service

            添加applicationContext-service.xml配置文件,用来处理事务,

            applicationContext-service.xml:如果不懂其中的代码的意思,就查看之前讲解spring管理事务的文章。这里直接复制粘帖即可,修改一些包名称等

              

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
        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-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd 
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.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="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="get*" propagation="SUPPORTS" read-only="true" /> <tx:method name="query*" propagation="SUPPORTS" read-only="true" /> </tx:attributes> </tx:advice> <!-- 切面 --> <aop:config> <aop:advisor advice-ref="txAdvice" pointcut="execution(* cn.itcast.ssm.service.*.*(..))" /> </aop:config> </beans>

          1.7、整合controller

            也就是使用springmvc了。非常简单。

            1.7.1、在web.xml中配置前端控制器DispatcherServlet

              

    <?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>springmvc-web</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>
    
        <!-- 配置spring -->
        <context-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring/applicationContext*.xml</param-value>
        </context-param>
    
        <!-- 使用监听器加载Spring配置文件 -->
        <listener>
            <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
        </listener>
    
        <!-- 配置SrpingMVC的前端控制器 -->
        <servlet>
            <servlet-name>springmvc-web</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-web</servlet-name>
            <!-- 配置所有以action结尾的请求进入SpringMVC -->
            <url-pattern>*.action</url-pattern>
        </servlet-mapping>
    
    </web-app>

            1.7.2、配置springmvc.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:p="http://www.springframework.org/schema/p"
        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-4.0.xsd
            http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
    
            
            
            <!-- 扫描@Controler  @Service   -->
            <context:component-scan base-package="com.itheima"/>
            
            <!-- 处理器映射器 -->
    <!--         <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/> -->
            <!-- 处理器适配器 -->
    <!--         <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/> -->
            <!-- 注解驱动 -->
            <mvc:annotation-driven conversion-service="conversionServiceFactoryBean"/>
            
            <!-- 配置Conveter转换器  转换工厂 (日期、去掉前后空格)。。 -->
            <bean id="conversionServiceFactoryBean" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
                <!-- 配置 多个转换器-->
                <property name="converters">
                    <list>
                        <bean class="com.itheima.springmvc.conversion.DateConveter"/>
                    </list>
                </property>
            </bean>
            
            <!-- 视图解释器 -->
            <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
                <property name="prefix" value="/WEB-INF/jsp/"/>
                <property name="suffix" value=".jsp"/>
            </bean>
            
       </beans>

          1.8、整合spring配置文件      

            就是将所有的spring的配置文件都进行加载启动。也就是在web.xml中配置spring的监听器

                  

          1.9、总结所有的配置如下图

                  

          1.10、部署测试

            1.10.1、查询商品列表(从数据库中查询) 

              1、编写service层 

                ItemsService 接口              

    package com.itheima.springmvc.service;
    
    import java.util.List;
    
    import com.itheima.springmvc.pojo.Items;
    
    public interface ItemService {
        
        //查询商品列表
        public List<Items> selectItemsList();
        
        public Items selectItemsById(Integer id);
        
        
        //修改
        public void updateItemsById(Items items);
    
    }

                ItemsServiceImpl 实现类 使用注解开发            

    package com.itheima.springmvc.service;
    
    import java.util.Date;
    import java.util.List;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    import com.itheima.springmvc.dao.ItemsMapper;
    import com.itheima.springmvc.pojo.Items;
    
    @Service
    public class ItemServiceImpl implements ItemService {
    
        @Autowired
        private ItemsMapper itemsMapper;
        
        //查询商品列表
        public List<Items> selectItemsList(){
            return itemsMapper.selectByExampleWithBLOBs(null);(检索字段中存在大字段类型,例如text字段类型)
        }
        public Items selectItemsById(Integer id){
            return itemsMapper.selectByPrimaryKey(id);
        }
        //修改
        public void updateItemsById(Items items){
            items.setCreatetime(new Date());
            itemsMapper.updateByPrimaryKeyWithBLOBs(items);
        }
    }                    

              2、编写controller层

               ItemsController

    package com.itheima.springmvc.controller;
    
    import java.util.ArrayList;
    import java.util.Date;
    import java.util.List;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.HttpRequestHandler;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.servlet.ModelAndView;
    
    import com.itheima.springmvc.pojo.Items;
    import com.itheima.springmvc.pojo.QueryVo;
    import com.itheima.springmvc.service.ItemService;
    
    @Controller
    public class ItemController {
    
        @Autowired
        private ItemService itemService;
        //入门程序 第一   包类 + 类包 + 方法名
        @RequestMapping(value = "/item/itemlist.action")
        public ModelAndView itemList(){
            //从Mysql中查询
            List<Items> list = itemService.selectItemsList();
            
            ModelAndView mav = new ModelAndView();
            //数据
            mav.addObject("itemList", list);
            mav.setViewName("itemList");
            return mav;
        }
        //去修改页面 入参 id
        @RequestMapping(value = "/itemEdit.action")
    //    public ModelAndView toEdit(@RequestParam(value = "id",required = false,defaultValue = "1") Integer idaaq,
        public ModelAndView toEdit(Integer id,
                HttpServletRequest request,HttpServletResponse response
                ,HttpSession session,Model model){
            
            //Servlet时代开发
    //        String id = request.getParameter("id");
            
            //查询一个商品
    //        Items items = itemService.selectItemsById(Integer.parseInt(id));
            Items items = itemService.selectItemsById(id);
            ModelAndView mav = new ModelAndView();
            //数据
            mav.addObject("item", items);
            mav.setViewName("editItem");
            return mav;
            
        }
        //提交修改页面 入参  为 Items对象  
        @RequestMapping(value = "/updateitem.action")
    //    public ModelAndView updateitem(Items items){
        public ModelAndView updateitem(QueryVo vo){
    
            //修改
            itemService.updateItemsById(vo.getItems());
            
            ModelAndView mav = new ModelAndView();
            mav.setViewName("success");
            return mav;
            
        }
        
    }

             3、添加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 }/editItems.do?id=${item.id}">修改</a></td>
    
    </tr>
    </c:forEach>
    
    </table>
    </form>
    </body>
    
    </html>
    

              4、测试http://localhost:8080/springmvc-mybatis/item/itemlist.action               

  • 相关阅读:
    pyhton锁机制,进程池
    Python脚本运行出现语法错误:IndentationError:unexpected indent
    进程线程之间如何通信
    进程基础整理
    paramido简单使用教程
    python多继承简单方法
    常用模块整理-时间模块
    如何使用临时文件
    如何折分字符串技巧讨论-总结
    python中dump与dumps的区别
  • 原文地址:https://www.cnblogs.com/lvoooop/p/10896952.html
Copyright © 2011-2022 走看看