SSM整合

环境搭建

1. 建表

  1. CREATE DATABASE `ssmbuild`;
  2. USE `ssmbuild`;
  3. DROP TABLE IF EXISTS `books`;
  4. CREATE TABLE `book` (
  5. `bookID` INT(10) NOT NULL AUTO_INCREMENT COMMENT '书id',
  6. `bookName` VARCHAR(100) NOT NULL COMMENT '书名',
  7. `bookCounts` INT(11) NOT NULL COMMENT '数量',
  8. `detail` VARCHAR(200) NOT NULL COMMENT '描述',
  9. KEY `bookID` (`bookID`)
  10. ) ENGINE=INNODB DEFAULT CHARSET=utf8;
  11. INSERT INTO `books`(`bookID`,`bookName`,`bookCounts`,`detail`)VALUES
  12. (1,'Java',1,'从入门到放弃'),
  13. (2,'MySQL',10,'从删库到跑路'),
  14. (3,'Linux',5,'从进门到进牢');

2. 导包

  1. <dependencies>
  2. <!--Junit-->
  3. <dependency>
  4. <groupId>junit</groupId>
  5. <artifactId>junit</artifactId>
  6. <version>4.12</version>
  7. </dependency>
  8. <!--数据库驱动-->
  9. <dependency>
  10. <groupId>mysql</groupId>
  11. <artifactId>mysql-connector-java</artifactId>
  12. <version>5.1.47</version>
  13. </dependency>
  14. <!-- 数据库连接池 -->
  15. <dependency>
  16. <groupId>com.mchange</groupId>
  17. <artifactId>c3p0</artifactId>
  18. <version>0.9.5.2</version>
  19. </dependency>
  20. <!--Servlet - JSP -->
  21. <dependency>
  22. <groupId>javax.servlet</groupId>
  23. <artifactId>servlet-api</artifactId>
  24. <version>2.5</version>
  25. </dependency>
  26. <dependency>
  27. <groupId>javax.servlet.jsp</groupId>
  28. <artifactId>jsp-api</artifactId>
  29. <version>2.2</version>
  30. </dependency>
  31. <dependency>
  32. <groupId>javax.servlet</groupId>
  33. <artifactId>jstl</artifactId>
  34. <version>1.2</version>
  35. </dependency>
  36. <!--Mybatis-->
  37. <dependency>
  38. <groupId>org.mybatis</groupId>
  39. <artifactId>mybatis</artifactId>
  40. <version>3.5.2</version>
  41. </dependency>
  42. <dependency>
  43. <groupId>org.mybatis</groupId>
  44. <artifactId>mybatis-spring</artifactId>
  45. <version>2.0.2</version>
  46. </dependency>
  47. <!--Spring-->
  48. <dependency>
  49. <groupId>org.springframework</groupId>
  50. <artifactId>spring-webmvc</artifactId>
  51. <version>5.1.9.RELEASE</version>
  52. </dependency>
  53. <dependency>
  54. <groupId>org.springframework</groupId>
  55. <artifactId>spring-jdbc</artifactId>
  56. <version>5.1.9.RELEASE</version>
  57. </dependency>
  58. <dependency>
  59. <groupId>org.projectlombok</groupId>
  60. <artifactId>lombok</artifactId>
  61. <version>1.16.10</version>
  62. </dependency>
  63. </dependencies>

3. 设置Maven资源过滤

  • pom.xml
  1. <build>
  2. <resources>
  3. <resource>
  4. <directory>src/main/java</directory>
  5. <includes>
  6. <include>**/*.properties</include>
  7. <include>**/*.xml</include>
  8. </includes>
  9. <filtering>false</filtering>
  10. </resource>
  11. <resource>
  12. <directory>src/main/resources</directory>
  13. <includes>
  14. <include>**/*.properties</include>
  15. <include>**/*.xml</include>
  16. </includes>
  17. <filtering>false</filtering>
  18. </resource>
  19. </resources>
  20. </build>

