ssm整合,我的案例

學習過程,B站一位老師的視屏:https://www.bilibili.com/video/av73118229php

博客網址:https://blog.kuangstudy.com/index.php/archives/487/css

我的項目打包:ssm_book  提取碼 : oum2html

我的整合思路

最好先保證每一個框架都能獨立運行,再去搞整合,這樣排錯比較容易。java

先展現一下結果mysql

1、先整合一下mybatis和spring

1.導包,一次性所有導完須要的包web

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <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>
            <!--aop相關的技術-->
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.6.8</version>
        </dependency>
        <dependency>
            <!--aop的jar包-->
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <!--spring的容器-->
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <!--web與webmvc是springmvc須要用的jar包-->
            <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>
            <!--jdbc模板技術-->
            <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>
            <!--mysql驅動包-->
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.version}</version>
        </dependency>
        <dependency>
            <!--servlet-->
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <!--jsp-->
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <!--想在頁面也el表達式須要用到的包-->
            <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>
            <!--mybatis-->
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>${mybatis.version}</version>
        </dependency>
        <dependency>
            <!--spring整合mybatis須要用到這個包-->
            <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>
      <!--maven資源過濾設置-->
      <resources>
          <resource>
              <directory>src/main/java</directory>
              <includes>
                  <include>**/*.properties</include>
                  <include>**/*.xml</include>
              </includes>
              <filtering>false</filtering>
          </resource>
          <resource>
              <directory>src/main/resources</directory>
              <includes>
                  <include>**/*.properties</include>
                  <include>**/*.xml</include>
              </includes>
              <filtering>false</filtering>
          </resource>
      </resources>
</build>

2.前期mysql準備spring

create database ssm;
use ssm;
create table books(
    bookid int primary key auto_increment not null comment '書id',
  bookName varchar(100) not null comment '書名',
    bookCounts int(11) not null comment '書數量',
    detail varchar(200) not null comment '書描述'
)engine = innodb default charset = utf8

insert into books(bookName,bookCounts,detail)
VALUES
('Java',2,'從入門到放棄'),
('MySql',2,'從刪庫到跑路'),
('Linux',2,'從進門到進牢');

3.實體類sql

public class Books {
private int bookID;
private String bookName;
private int bookCounts;
private String detail;
   getter,setter...
}

4.BooksMapper接口和映射文件BooksMapper.xml數據庫

BookMapper.java

