SSM項目案例搭建整合含源碼(IDEA版)輕鬆上手

環境:

  1. IDEA
  2. MySql5.7以上
  3. Tomcat7.0以上
  4. Maven3.0以上

運用Spring MyBatis,mysql 簡單前端知識總結來說,配置地獄,各種配置,噁心到吐,還是springboot香,但是總要有個過程吧,難受完了,你會看到新的曙光

1.簡潔的運行截圖,花裏胡哨可以自己加,基礎的增刪改查CRUD工程師

在這裏插入圖片描述

2.數據庫建表,我這裏是navicat

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 '描述',
  KEY `bookID` (`bookID`)
) ENGINE=INNODB DEFAULT CHARSET=utf8
INSERT  INTO `books`(`bookID`,`bookName`,`bookCounts`,`detail`)VALUES 
 (1, '華爲手冊', 30, '博學的利郎');
(2, '中東局勢', 10, '如何生存');
 (3, '上下五千年', 5, '我要當秦始皇');
 (4, '美國是狗', 999999, '不用解釋');

3.導入依賴(建議保存,通用依賴)

  <dependencies>
        <!--Junit-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <!--數據庫驅動-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <!-- 數據庫連接池 -->
        <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</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

        <!--Mybatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.6</version>
        </dependency>

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.2</version>
        </dependency>

        <!--Spring-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.3.18.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.3.18.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.4</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.8</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

4.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>

5.看一下這是整體的架構結構

在這裏插入圖片描述

6.首先完成數據庫的配置: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>

    <!--配置實體別名-->
    <typeAliases>
         <package name="com.learn.pojo"/>
    </typeAliases>

    <mappers>
        <package name="com.learn.dao"/>
    </mappers>
</configuration>

7.MyBatis層(你的mysql用戶名和密碼與之對應):database.properties

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


8.MyBatis的核心配置類 :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>

    <!--配置實體別名-->
    <typeAliases>
         <package name="com.learn.pojo"/>
    </typeAliases>

    <mappers>
        <package name="com.learn.dao"/>
    </mappers>
</configuration>

9.在pojo包下寫實體類(與數據庫要與之對應):Books

在這裏插入圖片描述

package com.learn.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;
}

10.編寫:BooksMapper

package com.learn.dao;

import com.learn.pojo.Books;

import java.util.List;



public interface BooksMapper {

    int addBook(Books books);

    int deleteBook(int bookId);

    int updateBook(Books books);

    Books getBookById(int bookId);

    List<Books> findAll();





}

