spring-spring mvc -mybatis 整合基礎步驟(idea 下)

環境搭建與配置

  1. 創建項目
  2. 導入相關的pom依賴
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.halloheihei.ssmdemo2</groupId>
    <artifactId>ssmdemo2</artifactId>
    <version>1.0-SNAPSHOT</version>
    <properties>
        <spring.version>5.0.2.RELEASE</spring.version>
        <slf4j.version>1.6.6</slf4j.version>
        <log4j.version>1.2.12</log4j.version>
        <mysql.version>5.1.6</mysql.version>
        <mybatis.version>3.4.5</mybatis.version>
    </properties>
    <dependencies>
        <!-- spring -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.6.8</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.version}</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency> <!-- log start -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>${log4j.version}</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${slf4j.version}</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>${slf4j.version}</version>
        </dependency> <!-- log end -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>${mybatis.version}</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.0</version>
        </dependency>
        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1.2</version>
            <type>jar</type>
            <scope>compile</scope>
        </dependency>
    </dependencies>
    <build>
        <finalName>ssm</finalName>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.2</version>
                    <configuration>
                        <source>1.8</source>
                        <target>1.8</target>
                        <encoding>UTF-8</encoding>
                        <showWarnings>true</showWarnings>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>


</project>

3. 創建基本結構和配置框架

  • com.hallheihei.pojo 或者 com.halloheihei.domain
  • com.halloheihei.dao
  • com.halloheihei.service
  • com.halloheihei.controlller
  • 在resources中創建 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:context="http://www.springframework.org/schema/context"
           xmlns:aop="http://www.springframework.org/schema/aop"
           xmlns:tx="http://www.springframework.org/schema/tx"
           xmlns:mvc="http://www.springframework.org/schema/mvc"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
    			    http://www.springframework.org/schema/beans/spring-beans.xsd
    			    http://www.springframework.org/schema/context
    			    http://www.springframework.org/schema/context/spring-context.xsd
    			    http://www.springframework.org/schema/aop
    			    http://www.springframework.org/schema/aop/spring-aop.xsd
    			    http://www.springframework.org/schema/tx
    			    http://www.springframework.org/schema/tx/spring-tx.xsd
    			    http://www.springframework.org/schema/mvc
    			    http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    </beans>

     