public interface BooksMapper {
//查詢全部
List<Books> queryAllBook();
//根據id查詢
Books queryBookById(int id);
//添加
int addBook(Books book);
//修改
int updateBook(Books books);
//刪除
int deleteBook(int id);
//模糊查詢
List<Books> queryByName(String name);
}
BookMappaer.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.cong.dao.BooksMapper">
<select id="queryAllBook" resultType="books">
select * from ssm.books;
</select>
<select id="queryBookById" resultType="books" parameterType="int">
select * from ssm.books where bookid = #{id};
</select>
<insert id="addBook" parameterType="books">
insert into ssm.books(bookName, bookCounts, detail)
VALUES (#{bookName},#{bookCounts},#{detail});
</insert>
<update id="updateBook" parameterType="books">
update ssm.books
set bookName=#{bookName},bookCounts=#{bookCounts},detail=#{detail}
where bookid = #{bookID};
</update>
<delete id="deleteBook" parameterType="int">
delete from ssm.books where bookid = #{bookId}
</delete>
<select id="queryByName" resultType="books" parameterType="string">
select * from ssm.books where bookName like #{name};
</select>
</mapper>

5. mybatis核心配置文件mybatis-config.xmlbootstrap

<?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>
    <!--log4j-->
    <settings>
        <setting name="logImpl" value="LOG4J"/>
    </settings>
    <!--別名-->
    <typeAliases>
        <package name="com.cong.pojo"/>
    </typeAliases>
</configuration>

 6. db.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm?useSSL=true&useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=123456

7. 建立application.xml配置文件,這個主要就是將其它的配置import進來

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       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.xsd ">
    <import resource="spring-service.xml"/>
    <import resource="spring-dao.xml"/>
</beans>

8. 編寫spring與mybatis的配置文件spring-dao.xml整合dao層,這裏使用的數據源是c3p0

<?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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">
    <!--1.關聯數據庫文件-->
    <context:property-placeholder location="classpath:db.properties"/>
    <!--2.dataSource-->
    <bean id="datasource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}"/>
        <property name="jdbcUrl" value="${jdbc.url}"/>
        <property name="user" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>
    <!--3.SqlSessionFactory-->
    <bean class="org.mybatis.spring.SqlSessionFactoryBean" id="sqlSessionFactory">
        <property name="dataSource" ref="datasource"/>
        <!-- 綁定mybatis全局配置文件:mybatis-config.xml -->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
    </bean>
    <!-- 4.掃描Dao接口包,動態實現Dao接口注入到spring容器中 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.cong.dao"/>
    </bean>
</beans>

9. spring整合service層,spring-service.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">
    <!--將BooksServiceImpl注入到spring-->
    <bean class="com.cong.service.BooksServiceImpl" id="booksService">
        <property name="booksMapper" ref="booksMapper"/>
    </bean>
    <!--聲明式配置事務-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="datasource"/>
    </bean>
    <!--配置事務的通知,本項目不須要-->
</beans>

10. 到了這裏,spring整合mybatis就算成功了,先測試一下

測試類

public class SpringTest {
    @Test
    public void test1(){
        //加載配置文件
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        //獲取對象
        BooksService booksService = (BooksService) context.getBean("booksService");
        //執行方法
        List<Books> books = booksService.queryAllBook();
        for (Books book : books) {
            System.out.println(book.toString());
        }
    }
}

結果,能夠查詢

 3、整合springmvc

在這裏就不作mvc的測試了,

主要就是配置springmvc.xml和web.xml以後,簡單寫一個controller和一個簡單的jsp頁面配合index.jsp,

而後配置好tomcat服務器,啓動以後可以作到頁面跳轉就沒問題。

1.springmvc的配置文件spring-mvc.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: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/mvc
    https://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!-- 1.開啓SpringMVC註解驅動 -->
    <mvc:annotation-driven />
    <!-- 2.靜態資源默認servlet配置-->
    <mvc:default-servlet-handler/>
    <!-- 3.配置jsp 顯示ViewResolver視圖解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>
    <!-- 4.掃描controller -->
    <context:component-scan base-package="com.cong.controller" />
</beans>

2.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_4_0.xsd"
         version="4.0">
    <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>
    <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>
</web-app>

3.在application中導入全部的配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       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.xsd ">
    <!--導入其餘配置文件-->
    <import resource="spring-mvc.xml"/>
    <import resource="spring-dao.xml"/>
    <import resource="spring-service.xml"/>
</beans>

這裏囉嗦一下,在web.xml中,咱們配置了

<param-value>classpath:applicationContext.xml</param-value>

就是將配置文件中包含的全部東西註冊到tomcat服務器中,而在applicationContext.xml中引入了其餘的配置文件,因此就沒有問題

還有另一種引入的方法,就是在web.xml中配置。

通常來講,web.xml中應該默認配置的是springmvc的配置文件,也就是咱們案例中的spring-mvc.xml

而後將其它的配置文件好比spring的配置文件application.xml(有的人會將mybatis和spring整合到這裏面)經過監聽器註冊到tomcat服務器中

 <!-- 配置Spring的監聽器 -->
    <!--該監聽器默認狀況只能加載在web中配置了的配置文件,好比次案例中的applicationContext.xml-->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!-- 因此能夠設置額外的配置文件,好比 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring-mvc.xml</param-value>
    </context-param>

4. 編寫controller類BookController

@Controller
@RequestMapping("/book")
public class BookController {
    @Autowired
    @Qualifier("booksService")
    private BooksService booksService;
    //顯示全部書籍
    @RequestMapping("/allBook")
    public String listBooks(Model model){
        List<Books> booksList = booksService.queryAllBook();
        model.addAttribute("list", booksList);
        return "allBook";
    }
    //跳轉到添加書籍的頁面
    @RequestMapping("/toAddBook")
    public String toAddPaper() {
        return "addBook";
    }
    //修改完書籍重定向到全部書籍頁面
    @RequestMapping("/addBook")
    public String addPaper(Books books) {
        booksService.addBook(books);
        return "redirect:/book/allBook";
    }
    //跳轉到修改書籍頁面
    @RequestMapping("/toUpdateBook")
    public String toUpdateBook(Model model,int id) {
        Books books = booksService.queryBookById(id);
        model.addAttribute("book",books );
        return "updateBook";
    }
    //修改完書籍重定向到全部書籍頁面
    @RequestMapping("/updateBook")
    public String updateBook(Model model, Books book) {
        booksService.updateBook(book);
        return "redirect:/book/allBook";
    }
    //刪除書籍直接重定向到全部書籍頁面
    @RequestMapping("/del/{bookId}")
    public String deleteBook(@PathVariable("bookId") int id) {
        booksService.deleteBook(id);
        return "redirect:/book/allBook";
    }
    //根據名字模糊查找書籍,跳轉到顯示查詢列表頁面
    @RequestMapping("/findByKeyWord")
    public String findByName(Model model,String keyword){
        List<Books> list = booksService.queryByName("%"+keyword+"%");
        model.addAttribute("list", list);
        return "allBook";
    }
}

5.下面是jsp文件

5.1 index.jsp,只有一個超連接,點進去就是書籍頁面

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE HTML>
<html>
<head>
    <title>首頁</title>
    <style type="text/css">
        a {
            text-decoration: none;
            color: black;
            font-size: 18px;
        }
        h3 {
            width: 180px;
            height: 38px;
            margin: 100px auto;
            text-align: center;
            line-height: 38px;
            background: deepskyblue;
            border-radius: 4px;
        }
    </style>
</head>
<body>
<h3>
    <a href="${pageContext.request.contextPath}/book/allBook">點擊進入列表頁</a><br/><br/>
</h3>
</body>
</html>

5.2  書籍頁面allBook.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>書籍列表</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- 引入 Bootstrap -->
    <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>

<div class="container">

    <div class="row clearfix">
        <div class="col-md-12 column">
            <div class="page-header">
                <h1>
                    <small>書籍列表 —— 顯示全部書籍</small>
                </h1>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-md-4 column">
            <a class="btn btn-primary" href="${pageContext.request.contextPath}/book/toAddBook">新增</a>
            <a class="btn btn-primary" href="${pageContext.request.contextPath}/book/allBook">返回列表</a>
        </div>
        <div class="col-md-4 column">
            <form action="/book/findByKeyWord" method="post" class="form-inline">
                <input type="text" name="keyword" placeholder="請輸入查詢的書籍名稱" class="form-control">
                <input type="submit" value="查詢" class="btn btn-primary" />
            </form>
        </div>
    </div>

    <div class="row clearfix">
        <div class="col-md-12 column">
            <table class="table table-hover table-striped">
                <thead>
                <tr>
                    <%--<th>書籍編號</th>--%>
                    <th>書籍名字</th>
                    <th>書籍數量</th>
                    <th>書籍詳情</th>
                    <th>操做</th>
                </tr>
                </thead>

                <tbody>
                <c:forEach var="book" items="${requestScope.get('list')}">
                    <tr>
                        <%--<td>${book.getBookID()}</td>--%>
                        <td>${book.getBookName()}</td>
                        <td>${book.getBookCounts()}</td>
                        <td>${book.getDetail()}</td>
                        <td>
                            <a href="${pageContext.request.contextPath}/book/toUpdateBook?id=${book.getBookID()}">更改</a> |
                            <a href="${pageContext.request.contextPath}/book/del/${book.getBookID()}">刪除</a>
                        </td>
                    </tr>
                </c:forEach>
                </tbody>
            </table>
        </div>
    </div>
</div>
</body>
</html>

5.3 addBook.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<html>
<head>
    <title>新增書籍</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- 引入 Bootstrap -->
    <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">

    <div class="row clearfix">
        <div class="col-md-12 column">
            <div class="page-header">
                <h1>
                    <small>新增書籍</small>
                </h1>
            </div>
        </div>
    </div>
    <form action="${pageContext.request.contextPath}/book/addBook" method="post">
        書籍名稱:<input type="text" name="bookName"><br><br><br>
        書籍數量:<input type="text" name="bookCounts"><br><br><br>
        書籍詳情:<input type="text" name="detail"><br><br><br>
        <input type="submit" value="添加">
    </form>
</div>
</body>
</html>

5.4 updateBook.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>修改信息</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- 引入 Bootstrap -->
    <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">

    <div class="row clearfix">
        <div class="col-md-12 column">
            <div class="page-header">
                <h1>
                    <small>修改信息</small>
                </h1>
            </div>
        </div>
    </div>

    <form action="${pageContext.request.contextPath}/book/updateBook" method="post">
        <input type="hidden" name="bookID" value="${book.getBookID()}"/>
        書籍名稱:<input type="text" name="bookName" value="${book.getBookName()}"/><br><br><br>
        書籍數量:<input type="text" name="bookCounts" value="${book.getBookCounts()}"/><br><br><br>
        書籍詳情:<input type="text" name="detail" value="${book.getDetail() }"/><br><br><br>
        <input type="submit" value="修改"/>
    </form>
</div>
</body>
</html>

以後,啓動tomcat,就能夠跑起來了

至此,SSM整合完成

項目結構

相關文章
相關標籤/搜索