1. 程式人生 > 其它 >SpringMVC:ssm整合

SpringMVC:ssm整合

環境要求

環境:IDEA、MySQL5.7.19、Tomact8.5、Mavec3.6.1

資料庫環境

CREATE DATABASE `ssmbuild`;

USE `ssmbuild`;

DROP TABLE IF EXISTS `books`;
CREATE TABLE `books` (
`bookID` int(10) NOT NULL AUTO_INCREMENT COMMENT '書id',
`bookName` varchar(100) NOT NULL COMMENT '書名',
`bookCounts` int(11) NOT NULL COMMENT '數量',
`detail` varchar(200) NOT NULL COMMENT '描述',
PRIMARY KEY (`bookID`),
KEY `bookID` (`bookID`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

INSERT INTO `books` VALUES ('1', 'Java', '1213', '從入門到放棄');
INSERT INTO `books` VALUES ('2', 'MySQL', '212', '從刪庫到跑路');
INSERT INTO `books` VALUES ('3', 'Linux', '1231', '從進門到進牢');

基本環境搭建

1.新建Maven專案,ssmbuild,新增web的支援

2.匯入相關的pom依賴

   <!--依賴:junit,資料庫驅動,連線池,servlet,jsp,mybatis,mybatis-spring,spring-->
     <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13</version>
        </dependency>
        <!--資料庫驅動-->
        <dependency>
            <
groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.25</version> </dependency> <!--資料庫連線池:c3p0--> <dependency> <groupId>com.mchange</groupId> <artifactId>c3p0</artifactId> <version>0.9.5.2</version> </dependency> <!--Servlet-JSP--> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.2</version> </dependency> <dependency> <groupId>javax.servlet.jsp.jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!--Mybatis--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.7</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>2.0.6</version> </dependency> <!--Spring--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.3.9</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.3.9</version> </dependency> </dependencies>

3.Maven資源過濾設定

    <!--靜態資源匯出問題-->
    <build>
        <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>

4.建立基本結構和配置框架!

  • com.yyw.pojo
  • com.yyw.dao
  • com.yyw.service
  • com.yyw.controller
  • mybatis-config.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>
    
</configuration>
  • 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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">

<import resource="classpath:spring-dao.xml"/>
<import resource="classpath:spring-service.xml"/>
<import resource="classpath:spring-mvc.xml"/>
</beans>

Mybatis層編寫

1.資料庫配置檔案database.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssmbuild?userSSL=true&useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=wuhui1017

2.IDEA關聯資料庫

3.編寫MyBatis的核心配置檔案

<?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>

<!--配置資料來源,交給Spring去做-->
<typeAliases>
<package name="com.yyw.pojo"/>
</typeAliases>

<mappers>
<mapper class="com.yyw.dao.BookMapper"/>
</mappers>
</configuration>

4.編寫實體類com.yyw.pojo.Books,使用lombok外掛!

package com.yyw.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Books {

    private int bookID;
    private String bookName;
    private int bookCounts;
    private String detail;
}

5編寫Dao層的Mapper介面!

package com.yyw.dao;

import com.yyw.pojo.Books;
import org.apache.ibatis.annotations.Param;

import java.util.List;

public interface BookMapper {

//增加
int addBook(Books books);

//刪除
int deleteBookById(@Param("bookId") int id);

//更新
int updateBook(Books books);


//查詢一本書
Books queryBookById(@Param("bookId") int id);


//查詢全部
List<Books> queryAllBook();

//根據書名查詢
Books queryBookByName(@Param("bookName") String bookName);

}

6.編寫對應的Mapper.xml檔案,需要匯入MyBatis的包

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.yyw.dao.BookMapper">

<insert id="addBook" parameterType="Books">
insert into ssmbuild.books(bookName,bookCounts,detail)
values (#{bookName},#{bookCounts},#{detail});
</insert>

<delete id="deleteBookById" parameterType="int">

delete from ssmbuild.books
where bookID=#{bookId}
</delete>

<update id="updateBook" parameterType="Books">
update ssmbuild.books set bookName=#{bookName},bookCounts=#{bookCounts},detail=#{detail}
where bookID=#{bookID};
</update>

<select id="queryBookById" resultType="Books">

select * from ssmbuild.books
where bookID=#{bookId}
</select>

<select id="queryAllBook" resultType="Books">

select * from ssmbuild.books
</select>

<select id="queryBookByName" resultType="Books">
select * from ssmbuild.books
where bookName=#{bookName}
</select>
</mapper>

7.編寫Service層的介面和實現類

介面:

package com.yyw.service;

import com.yyw.pojo.Books;
import org.apache.ibatis.annotations.Param;

import java.util.List;

public interface BookService {

//增加
int addBook(Books books);

//刪除
int deleteBookById(int id);

//更新
int updateBook(Books books);


//查詢一本書
Books queryBookById(int id);


//查詢全部
List<Books> queryAllBook();

//根據書名查詢
Books queryBookByName(String bookName);

}

實現類:

package com.yyw.service;

import com.yyw.dao.BookMapper;
import com.yyw.pojo.Books;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class BookServiceImpl implements BookService {
//service調dao層,組合Dao
@Autowired
private BookMapper bookMapper;

public void setBookMapper(BookMapper bookMapper) {
this.bookMapper = bookMapper;
}

public int addBook(Books books) {
System.out.println("BookServiceImpl:addBook=>"+books);
return bookMapper.addBook(books);
}

public int deleteBookById(int id) {
return bookMapper.deleteBookById(id);
}

public int updateBook(Books books) {
System.out.println("BookServiceImpl:updateBook=>"+books);
return bookMapper.updateBook(books);
}

public Books queryBookById(int id) {
return bookMapper.queryBookById(id);
}

public List<Books> queryAllBook() {
return bookMapper.queryAllBook();
}

public Books queryBookByName(String bookName) {
return bookMapper.queryBookByName(bookName);
}


}

Spring層

1.配置Spring整合Mybatis,我們這裡使用c3p0連線池

2.編寫Spring整合MyBatis的相關配置檔案spring-dao.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"
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:database.properties"/>

<!--2.連線池
dbcp:半自動化操作,不能自動連線
c3p0:自動化操作,自動載入配置檔案,並且可以自動設定到物件中
druid:
hikari:
-->
<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}"/>

<!--c3p0連線池的私有屬性-->
<property name="maxPoolSize" value="30"/>
<property name="minPoolSize" value="10"/>
<!--關閉連線後不自動commit-->
<property name="autoCommitOnClose" value="false"/>
<!--獲取連線超時時間-->
<property name="checkoutTimeout" value="10000"/>
<!--當獲取連線失敗重試次數-->
<property name="acquireRetryAttempts" value="2"/>
</bean>
<!--3.sqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!--繫結Mybatis的配置檔案-->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>

<!--配置dao介面掃描包,動態實現Dao介面可以注入到Spring容器中-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--注入sqlSessionFactory-->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!--掃描Dao包-->
<property name="basePackage" value="com.yyw.dao"/>
</bean>

</beans>

3.Spring整合service層

<?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"
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
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">

<!--1.掃描service下的包-->
<context:component-scan base-package="com.yyw.service"/>

<!--2.將我們的所有業務類,注入到Spring,可以通過配置或者註解實現-->
<bean id="BookServiceImpl" class="com.yyw.service.BookServiceImpl">
<property name="bookMapper" ref="bookMapper"/>
</bean>
<!--3.宣告式事務配置-->
<!--注入資料來源-->
<bean id="TransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>


<!--結合AOP實現事務的織入-->
<!--配置事務通知-->
<tx:advice id="txAdvice" transaction-manager="TransactionManager">
<!--給那些方法配置事務-->
<!--配置事務的傳播特性:new propagation-->
<tx:attributes>
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<!--4.aop事務支援-->
<aop:config>
<aop:pointcut id="txPointCut" expression="execution(* com.yyw.dao.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
</aop:config>


</beans>

SpringMVC層

1.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">
    <!--DispatchServlet-->
    <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:applicationContext.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</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>

    <!--Session-->
    <session-config>
        <session-timeout>15</session-timeout>
    </session-config>
</web-app>

2.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:mvc="http://www.springframework.org/schema/mvc"
       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/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

    <!--1.註解驅動-->
    <mvc:annotation-driven/>
    <!--2.靜態資源過濾-->
    <mvc:default-servlet-handler/>
    <!--3.掃描包:controller-->
    <context:component-scan base-package="com.yyw.controller"/>
    <!--4.檢視解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

</beans>

3.Spring配置整合檔案,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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

    <import resource="classpath:spring-dao.xml"/>
    <import resource="classpath:spring-service.xml"/>
    <import resource="classpath:spring-mvc.xml"/>
</beans>

配置檔案暫時結束,Controller和檢視層編寫

1.BookController類編寫

package com.yyw.controller;

import com.yyw.pojo.Books;
import com.yyw.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/book")
public class BookController {
    //controller調service層
    @Autowired
    @Qualifier("BookServiceImpl")
    private BookService bookService;

    //查詢全部書籍,並返回到書籍展示頁面
    @RequestMapping("/allBook")
    public String list(Model model){
        List<Books> list = bookService.queryAllBook();
        model.addAttribute("list",list);
        return "allBook";
    }

    //新增書籍
    @RequestMapping("/addBook")
    public String add(){
        return "addBook";
    }

    //新增書籍請求
    @RequestMapping("/addBook1")
    public String addBook(Books books){
        System.out.println("addBook==>"+books);
        bookService.addBook(books);
        return "redirect:/book/allBook";//重定向到allBook
    }

    //刪除書籍
    @RequestMapping("/deleteBook/{bookId}")
    public String deleteBook(@PathVariable("bookId") int id){
        bookService.deleteBookById(id);

        return "redirect:/book/allBook";
    }

    //修改書籍
    @RequestMapping("/update")
    public String update(int id,Model model){
        Books books = bookService.queryBookById(id);
        model.addAttribute("QBooks",books);
        return "updateBook";
    }

    //修改書籍詳情
    @RequestMapping("/updateBook")
    public String updateBook(Books books){
        System.out.println("updateBooks=>"+books);
        int i = bookService.updateBook(books);

        if (i>0){
            System.out.println("新增books成功"+books);
        }
        return "redirect:/book/allBook";
    }

    //查詢書籍
    @RequestMapping("/query")
    public String queryBook(String queryBookName,Model model){

        Books books = bookService.queryBookByName(queryBookName);
        List<Books> list=new ArrayList<Books>();
        list.add(books);

        if (books==null){
            list=bookService.queryAllBook();
            model.addAttribute("error","沒有對應資訊");
        }


        model.addAttribute("list",list);
        return "allBook";
    }



}

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>

    <%--BootStrap美化介面--%>
    <link href="//cdn.bootcss.com/bootstrap/3.3.1/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/addBook">新增書籍</a>
            <a class="btn btn-primary" href="${pageContext.request.contextPath}/book/allBook">顯示全部書籍</a>
        </div>
        <div class="col-md-4 column"></div>
        <div class="col-md-4 column">
            <form action="${pageContext.request.contextPath}/book/query?bookName=${bookName}" method="post" style="float: right" class="form-inline">
                <span style="color: red;font-weight:bold ">${error}</span>
                <input type="text" name="queryBookName" class="form-control" placeholder="請輸入要查詢的書籍名稱">
                <input type="submit" class="btn btn-primary" value="提交">
            </form>
        </div>
    </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>
            <%--書籍從資料庫中查找出來,從這個list中遍歷出來:foreach--%>
            <tbody>
                <c:forEach var="book" items="${list}">
                    <tr>
                        <td>${book.bookID}</td>
                        <td>${book.bookName}</td>
                        <td>${book.bookCounts}</td>
                        <td>${book.detail}</td>
                        <td>
                            <a class="btn btn-primary" href="${pageContext.request.contextPath}/book/update?id=${book.bookID}">修改</a>
                            &nbsp;|&nbsp;
                            <a class="btn btn-primary" href="${pageContext.request.contextPath}/book/deleteBook/${book.bookID}">刪除</a>
                        </td>
                    </tr>
                </c:forEach>
            </tbody>
        </table>
    </div>
</div>
</body>
</html>

3.add.jsp

<%--
  Created by IntelliJ IDEA.
  User: dell
  Date: 2021/9/6
  Time: 19:12
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>新增書籍</title>
    <%--BootStrap美化介面--%>
    <link href="//cdn.bootcss.com/bootstrap/3.3.1/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/addBook1" method="post">
        <div class="form-group">
            <label>書籍名稱:</label><input type="text" name="bookName" class="form-group" required><br>
        </div>
        <div class="form-group">
            <label>書籍數量:</label><input type="text" name="bookCounts" class="form-group" required><br>
        </div>
        <div class="form-group">
            <label>書籍描述:</label><input type="text" name="detail" class="form-group" required><br>
        </div>
        <div class="form-group">
            <input type="submit" class="form-group" value="新增" size="100px">
        </div>
    </form>
</div>
</body>
</html>

4.updatebook.jsp

<%--
  Created by IntelliJ IDEA.
  User: dell
  Date: 2021/9/7
  Time: 16:26
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>修改書籍</title>
    <%--BootStrap美化介面--%>
    <link href="//cdn.bootcss.com/bootstrap/3.3.1/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">
        <%--出現問題:提交了修改SQL的請求,但修改失敗,初次考慮,是事務問題,配置完畢後,依舊失敗--%>
        <%--看一下SQL語句,能否執行成功:SQL執行失敗,修改未完成--%>
            <%--前端傳遞隱藏域--%>
        <input type="hidden" name="bookID" value="${QBooks.bookID}">
        <div class="form-group">
            <label>書籍名稱:</label><input type="text" name="bookName" class="form-group" value="${QBooks.bookName}">
        </div>
        <div class="form-group">
            <label>書籍數量:</label><input type="text" name="bookCounts" class="form-group" value="${QBooks.bookCounts}">
        </div>
        <div class="form-group">
            <label>書籍詳情:</label><input type="text" name="detail" class="form-group" value="${QBooks.detail}">
        </div>
        <div class="form-group">
            <input type="submit" class="btn btn-primary" value="確定">
            <a class="btn btn-primary" href="${pageContext.request.contextPath}/book/allBook">取消</a>
        </div>
    </form>
</div>

</body>
</html>

執行,即可完成!