zoukankan      html  css  js  c++  java
  • SpringMVC框架二:SpringMVC与MyBatis整合

    下面整合SpringMVC和MyBatis框架,并做一个小案例

    创建数据库springmvc,并创建两张表,加入一些数据:

    两张表:商品表,用户表

    CREATE DATABASE springmvc;
    
    CREATE TABLE `items` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `name` varchar(32) NOT NULL COMMENT '商品名称',
      `price` float(10,1) NOT NULL COMMENT '商品定价',
      `detail` text COMMENT '商品描述',
      `pic` varchar(64) DEFAULT NULL COMMENT '商品图片',
      `createtime` datetime NOT NULL COMMENT '生产日期',
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
    
    INSERT INTO `items` VALUES ('1', '台式机', '3000.0', '该电脑质量非常好!!!!', null, '2016-02-03 13:22:53');
    INSERT INTO `items` VALUES ('2', '笔记本', '6000.0', '笔记本性能好,质量好!!!!!', null, '2015-02-09 13:22:57');
    INSERT INTO `items` VALUES ('3', '背包', '200.0', '名牌背包,容量大质量好!!!!', null, '2015-02-06 13:23:02');
    
    CREATE TABLE `user` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `username` varchar(32) NOT NULL COMMENT '用户名称',
      `birthday` date DEFAULT NULL COMMENT '生日',
      `sex` char(1) DEFAULT NULL COMMENT '性别',
      `address` varchar(256) DEFAULT NULL COMMENT '地址',
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=27 DEFAULT CHARSET=utf8;
    
    
    INSERT INTO `user` VALUES ('1', '王五', null, '2', null);
    INSERT INTO `user` VALUES ('10', '张三', '2014-07-10', '1', '北京市');
    INSERT INTO `user` VALUES ('16', '张小明', null, '1', '河南郑州');
    INSERT INTO `user` VALUES ('22', '陈小明', null, '1', '河南郑州');
    INSERT INTO `user` VALUES ('24', '张三丰', null, '1', '河南郑州');
    INSERT INTO `user` VALUES ('25', '陈小明', null, '1', '河南郑州');
    INSERT INTO `user` VALUES ('26', '王五', null, null, null);

    新建Dynamic Web Project:

    导包:

    先把简单的数据库配置完成:

    db.properties:

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

    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>
    
        <typeAliases>
            <package name="org.dreamtech.springmvc.pojo" />
        </typeAliases>
    
    </configuration>

    applicationContext.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>
    
        <bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="dataSource" ref="dataSource" />
            <property name="configLocation" value="classpath:sqlMapConfig.xml" />
        </bean>
    
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <property name="basePackage" value="org.dreamtech.mybatis.springmvc.dao" />
        </bean>
    
        <!-- 注解事务 -->
        <bean id="transactionManager"
            class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
            <property name="dataSource" ref="dataSource" />
        </bean>
    
        <!-- 开启注解 -->
        <tx:annotation-driven transaction-manager="transactionManager" />
    </beans>

    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>springmvc-mybatis</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>
    
        <context-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:applicationContext.xml</param-value>
        </context-param>
    
        <listener>
            <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
        </listener>
    
        <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:springmvc.xml</param-value>
            </init-param>
        </servlet>
    
        <servlet-mapping>
            <servlet-name>springmvc</servlet-name>
            <url-pattern>*.action</url-pattern>
        </servlet-mapping>
    </web-app>

    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">
    
        <context:component-scan base-package="org.dreamtech"/>
        <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>

    Controller:

    package org.dreamtech.springmvc.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 org.dreamtech.springmvc.pojo.Items;
    import org.dreamtech.springmvc.service.ItemService;
    
    /**
     * 商品管理
     */
    @Controller
    public class ItemController {
        
        @Autowired
        private ItemService itemService;
        @RequestMapping(value = "/item/itemlist.action")
        public ModelAndView itemList(){
            
            List<Items> list = itemService.selectItemsList();
            
            ModelAndView mav = new ModelAndView();
            mav.addObject("itemList", list);
            mav.setViewName("itemList");
            return mav;
        }
    
        
    }

    另外:RequestMapping注解的使用:

    限定Get或Post方法:

        @RequestMapping(value = "/deletes.action",method=RequestMethod.GET)
        public ModelAndView deletes(Integer[] ids) {
            
            ModelAndView mav = new ModelAndView();
            mav.setViewName("success");
            return mav;
        }

    如果要想两项都支持:

        @RequestMapping(value = "/deletes.action", method = { RequestMethod.GET, RequestMethod.POST })
        public ModelAndView deletes(Integer[] ids) {
    
            ModelAndView mav = new ModelAndView();
            mav.setViewName("success");
            return mav;
        }

    当然,如果不写的话:支持八大请求方式

    如果当前Controller之下的所有URL都是同一个目录下:

    可以将它提出,给当前类一个RequestMapping(value="/xxx")注解

    另外:RequestMapping的value是一个String[]类型,意味着可以多个URL交到一起处理

    至于Service层的接口和实现类,Dao层MyBatis的Mapper动态代理,POJO类,页面简单的JSP代码......

    这些与SpringMVC无关,于是省略了,现在启动项目

    访问:

    http://localhost:8080/springmvc-mybatis1/item/itemlist.action

    成功从数据库读出数据,完成了SpringMVC和MyBatis的整合

  • 相关阅读:
    怎么在一个线程结束后回到主线程?
    iOS KVC & KVO
    iOS添加到购物车的简单动画效果
    如何在键盘出现时滚动表格,以适应输入框的显示
    iOS开发之多媒体播放
    算法的时间复杂度(一)
    SPI通信
    三级管的原理
    stm32之595(spi芯片)
    stm32之Systick(系统时钟)
  • 原文地址:https://www.cnblogs.com/xuyiqing/p/9419144.html
Copyright © 2011-2022 走看看