1 dao層整合

  1. 編寫pojo類 類名Books
    package com.halloheihei.domain;
    
    /**
     * @author halloheihei
     * @create 2019-11-01 13:36
     */
    public class Books {
    
        private int bookID;
        private String bookName;
        private String detail;
        private int bookCounts;
    
    
        public int getBookID() {
            return bookID;
        }
    
        public void setBookID(int bookID) {
            this.bookID = bookID;
        }
    
        public String getBookName() {
            return bookName;
        }
    
        public void setBookName(String bookName) {
            this.bookName = bookName;
        }
    
        public String getDetail() {
            return detail;
        }
    
        public void setDetail(String detail) {
            this.detail = detail;
        }
    
        public int getBookCounts() {
            return bookCounts;
        }
    
        public void setBookCounts(int bookCounts) {
            this.bookCounts = bookCounts;
        }
    }
    

     

  2. 編寫dao 接口,以讓mybatis-mapper.xml實現
    package com.halloheihei.dao;
    
    import com.halloheihei.domain.Books;
    
    import java.util.List;
    
    /**
     * @author halloheihei
     * @create 2019-11-01 13:35
     */
    public interface BookDao {
    
        //增加一個Book
        int addBook(Books books);
    
        //根據id刪除一個Book
        int deleteBookById(int id);
    
        //更新Book
        int updateBook(Books books);
    
        //根據id查詢,返回一個Book
        Books queryBookById(int id);
    
        //查詢全部Book,返回list集合
        List<Books> queryAllBook();
    }
    

     

  3. 編寫map.xml文件  文件名與dao的接口文件名一直,並且放入resources中,文件目錄需要與dao中接口目錄一致 Bookdao.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="com.halloheihei.dao.BookDao">
    
        <!--增加一個Book-->
        <insert id="addBook" parameterType="Books">
            insert into test.books(bookName,bookCounts,detail)
            values (#{bookName}, #{bookCounts}, #{detail})
        </insert>
    
        <!--根據id刪除一個Book-->
        <delete id="deleteBookById" parameterType="int">
            delete from test.books where bookID=#{bookID}
        </delete>
    
        <!--更新Book-->
        <update id="updateBook" parameterType="Books">
            update test.books
            set bookName = #{bookName},bookCounts = #{bookCounts},detail = #{detail}
            where bookID = #{bookID}
        </update>
    
        <!--根據id查詢,返回一個Book-->
        <select id="queryBookById" resultType="Books">
            select * from test.books
            where bookID = #{bookID}
        </select>
    
        <!--查詢全部Book-->
        <select id="queryAllBook" resultType="Books">
            SELECT * from test.books
        </select>
    
    </mapper>

     

  4. 在applicationContext.xml中添加
    <!--dao層配置開始-->
        <!--mybatis 數據庫連接池配置-->
        <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
            <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
            <property name="url" value="jdbc:mysql://localhost:3306/test"/>
            <property name="username" value="root"/>
            <property name="password" value="123456"/>
        </bean>
    
    
        <!--mapper配置-->
        <!--spring 管理 sqlSessionFactory ,使用mybatis 和 spring整合的包-->
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <!--數據庫連接池-->
            <property name="dataSource" ref="dataSource"/>
    
            <!--實體類別名-->
            <property name="typeAliasesPackage" value="com.halloheihei.domain"/>
        </bean>
    
        <!--mapper 掃描器 用來生產代理對象-->
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <property name="basePackage" value="com.halloheihei.dao"/>
        </bean>
        <!--dao層配置結束-->
  5. 測試
     @Test
        public void testFind() {
    
            ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
    
            BookDao bookDao = applicationContext.getBean(BookDao.class);
            Books books = bookDao.queryBookById(3);
            System.out.println(books.getBookName());
        }
    

     

2 service層整合

  1. 編寫service接口
    package com.halloheihei.service;
    
    import com.halloheihei.domain.Books;
    
    import java.util.List;
    
    /**
     * @author halloheihei
     * @create 2019-11-01 14:20
     */
    public interface BooksService {
        //增加一個Book
        int addBook(Books books);
    
        //根據id刪除一個Book
        int deleteBookById(int id);
    
        //更新Book
        int updateBook(Books books);
    
        //根據id查詢,返回一個Book
        Books queryBookById(int id);
    
        //查詢全部Book,返回list集合
        List<Books> queryAllBook();
    }
    

     

  2. 編寫service接口實現類
    package com.halloheihei.service.impl;
    
    import com.halloheihei.dao.BookDao;
    import com.halloheihei.domain.Books;
    import com.halloheihei.service.BooksService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    import java.util.List;
    
    /**
     * @author halloheihei
     * @create 2019-11-01 14:21
     */
    @Service
    public class BooksServiceImpl implements BooksService {
    
        @Autowired
        private BookDao bookDao;
    
        public int addBook(Books books) {
            return 0;
        }
    
        public int deleteBookById(int id) {
            return 0;
        }
    
        public int updateBook(Books books) {
            return 0;
        }
    
        public Books queryBookById(int id) {
            return bookDao.queryBookById(2);
        }
    
        public List<Books> queryAllBook() {
            return null;
        }
    }
    

     

  3. 配置applicationContext.xml
    <!--service 配置文件開始-->
        <context:component-scan base-package="com.halloheihei.service"/>
    
        <!--配置事務管理器-->
        <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
            <property name="dataSource" ref="dataSource"/>
        </bean>
    
        <!--&lt;!&ndash;配置事務通知&ndash;&gt;-->
        <tx:advice id="advice">
            <tx:attributes>
                <tx:method name="save*" propagation="REQUIRED"/>
                <tx:method name="update*" propagation="REQUIRED"/>
                <tx:method name="find*" propagation="REQUIRED"/>
                <tx:method name="delete*" propagation="REQUIRED"/>
                <tx:method name="*" propagation="REQUIRED"/>
            </tx:attributes>
        </tx:advice>
    
        <!--配置切面-->
        <aop:config>
            <aop:pointcut id="pointcut" expression="execution(* com.halloheihei.service.impl.*.*(..))"/>
            <aop:advisor advice-ref="advice" pointcut-ref="pointcut"/>
        </aop:config>
    
        <!--service 配置文件結束-->

     

  4. 測試
     @Test
        public void testServiceFind() {
    
            ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
    
            BooksService bookDao = applicationContext.getBean(BooksService.class);
            Books books = bookDao.queryBookById(3);
            System.out.println(books.getBookName());
        }

     

3 整合前端和controller

  1. 編寫控制器文件 BookController
    package com.halloheihei.controller;
    
    import com.halloheihei.domain.Books;
    import com.halloheihei.service.BooksService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    /**
     * @author halloheihei
     * @create 2019-11-01 14:47
     */
    @Controller
    @RequestMapping("/bb")
    public class BookController {
    
        @Autowired
        private BooksService booksService;
    
        @RequestMapping("/cc")
        public String find(Model model) {
    
            Books books = booksService.queryBookById(3);
            System.out.println(books.getBookName());
    
            System.out.println(books);
            model.addAttribute("book",books );
            return "hh";
        }
    }
    

     

  2. 編寫jsp輸出文件 show.jsp
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>修改信息</title>
    </head>
    <body>
    
    這裏的書本信息是 ${book.bookName}
    
    
    </body>
    </html>

     

  3. 配置applicationContext.xml
    <!--spring mvc 配置-->
        <!--處理器映射器,處理器適配器-->
        <mvc:annotation-driven/>
        <!--釋放靜態 資源-->
        <mvc:default-servlet-handler/>
        <!--組件掃描-->
        <context:component-scan base-package="com.halloheihei.controller"/>
        <!--視圖解析器-->
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix" value="/WEB-INF/jsp/"></property>
            <property name="suffix" value=".jsp"></property>
        </bean>

     

  4. 配置web.xml
    <?xml version="1.0" encoding="UTF-8"?>
    
    <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
             http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
             version="3.1">
    
    
        <welcome-file-list>
            <welcome-file>index.jsp</welcome-file>
        </welcome-file-list>
    
        <!--DispatcherServlet-->
        <servlet>
            <servlet-name>DispatcherServlet</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <init-param>
                <param-name>contextConfigLocation</param-name>
                <param-value>classpath:applicationContext.xml</param-value>
            </init-param>
            <load-on-startup>1</load-on-startup>
        </servlet>
        <servlet-mapping>
            <servlet-name>DispatcherServlet</servlet-name>
            <url-pattern>/</url-pattern>
        </servlet-mapping>
    
        <!-- 配置Spring的監聽器 -->
        <!--<listener>-->
            <!--<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>-->
        <!--</listener> &lt;!&ndash; 配置加載類路徑的配置文件 &ndash;&gt;-->
        <!--<context-param>-->
            <!--<param-name>contextConfigLocation</param-name>-->
            <!--<param-value>classpath:applicationContext.xml</param-value>-->
        <!--</context-param>-->
    
    
        <!--encodingFilter-->
        <filter>
            <filter-name>encodingFilter</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>encodingFilter</filter-name>
            <url-pattern>/</url-pattern>
        </filter-mapping>
    
        <!--Session過期時間-->
        <session-config>
            <session-timeout>15</session-timeout>
        </session-config>
    </web-app>

     

  5. 啓動服務器測試

項目目錄截圖展示:

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章