11.寫SQL語句:BooksMapper.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.learn.dao.BooksMapper">
    <insert id="addBook" parameterType="Books">
        insert into books (bookName,bookCounts,detail) values (#{bookName},#{bookCounts},#{detail})

    </insert>
    <delete id="deleteBook" parameterType="int">
        delete  from  books where bookID=#{bookID}
    </delete>

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

    <select id="getBookById" parameterType="int" resultType="Books">
        select *
        from books where bookID=#{bookID};
    </select>

    <select id="findAll" resultType="Books" >
        select *
        from books;
    </select>

</mapper>

12.現在可以寫與之對應的(這裏寫死就可以保存,沒有邏輯結構):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
        http://www.springframework.org/schema/context/spring-context.xsd">

    <!--引入數據庫配置文件-->
 <context:property-placeholder location="classpath:database.properties"/>

    <!--根據數據庫連接信息創建連接池-->
    <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>


    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
         <!--mybatis的客戶化配置-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
    </bean>



      <!--使用整合包生產代理對象注入到spring容器中-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <property name="basePackage"  value="com.learn.dao"/>
    </bean>


</beans>

13.接下來是編寫服務層:BooksServiceImpl

package com.learn.service.impl;

import com.learn.dao.BooksMapper;
import com.learn.pojo.Books;
import com.learn.service.BooksService;

import java.util.List;


public class BooksServiceImpl implements BooksService {


    private BooksMapper booksMapper;

    public void setBooksMapper(BooksMapper booksMapper) {
        this.booksMapper = booksMapper;
    }

    public int addBook(Books books) {
        return booksMapper.addBook(books);
    }

    public int deleteBook(int bookId) {
        int i= booksMapper.deleteBook(bookId);
        int j=1/0;
        return  i;
    }

    public int updateBook(Books books) {
        return  booksMapper.updateBook(books);
    }

    public Books getBookById(int bookId) {
        return booksMapper.getBookById(bookId) ;
    }

    public List<Books> findAll() {
        return  booksMapper.findAll();
    }
}

14.與之對應的BooksService

package com.learn.service;

import com.learn.pojo.Books;

import java.util.List;


public interface BooksService {

    int addBook(Books books);

    int deleteBook(int bookId);

    int updateBook(Books books);

    Books getBookById(int bookId);

    List<Books> findAll();
}

15.剩餘最後兩個配置類了: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"
       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
        http://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
        https://www.springframework.org/schema/tx/spring-tx.xsd">


    <context:component-scan base-package="com.learn.service"/>

    <bean id="booksService" class="com.learn.service.impl.BooksServiceImpl">
        <property name="booksMapper" ref="booksMapper"/>
    </bean>
    
    
    <!--開啓聲明式事務管理器-->
    <bean id="dataSourceTransactionManager"  class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!--定義事務管理器的作用範圍-->
    <tx:advice id="txAdvice" transaction-manager="dataSourceTransactionManager">
        <tx:attributes>
            <tx:method name="*" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>

    <!--定義在哪些方法上需要使用事務管理器-->
    <aop:config>
        <aop:pointcut id="txPoint" expression="execution(* com.learn.*.*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPoint"/>
    </aop:config>


</beans>

16.spring-webMvc.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">

         <!--註解驅動-->
         <mvc:annotation-driven/>
         <!--不處理靜態資源-->
         <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.掃描web相關的bean -->
    <context:component-scan base-package="com.learn.controller" />




</beans>

17.最最關鍵的:BookController層!!!!!增刪改查的操作都在裏面

package com.learn.controller;

import com.learn.pojo.Books;
import com.learn.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.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

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

@Controller
@RequestMapping("/book")
public class BookController {




    @Autowired
    private BooksService booksService;

    @RequestMapping("/queryAll")
    public String getAllBooks(Model model){
        List<Books> books = booksService.findAll();
        model.addAttribute("bookList",books);
         return "AllBook";
    }


    @RequestMapping("/toAddBook")
    public String toAddBookPage(){
          return  "addBook";
    }


    @RequestMapping("/addBook")
    public String addBook(Books book , HttpServletRequest request){
        //表單提交的name與實體類屬性一致springmvc會封裝到對象中,不一致需要從request中去取
        System.out.println(request.getParameter("detail"));
        booksService.addBook(book);
        return "redirect:/book/queryAll";
    }

    //restful風格參數獲取
    @RequestMapping("/del/{bookId}")
    public String delBook(@PathVariable int bookId){
        booksService.deleteBook(bookId);

        return "redirect:/book/queryAll";
    }


    //用問號傳參的字段名和參數名一致可以直接接收
    @RequestMapping("/toUpdateBook")
    public  String toUpdateBook(Model model,int id){
        Books book = booksService.getBookById(id);
        model.addAttribute("book",book);
        return "updateBook";
    }

    @RequestMapping("/updateBook")
    public  String updateBook(Books book){
        booksService.updateBook(book);
        return "redirect:/book/queryAll";
    }

}

2.1接下來是網頁addBook.jsp

<%@ 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>
  </body>
</html>

2.2AllBook.jsp查詢所有書籍

<%@ 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>
  </body>
</html>

2.3updateBook.jsp更新所有書籍

<%@ 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()}" ><br><br><br>
            書籍名稱:<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>
  </body>
</html>

2.4一個簡單的登錄界面index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>首頁</title>
     <style type="text/css">
            a {
                text-decoration: none;
                color: #00870b;
                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/queryAll">全部書籍</a></h3>
  </body>
</html>

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