1. 程式人生 > 其它 >SSM整合(一)

SSM整合(一)

SpringMVC:整合SSM

要求:需要熟練掌握MySQL資料庫,Spring,JavaWeb及MyBatis知識,簡單的前端知識

一、資料庫環境

建立一個存放書籍資料的資料庫表

create database `ssmbuild`;

use `ssmbuild`;

create table `book`(
`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 '描述',
KEY `bookID`(`bookID`)
)ENGINE=INNODB DEFAULT CHARSET=utf8;

INSERT INTO `book`(`bookID`,`bookName`,`bookCounts`,`detail`)VALUES
(1,'Java',1,'從入門到放棄'),
(2,'MySQL',10,'從刪庫到跑路'),
(3,'Linux',5,'從進門到進牢');

二、基本環境搭建

1、匯入依賴

<!--依賴:junit,資料庫驅動,連結池,servlet,jsp,mybatis,mybatis-spring,spring-->
    <dependencies>
        <!-- https://mvnrepository.com/artifact/junit/junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.25</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.mchange/c3p0 -->
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.5</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
            <scope>provided</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/javax.servlet.jsp/jsp-api -->
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.2</version>
            <scope>provided</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.7</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.6</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.8</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.3.8</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
		<dependency>
    		<groupId>org.projectlombok</groupId>
    		<artifactId>lombok</artifactId>
    		<version>1.18.20</version>
    		<scope>provided</scope>
		</dependency>

2、靜態資源匯出問題

	<build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
            </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>

3、在IDEA中連線資料庫

4、建包

pojo、dao(mapper)、service、controller

5、resource檔案

mybatis-config.xml(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>

</configuration>

applicationContext.xml(Spring核心配置檔案)

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

</beans>

database.properties

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssmbuild?useSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
jdbc.username=root
jdbc.password=123456

6、實體類pojo

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Book {
    private int bookID;
    private String bookName;
    private int bookCounts;
    private String detail;
}

三、Mybatis層

1、dao

  • BookMapper
public interface BookMapper {
    //增加一本書
    int addBook(Book book);
    //刪除一本書
    int deleteBookById(@Param("bookId") int id);
    //更新一本書
    int updateBook(Book book);
    //查詢一本書
    Book queryBookById(@Param("bookId") int id);
    //查詢全部書
    List<Book> queryAllBook();
}
  • BookMapper.xml
<?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.aurora.dao.BookMapper">
    <insert id="addBook" parameterType="Book">
        insert into ssmbuild.book(bookName,bookCounts,detail)values (#{bookName},#{bookCounts},#{detail})
    </insert>
    <delete id="deleteBookById" parameterType="int">
        delete from ssmbuild.book where bookID=#{bookId}
    </delete>
    <update id="updateBook" parameterType="Book">
        update ssmbuild.book set bookName=#{bookName},bookCounts=#{bookCounts},detail=#{detail} where bookID=#{bookID}
    </update>
    <select id="queryBookById" resultType="Book">
        select * from ssmbuild.book where bookID=#{bookId}
    </select>
    <select id="queryAllBook" resultType="Book">
        select * from ssmbuild.book
    </select>
</mapper>
  • 在mybatis-config.xml中註冊
	<mappers>
        <mapper class="com.aurora.dao.BookMapper"/>
    </mappers>

2、service

  • BookService
public interface BookService {
    //增加一本書
    int addBook(Book book);
    //刪除一本書
    int deleteBookById(int id);
    //更新一本書
    int updateBook(Book book);
    //查詢一本書
    Book queryBookById(int id);
    //查詢全部書
    List<Book> queryAllBook();
}
  • BookServiceImpl
public class BookServiceImpl implements BookService{
    //業務層調dao層,組合dao
    private BookMapper bookMapper;

    public void setBookMapper(BookMapper bookMapper) {
        this.bookMapper = bookMapper;
    }
    @Override
    public int addBook(Book book) {
        return bookMapper.addBook(book);
    }

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

    @Override
    public int updateBook(Book book) {
        return bookMapper.updateBook(book);
    }

    @Override
    public Book queryBookById(int id) {
        return bookMapper.queryBookById(id);
    }

    @Override
    public List<Book> queryAllBook() {
        return bookMapper.queryAllBook();
    }
}

四、Spring層

1、整合dao

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
        https://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}"/>
    </bean>
    <!--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.aurora.dao"/>
    </bean>
</beans>

2、整合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"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">
    <!--1、掃描service下的包-->
    <context:component-scan base-package="com.aurora.service"/>
    <!--2、將我們所有業務類注入到Spring,可以通過配置或者註解實現(@Service、@Autowired)-->
    <bean id="BookServiceImpl" class="com.aurora.service.BookServiceImpl">
        <property name="bookMapper" ref="bookMapper"/>
    </bean>
    <!--3、宣告式事務配置-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!--注入資料來源-->
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <!--4、aop事務支援-->
</beans>

五、SpringMVC層

1、增加web支援

2、在web.xml中新增

    <!--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:spring-mvc.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>

3、配置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
        https://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.aurora.controller"/>
    <!--4、檢視解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

六、新增查詢書籍功能

1、controller層

@Controller
@RequestMapping("/book")
public class BookController {
    //controller調service層
    @Autowired
    @Qualifier("BookServiceImpl")
    private BookService bookService;
    //查詢全部書籍,並且返回到一個書籍展示頁面
    @RequestMapping("/allBook")
    public String list(Model model){
        List<Book> list = bookService.queryAllBook();
        model.addAttribute("list",list);
        return "allBook";
    }
}

2、新增查詢頁面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>書籍展示</title>
</head>
<body>
<h1>書籍展示</h1>
<h2>${list}</h2>
</body>
</html>

問題:

  • 沒有給lib下新增依賴包,導致瀏覽器打不開
  • web.xml中繫結配置檔案出了問題

3、美化介面

  • 首頁
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>首頁</title>
    <style>
      a{
        text-decoration: none;
        color: black;
        font-size: 18px;
      }
      h3{
        width: 180px;
        height: 30px;
        margin: 100px auto;
        text-align: center;
        line-height: 30px;
        background: aqua;
        border-radius: 5px;
      }
    </style>
  </head>
  <body>
  <h3>
    <a href="${pageContext.request.contextPath}/book/allBook">進入書籍頁面</a>
  </h3>
  </body>
</html>
  • 書籍展示頁面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>書籍展示</title>
    <%--BootSrap美化介面--%>
    <link href="https://cdn.staticfile.org/twitter-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 clearfix">
        <div class="col-md-12 column">
            <table class="table table-hover table-striped">
                <thead>
                <tr>
                    <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>
                    </tr>
                </c:forEach>
                </tbody>
            </table>
        </div>
    </div>
</div>
</body>
</html>

問題:如果顯示不出書籍在lib中新增jstl支援

七、新增書籍功能

1、跳轉新增書籍頁面

<div class="row">
	<div class="col-md-4 colum">
		<a class="btn btn-primary" href="${pageContext.request.contextPath}/book/toAddPaper">新增書籍</a>
     </div>
</div>

2、在控制層響應跳轉頁面

    //跳轉到增加書籍頁面
    @RequestMapping("/toAddPaper")
    public String toAddPaper(){
        return "addBook";
    }

3、新建跳轉頁面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <%--BootSrap美化介面--%>
    <link href="https://cdn.staticfile.org/twitter-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">
            <div class="form-group">
                <label>書籍名稱:</label>
                <input type="text" name="bookName" class="form-control" required>
            </div>
            <div class="form-group">
                <label>書籍數量:</label>
                <input type="text" name="bookCounts" class="form-control" required>
            </div>
            <div class="form-group">
                <label>書籍描述:</label>
                <input type="text" name="detail" class="form-control" required>
            </div>
            <div class="form-group">
                <input type="submit" class="form-control" value="新增" required>
            </div>
        </form>
    </div>
</body>
</html>

4、在控制層新增書籍新增請求

    //新增書籍的請求
    @RequestMapping("/addBook")
    public String addBook(Book book){
        System.out.println("addBook"+book);
        bookService.addBook(book);
        return "redirect:/book/allBook";//重定向到我們的@RequestMapping
    }

八、更新書籍功能

1、新增修改介面

<c:forEach var="book" items="${requestScope.get('list')}">
	<tr>
    	<td>${book.bookID}</td>
    	<td>${book.bookName}</td>
    	<td>${book.bookCounts}</td>
    	<td>${book.detail}</td>
    	<td>
        	<a href="${pageContext.request.contextPath}/book/toUpdatePaper?id=${book.bookID}">修改</a>
            &nbsp;|&nbsp;
            <a href="">刪除</a>
         </td>
    </tr>
</c:forEach>

2、controller層跳轉頁面

    //跳轉到修改頁面
    @RequestMapping("/toUpdatePaper")
    public String toUpdatePaper(int id,Model model){
        Book book = bookService.queryBookById(id);
        model.addAttribute("Qbook",book);
        return "updateBook";
    }

3、新增更新頁面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>修改書籍</title>
    <%--BootSrap美化介面--%>
    <link href="https://cdn.staticfile.org/twitter-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" class="form-control" value="${Qbook.bookID}">
        <div class="form-group">
            <label>書籍名稱:</label>
            <input type="text" name="bookName" class="form-control" value="${Qbook.bookName}" required>
        </div>
        <div class="form-group">
            <label>書籍數量:</label>
            <input type="text" name="bookCounts" class="form-control" value="${Qbook.bookCounts}" required>
        </div>
        <div class="form-group">
            <label>書籍描述:</label>
            <input type="text" name="detail" class="form-control" value="${Qbook.detail}" required>
        </div>
        <div class="form-group">
            <input type="submit" class="form-control" value="修改" required>
        </div>
    </form>
</div>
</body>
</html>

4、在controller層新增修改請求

    //修改書籍
    @RequestMapping("/updateBook")
    public String updateBook(Book book){
        System.out.println("updateBook=="+book);
        bookService.updateBook(book);
        return "redirect:/book/allBook";
    }

九、刪除書籍功能

1、新增刪除頁面

<a href="${pageContext.request.contextPath}/book/deleteBook/${book.bookID}">刪除</a>

基於RESTFUL是一種網路應用程式的設計風格和開發方式

2、在controller層新增刪除請求

    //刪除書籍
    @RequestMapping("/deleteBook/{bookID}")
    public String deleteBook(@PathVariable("bookID") int id){
        bookService.deleteBookById(id);
        return "redirect:/book/allBook";
    }

十、根據書名查詢書籍功能

1、新增查詢頁面

<div class="row clearfix">
        <div class="col-md-12 column">
            <div class="page-header">
                <h1>
                    <small>書籍列表————顯示所有書籍</small>
                </h1>
            </div>
        </div>
        <div class="row">
            <div class="col-md-4 colum">
                <a class="btn btn-primary" href="${pageContext.request.contextPath}/book/toAddPaper">新增書籍</a>
                <a class="btn btn-primary" href="${pageContext.request.contextPath}/book/allBook">顯示全部書籍</a>
            </div>
            <div class="col-md-8 colum">
                <%--查詢書籍--%>
                <form class="form-inline" action="${pageContext.request.contextPath}/book/queryBook" method="post" style="float: right">
                    <span style="color: red;font-weight: bold">${error}</span>
                    <input type="text" name="queryBookName" class="form-control" placeholder="請輸入要查詢的書籍名稱">
                    <input type="submit" value="查詢" class="btn btn-primary">
                </form>
            </div>
        </div>
    </div>

2、在dao層新增查詢方法

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

3、在mapper中新增查詢SQL

    <select id="queryBookByName" resultType="Book">
        select * from ssmbuild.book where bookName=#{bookName}
    </select>

4、在service層新增查詢方法及實現類

    //根據書名查詢書籍
    Book queryBookByName(String bookName);
    @Override
    public Book queryBookByName(String bookName) {
        return bookMapper.queryBookByName(bookName);
    }

5、在控制層新增請求

    //查詢書籍
    @RequestMapping("/queryBook")
    public String queryBook(String queryBookName,Model model){
        Book book = bookService.queryBookByName(queryBookName);
        List<Book> list = new ArrayList<>();
        list.add(book);
        if (book==null){
            list=bookService.queryAllBook();
            model.addAttribute("error","未查到");
        }
        model.addAttribute("list",list);
        return "allBook";
    }