ssm整合

SSM整合笔记

整合Spring

  1. 编写xml配置文件,开启注解扫描(指定Controller注解不扫描)

     <!--开启注解扫描,只处理service和dao,controller不需要Spring框架处理-->
         <context:component-scan base-package="cn.itcast">
         <!--配置哪些不扫描-->
         <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
         </context:component-scan>
    
  2. 在业务层的实现类上编写Spring注解,如:

     @Service("accountService")
     public class AccountServiceImpl implements AccountService
    
  3. Spring整合完成,测试一下(非必须):

     @Test
         public void run1(){
             ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
             AccountService as = (AccountService) ac.getBean("accountService");
             as.findAll();
         }
    

整合SpringMVC

  1. 在web.xml中配置前端控制器和中文乱码过滤器

     <!--配置前端控制器-->
       <servlet>
         <servlet-name>dispatcherServlet</servlet-name>
         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
         <!--加载springmvc.xml配置文件-->
         <init-param>
           <param-name>contextConfigLocation</param-name>
           <param-value>classpath:springmvc.xml</param-value>
         </init-param>
    
         <!--启动服务器,创建servlet-->
         <load-on-startup>1</load-on-startup>
       </servlet>
       
       <servlet-mapping>
         <servlet-name>dispatcherServlet</servlet-name>
         <url-pattern>/</url-pattern>
       </servlet-mapping>
       
       <!--解决中文乱码的过滤器-->
       <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>
    
  2. 编写springmvc.xml配置文件,内容包括

     1. 开启注解扫描,只扫描Controller注解
     2. 配置视图解析器对象
     3. 过滤静态资源
     4. 开启SpringMVC注解的支持
    
     <!--开启注解扫描,只扫描Controller注解-->
     <context:component-scan base-package="cn.itcast">
         <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
     </context:component-scan>
     <!--配置视图解析器对象-->
     <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"/>
         <property name="suffix" value=".jsp"/>
     </bean>
     <!--过滤静态资源-->
     <mvc:resources mapping="/css/**" location="/css/"/>
     <mvc:resources mapping="/images/**" location="/images/"/>
     <mvc:resources mapping="/js/**" location="/js/"/>
     <!--开启SpringMVC注解的支持-->
     <mvc:annotation-driven/>
    
  3. 编写web层业务逻辑

     @Controller
     @RequestMapping("/account")
     public class AccountController {
    
         @RequestMapping("/findAll")
         public String findAll(){
             System.out.println("表现层:查询所有账户》。。");
             return "list";
         }
     }
     //在index.xml中跳转进行测试:<a href="account/findAll">测试</a>
    

Spring和SpringMVC两者的整合

》我们知道,在web.xml中前端控制器中加载了spingmvc.xml,但是spring的配置文件还没有加载
》所以,需要在web.xml中配置Spring监听器,去加载applicationContext.xml

  1. 在web.xml配置文件中配置Spring的监听器:

     <!--配置Spring的监听器,默认只加载WEB-INF目录下的applicationContext.xml配置文件,通过context-param配置正确的路径-->
     <listener>
     <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
     </listener>
     <context-param>
     <param-name>contextConfigLocation</param-name>
     <param-value>classpath:applicationContext.xml</param-value>
     </context-param>
    
  2. 在web层通过依赖注入,将service层对象注入:

     @Controller
     @RequestMapping("/account")
     public class AccountController {
    
         @Autowired
         private AccountService accountService;  //依赖注入
    
         @RequestMapping("/findAll")
         public String findAll(){
             System.out.println("表现层:查询所有账户》。。");
             //调用service层方法
             accountService.findAll();
             return "list";
         }
     }
    

mybatis

  1. 使用注解编写dao层接口的sql语句

     public interface AccountDao {
         //查询所有
         @Select("select * from account")
         List<Account> findAll();
         //保存账户信息
         @Insert("insert into account (name,money) values (#{name},#{money})")
         void saveAccount(Account account);
     }
    
  2. 编写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>
         <!--配置环境-->
         <environments default="mysql">
             <environment id="mysql">
                 <transactionManager type="JDBC"/>
                 <dataSource type="POOLED">
                     <property name="driver" value="com.mysql.jdbc.Driver"/>
                     <property name="url" value="jdbc:mysql://localhost:3306/ssm"/>
                     <property name="username" value="root"/>
                     <property name="password" value="root"/>
                 </dataSource>
             </environment>
         </environments>
         <!--引入映射配置文件,这里没有配置文件,使用dao类路径-->
         <mappers>
             <!--<mapper resource="xxx.xml"/> 资源配置文件-->
             <!--<mapper class="cn.itcast.dao.AccountDao"/> 单独指定某个类文件-->
             <!--使用package指定包名,包里所有的接口都会被扫描到-->
             <package name="cn.itcast.dao"/>
         </mappers>
     </configuration>
    
  3. 编写测试类(非必须)

     public class TestMybatis {
         @Test
         public void testMybatis() throws Exception {
             //加载配置文件
             InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
             //创建SqlSessionFactory对象
             SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
             //创建SqlSession对象
             SqlSession sqlSession = factory.openSession();
             //获取代理对象
             AccountDao dao = sqlSession.getMapper(AccountDao.class);
             //查询所有数据
             List<Account> list = dao.findAll();
             for (Account account : list) {
                 System.out.println(account);
             }
             //关闭资源
             sqlSession.close();
             in.close();
         }
     }
    

整合mybatis