4. 创建项目结构和配置框架

SSM整合 - 图2

  • mybatis-config.xml ``` <?xml version=”1.0” encoding=”UTF-8” ?> <!DOCTYPE configuration
    1. PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
    2. "http://mybatis.org/dtd/mybatis-3-config.dtd">

  1. -
  2. applicationContext.xml

<?xml version=”1.0” encoding=”UTF-8”?>

  1. -
  2. db.properties
  3. <a name="Mybatis"></a>
  4. ## Mybatis
  5. <a name="8b3dcf3d"></a>
  6. ### 1. 创建实体类
  7. ```java
  8. package com.william.po;
  9. import lombok.AllArgsConstructor;
  10. import lombok.Data;
  11. import lombok.NoArgsConstructor;
  12. @Data
  13. @AllArgsConstructor
  14. @NoArgsConstructor
  15. public class Book {
  16. private int bookID;
  17. private String bookName;
  18. private int bookCounts;
  19. private String detail;
  20. }

2. 创建Dao层Mapper接口和Mapper.xml文件

  • Mapper.class
  1. package com.william.dao;
  2. import com.william.po.Book;
  3. import java.util.List;
  4. public interface BookMapper {
  5. //增加一个Book
  6. int addBook(Book book);
  7. //根据id删除一个Book
  8. int deleteBookById(int id);
  9. //更新Book
  10. int updateBook(Book book);
  11. //根据id查询,返回一个Book
  12. Book queryBookById(int id);
  13. //查询全部Book,返回list集合
  14. List<Book> queryAllBook();
  15. }
  • Mapper.xml

    1. <?xml version="1.0" encoding="UTF-8" ?>
    2. <!DOCTYPE mapper
    3. PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
    4. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    5. <mapper namespace="com.william.dao.BookMapper">
    6. <!--增加一个Book-->
    7. <insert id="addBook" parameterType="Book">
    8. insert into ssmbuild.book(bookName,bookCounts,detail)
    9. values (#{bookName}, #{bookCounts}, #{detail})
    10. </insert>
    11. <!--根据id删除一个Book-->
    12. <delete id="deleteBookById" parameterType="int">
    13. delete from ssmbuild.book where bookID=#{bookID}
    14. </delete>
    15. <!--更新Book-->
    16. <update id="updateBook" parameterType="Book">
    17. update ssmbuild.book
    18. set bookName = #{bookName},bookCounts = #{bookCounts},detail = #{detail}
    19. where bookID = #{bookID}
    20. </update>
    21. <!--根据id查询,返回一个Book-->
    22. <select id="queryBookById" resultType="Book">
    23. select * from ssmbuild.book
    24. where bookID = #{bookID}
    25. </select>
    26. <!--查询全部Book-->
    27. <select id="queryAllBook" resultType="Book">
    28. SELECT * from ssmbuild.book
    29. </select>
    30. </mapper>

3. 创建Service层的接口和实现类,并在其中调用Dao层

  • Service.class ```java package com.william.service;

import com.william.po.Book; import java.util.List;

public interface BookService { //增加一个Book int addBook(Book book); //根据id删除一个Book int deleteBookById(int id); //更新Book int updateBook(Book book); //根据id查询,返回一个Book Book queryBookById(int id); //查询全部Book,返回list集合 List queryAllBook(); }

  1. -
  2. ServiceImpl.class
  3. ```java
  4. package com.william.service;
  5. import com.william.dao.BookMapper;
  6. import com.william.po.Book;
  7. import java.util.List;
  8. public class BookServiceImpl implements BookService {
  9. // 持有Dao层
  10. public BookMapper bookMapper;
  11. // 方法均调用Dao层中同名方法
  12. @Override
  13. public int addBook(Book book) {
  14. return bookMapper.addBook(book);
  15. }
  16. @Override
  17. public int deleteBookById(int id) {
  18. return bookMapper.deleteBookById(id);
  19. }
  20. @Override
  21. public int updateBook(Book book) {
  22. return bookMapper.updateBook(book);
  23. }
  24. @Override
  25. public Book queryBookById(int id) {
  26. return bookMapper.queryBookById(id);
  27. }
  28. @Override
  29. public List<Book> queryAllBook() {
  30. return bookMapper.queryAllBook();
  31. }
  32. public void setBookMapper(BookMapper bookMapper) {
  33. this.bookMapper = bookMapper;
  34. }
  35. }

Spring

  • spring-dao.xml

    1. <?xml version="1.0" encoding="UTF-8"?>
    2. <beans xmlns="http://www.springframework.org/schema/beans"
    3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    4. xmlns:context="http://www.springframework.org/schema/context"
    5. xsi:schemaLocation="http://www.springframework.org/schema/beans
    6. http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
    7. <!-- 1.关联数据库配置文件-->
    8. <context:property-placeholder location="classpath:jdbc.properties"/>
    9. <!-- 2.数据库连接池 -->
    10. <!--数据库连接池
    11. dbcp 半自动化操作 不能自动连接
    12. c3p0 自动化操作(自动的加载配置文件 并且设置到对象里面)
    13. -->
    14. <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    15. <!-- 配置连接池属性 -->
    16. <property name="driverClass" value="${jdbc.driver}"/>
    17. <property name="jdbcUrl" value="${jdbc.url}"/>
    18. <property name="user" value="${jdbc.username}"/>
    19. <property name="password" value="${jdbc.password}"/>
    20. <!-- c3p0连接池的私有属性 -->
    21. <property name="maxPoolSize" value="30"/>
    22. <property name="minPoolSize" value="10"/>
    23. <!-- 关闭连接后不自动commit -->
    24. <property name="autoCommitOnClose" value="false"/>
    25. <!-- 获取连接超时时间 -->
    26. <property name="checkoutTimeout" value="10000"/>
    27. <!-- 当获取连接失败重试次数 -->
    28. <property name="acquireRetryAttempts" value="2"/>
    29. </bean>
    30. <!-- 3.配置SqlSessionFactory对象 -->
    31. <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    32. <!-- 注入数据库连接池 -->
    33. <property name="dataSource" ref="dataSource"/>
    34. <!-- 配置MyBatis全局配置文件:mybatis-config.xml -->
    35. <property name="configLocation" value="classpath:mybatis-config.xml"/>
    36. </bean>
    37. <!-- 4.配置扫描Dao接口包,动态实现Dao接口注入到spring容器中 -->
    38. <!--解释 :https://www.cnblogs.com/jpfss/p/7799806.html-->
    39. <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    40. <!-- 注入sqlSessionFactory -->
    41. <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    42. <!-- 给出需要扫描Dao接口包 -->
    43. <property name="basePackage" value="com.william.dao"/>
    44. </bean>
    45. </beans>

重点!!!!SSM整合 - 图3


参考:https://blog.csdn.net/qq598535550/article/details/51703190?ops_request_misc=%7B%22request%5Fid%22%3A%22160359229319724842930227%22%2C%22scm%22%3A%2220140713.130102334..%22%7D&request_id=160359229319724842930227&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2top_click~default-4-51703190.pc_first_rank_v2_rank_v28&utm_term=ssm&spm=1018.2118.3001.4187

  • spring-service.xml ```xml <?xml version=”1.0” encoding=”UTF-8”?>

  1. <a name="SpringMVC"></a>
  2. ## SpringMVC
  3. -
  4. web.xml
  5. ```xml
  6. <?xml version="1.0" encoding="UTF-8"?>
  7. <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
  8. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  9. xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
  10. version="4.0">
  11. <!--DispatcherServlet-->
  12. <servlet>
  13. <servlet-name>DispatcherServlet</servlet-name>
  14. <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  15. <init-param>
  16. <param-name>contextConfigLocation</param-name>
  17. <!--一定要注意:我们这里加载的是总的配置文件,之前被这里坑了!-->
  18. <param-value>classpath:applicationContext.xml</param-value>
  19. </init-param>
  20. <load-on-startup>1</load-on-startup>
  21. </servlet>
  22. <servlet-mapping>
  23. <servlet-name>DispatcherServlet</servlet-name>
  24. <url-pattern>/</url-pattern>
  25. </servlet-mapping>
  26. <!--encodingFilter-->
  27. <filter>
  28. <filter-name>encodingFilter</filter-name>
  29. <filter-class>
  30. org.springframework.web.filter.CharacterEncodingFilter
  31. </filter-class>
  32. <init-param>
  33. <param-name>encoding</param-name>
  34. <param-value>utf-8</param-value>
  35. </init-param>
  36. </filter>
  37. <filter-mapping>
  38. <filter-name>encodingFilter</filter-name>
  39. <url-pattern>/*</url-pattern>
  40. </filter-mapping>
  41. <!--Session过期时间-->
  42. <session-config>
  43. <session-timeout>15</session-timeout>
  44. </session-config>
  45. </web-app>
  • spring-mvc.xml ```xml <?xml version=”1.0” encoding=”UTF-8”?>

  1. <a name="dc53819c"></a>
  2. ## 配置文件的整合
  3. <a name="bbce0330"></a>
  4. ### 1.使用IDEA
  5. ![](https://gitee.com/qinweilong/cloudimage/raw/master/img/image-20201025154842299.png#alt=image-20201025154842299)
  6. <a name="3e2ce77f"></a>
  7. ### 2.applicationContext.xml中配置
  8. ```xml
  9. <?xml version="1.0" encoding="UTF-8"?>
  10. <beans xmlns="http://www.springframework.org/schema/beans"
  11. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  12. xsi:schemaLocation="http://www.springframework.org/schema/beans
  13. http://www.springframework.org/schema/beans/spring-beans.xsd">
  14. <import resource="spring-dao.xml"/>
  15. <import resource="spring-service.xml"/>
  16. <import resource="spring-mvc.xml"/>
  17. </beans>

Controller层

  • bookController.class ```java package com.william.controller;

import com.william.po.Book; import com.william.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 java.util.List;

@Controller @RequestMapping(“/book”) public class BookController {

  1. // 查询
  2. @Autowired
  3. @Qualifier("BookServiceImpl")
  4. private BookService bookService;
  5. @RequestMapping("/allBook")
  6. public String list(Model model) {
  7. List<Book> list = bookService.queryAllBook();
  8. model.addAttribute("list", list);
  9. return "allBook";
  10. }
  11. // 增加
  12. @RequestMapping("/toAddBook")
  13. public String toAddPaper() {
  14. return "addBook";
  15. }
  16. @RequestMapping("/addBook")
  17. public String addPaper(Book book) {
  18. System.out.println(book);
  19. bookService.addBook(book);
  20. // 重定向
  21. return "redirect:/book/allBook";
  22. }
  23. // 修改
  24. @RequestMapping("/toUpdateBook")
  25. public String toUpdateBook(Model model, int id) {
  26. Book book = bookService.queryBookById(id);
  27. System.out.println(book);
  28. model.addAttribute("book", book);
  29. return "updateBook";
  30. }
  31. @RequestMapping("/updateBook")
  32. public String updateBook(Model model, Book book) {
  33. System.out.println(book);
  34. bookService.updateBook(book);
  35. Book books = bookService.queryBookById(book.getBookID());
  36. model.addAttribute("books", book);
  37. return "redirect:/book/allBook";
  38. }
  39. // 删除
  40. @RequestMapping("/del/{bookId}")
  41. public String deleteBook(@PathVariable("bookId") int id) {
  42. bookService.deleteBookById(id);
  43. return "redirect:/book/allBook";
  44. }

} ```

另外编写对应前端页面

  • allBook.jsp
  • addBook.jsp
  • updateBook.jsp