思路:现在需要将获取到的代理对象,存入容器中,在service中获取到dao层的代理对象,调用dao层代理对象的方法,如何操作呢?
答案:在业务层service的配置文件applicationContext.xml中配置

  1. 编写applicationContext.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:aop="http://www.springframework.org/schema/aop"
            xmlns:tx="http://www.springframework.org/schema/tx"
            xmlns:context="http://www.springframework.org/schema/context"
            xsi:schemaLocation="http://www.springframework.org/schema/beans
             http://www.springframework.org/schema/beans/spring-beans.xsd
             http://www.springframework.org/schema/tx
             http://www.springframework.org/schema/tx/spring-tx.xsd
             http://www.springframework.org/schema/aop
             http://www.springframework.org/schema/aop/spring-aop.xsd
             http://www.springframework.org/schema/context
             http://www.springframework.org/schema/context/spring-context.xsd">
    
         <!--开启注解扫描,只处理service和dao,controller不需要Spring框架处理-->
         <context:component-scan base-package="cn.itcast">
             <!--配置哪些不扫描-->
             <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
         </context:component-scan>
    
    
         <!--整合mybatis框架-->
         <!--配置连接池-->
         <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
             <property name="driverClass" value="com.mysql.jdbc.Driver"/>
             <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/ssm"/>
             <property name="user" value="root"/>
             <property name="password" value="root"/>
         </bean>
         <!--配置SqlSessionFactory工厂-->
         <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
             <!--配置连接池-->
             <property name="dataSource" ref="dataSource"/>
         </bean>
         <!--配置AccountDao接口所在的包-->
         <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
             <property name="basePackage" value="cn.itcast.dao"/>
         </bean>
     </beans>
    
  2. 此时,之前编写的SqlMapConfig.xml就没有用处了,可以删掉

  3. 在service层注入dao代理对象

     @Service("accountService")
     public class AccountServiceImpl implements AccountService {
    
         @Autowired
         private AccountDao accountDao; //注入代理对象
    
         @Override
         public List<Account> findAll() {
             System.out.println("业务层:查询所有账户信息...");
             return accountDao.findAll();
         }
    
         @Override
         public void saveAccount(Account account) {
             System.out.println("业务层:保存账户");
             accountDao.saveAccount(account);
             //这里没有添加事务,并不会真的保存到数据库
         }
     }
    
  4. 整合完成,此时我们在web层可以将数据,转发到页面中去(通过Model)

     @Controller
     @RequestMapping("/account")
     public class AccountController {
    
         @Autowired
         private AccountService accountService;
    
         @RequestMapping("/findAll")
         public String findAll(Model model){
             System.out.println("表现层:查询所有账户》。。");
             //调用service层方法
             List<Account> list = accountService.findAll();
             model.addAttribute("list",list);
             return "list";
         }
     }
     
     //页面展示代码
     <%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
     <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
     <html>
     <head>
         <title>Title</title>
     </head>
     <body>
         <h3>查询所有账户...</h3>
         <%--${list}--%>
         <c:forEach items="${list}" var="account">
             ${account.name}
         </c:forEach>
     </body>
     </html>
    

整合mybatis框架-事务管理

  1. 在applicationContext.xml中配置事务管理

     <!--配置Spring框架声明式事务管理-->
     <!--1. 配置事务管理器-->
     <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
         <property name="dataSource" ref="dataSource"/>
     </bean>
     <!--2. 配置事务通知-->
     <tx:advice id="txAdvice" transaction-manager="transactionManager">
         <tx:attributes>
             <tx:method name="find*" read-only="true"/>
             <tx:method name="*" isolation="DEFAULT"/>
         </tx:attributes>
     </tx:advice>
     <!--3. 配置AOP增强-->
     <aop:config>
         <aop:advisor advice-ref="txAdvice" pointcut="execution(* cn.itcast.service.impl.*ServiceImpl.*(..))"/>
     </aop:config>
     
     
     //测试 前端页面
     <h3>测试保存(事务管理)</h3>
     <form action="account/saveAccount" method="post">
         姓名:<input type="text" name="name"/><br/>
         金额:<input type="text" name="money"/><br/>
         <input type="submit" value="保存"/><br/>
     </form>
     
     //web层
     @RequestMapping("/saveAccount")
     public void saveAccount(Account account, HttpServletRequest request, HttpServletResponse response) throws IOException {
         System.out.println("表现层:保存账户》。。");
         //调用service层方法
        accountService.saveAccount(account);
        response.sendRedirect(request.getContextPath()+"/account/findAll"); //重定向
         return;
     }
    
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,117评论 4 360
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,963评论 1 290
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 107,897评论 0 240
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,805评论 0 203
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,208评论 3 286
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,535评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,797评论 2 311
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,493评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,215评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,477评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,988评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,325评论 2 252
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,971评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,055评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,807评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,544评论 2 271
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,455评论 2 266

推荐阅读更多精彩内容

  • springmvc + spring + mybatis 配置整合 eclipse里创建一个web project...
    _NineSun旭_阅读 1,931评论 0 4
  • 对于java中的思考的方向,1必须要看前端的页面,对于前端的页面基本的逻辑,如果能理解最好,不理解也要知道几点。 ...
    神尤鲁道夫阅读 738评论 0 0
  • Mybatis与Spring的整合 1:引入spring与mybatis各自的jar包 2:引入spring与my...
    宋雨轩同学阅读 454评论 1 1
  • 部分内容转载自:HOW2J.CN 数据库准备 创建数据库/数据表 插入数据use how2java;insert ...
    zheng7阅读 466评论 0 0
  • ssm整合主要有3个配置文件,web.xml、springmvc.xml和applicationContext.x...
    PC_Repair阅读 228评论 0 0