ssm框架的整合

SSMBuild

1. 基本环境搭建

  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 '描述',
    KEY `bookID` (`bookID`)
    ) ENGINE=INNODB DEFAULT CHARSET=utf8
    
    INSERT  INTO `books`(`bookID`,`bookName`,`bookCounts`,`detail`)VALUES
    (1,'Java',1,'从入门到放弃'),
    (2,'MySQL',10,'从删库到跑路'),
    (3,'Linux',5,'从进门到进牢');
    
  2. 导入依赖(看常用配置文件)

  3. 资源文件导出问题(看常用配置文件)

2. 编写Model层

  1. 编写db.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
    
  2. 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.iandf.pojo"/>
        </typeAliases>
    
        <mappers>
            <mapper class="com.iandf.dao.BooksMapper"/>
        </mappers>
    </configuration>
    
  3. 编写实体类

    public class Books {
        private int bookID;
        private String bookName;
        private int bookCounts;
        private  String detail;
    }
    
  4. 编写Mapper接口

    public interface BooksMapper {
        //添加一本书
        int addBooks(Books books);
        //删除一本书
        int deleteBooksByID(@Param("bookID") int id);
        //更新一本书
        int updateBooks(Books books);
        //查询一本书
        Books queryBooksByID(@Param("bookID") int id);
        //查询所有书
        List<Books> getBooksList();
    }
    
  5. 编写mapper.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.iandf.dao.BooksMapper">
        <insert id="addBooks" parameterType="books">
            insert into ssmbuild.books(bookID, bookName, bookCounts, detail)
            VALUES (#{bookID},#{bookName},#{bookCounts},#{detail})
        </insert>
        <delete id="deleteBooksByID" parameterType="_int">
            delete from ssmbuild.books where bookID = #{bookID};
        </delete>
        <update id="updateBooks" parameterType="books">
            update ssmbuild.books
            set bookCounts = #{bookCounts},bookName = #{bookName},bookCounts = #{bookName}
            where bookID = #{bookID}
        </update>
        <select id="queryBooksByID" parameterType="_int" resultType="books">
            select * from ssmbuild.books where bookID = #{bookID}
        </select>
        <select id="getBooksList" resultType="books">
            select * from ssmbuild.books
        </select>
    </mapper>
    
  6. spring-dao.xml中注册sqlSessionTemplate

    <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
            <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"/>
    </bean>
    
  7. 使用SqlSessionDaoSupport编写BooksMapper的实现类

    public class BooksMapperImpl extends SqlSessionDaoSupport implements BooksMapper{
        public BooksMapperImpl() {
    
        }
    
        @Override
        public int addBooks(Books books) {
            return getSqlSession().getMapper(BooksMapper.class).addBooks(books);
        }
    
        @Override
        public int deleteBooksByID(int id) {
            return getSqlSession().getMapper(BooksMapper.class).deleteBooksByID(id);
        }
    
        @Override
        public int updateBooks(Books books) {
            return getSqlSession().getMapper(BooksMapper.class).updateBooks(books);
        }
    
        @Override
        public Books queryBooksByID(int id) {
            return getSqlSession().getMapper(BooksMapper.class).queryBooksByID(id);
        }
    
        @Override
        public List<Books> getBooksList() {
            return getSqlSession().getMapper(BooksMapper.class).getBooksList();
        }
    }
    
  8. 在spring-dao.xml中注册BooksMapperImpl

    <bean id="booksMapperImpl" class="com.iandf.dao.BooksMapperImpl">
            <property name="sqlSessionTemplate" ref="sqlSessionTemplate"/>
    </bean>
    

3. 编写service层

  1. 编写service层接口

    public interface BooksService {
        //添加一本书
        int addBooks(Books books);
        //删除一本书
        int deleteBooksByID( int id);
        //更新一本书
        int updateBooks(Books books);
        //查询一本书
        Books queryBooksByID(int id);
        //查询所有书
        List<Books> getBooksList();
    }
    
  2. 编写service接口的实现类持有dao层的对象

    public class BooksServiceImpl implements BooksService {
        private final BooksMapper booksMapper;
    
        public BooksServiceImpl(BooksMapper booksMapper) {
            this.booksMapper = booksMapper;
        }
    
        @Override
        public int addBooks(Books books) {
            return booksMapper.addBooks(books);
        }
    
        @Override
        public int deleteBooksByID(int id) {
            return booksMapper.deleteBooksByID(id);
        }
    
        @Override
        public int updateBooks(Books books) {
            return booksMapper.updateBooks(books);
        }
    
        @Override
        public Books queryBooksByID(int id) {
            return booksMapper.queryBooksByID(id);
        }
    
        @Override
        public List<Books> getBooksList() {
            return booksMapper.getBooksList();
        }
    }
    
  3. 编写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
           http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
        <context:component-scan base-package="com.iandf.service"/>
        
        <bean class="com.iandf.service.BooksServiceImpl" id="booksService">
            <constructor-arg name="booksMapper" ref="booksMapperImpl"/>
        </bean>
    
        
    </beans>
    

4. 整合spring-mvc

  1. 添加web框架支持

  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">
        <!--DispatcherServlet-->
        <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>
        
        <!--encodingFilter-->
        <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>
    
  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
           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.开启注解驱动支持-->
        <mvc:annotation-driven/>
        <!--2.不过滤静态资源访问-->
        <mvc:default-servlet-handler/>
        <!--3.配置视图解析器-->
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix" value="/WEB-INF/jsp/"/>
            <property name="suffix" value=".jsp"/>
        </bean>
        <!-- 4.扫描web相关的bean -->
        <context:component-scan base-package="com.iandf.controller" />
    </beans>
    
  4. 把spring-dao.xml spring_service.xml spring_mvc.xml整合到applicationContext.xml中

    <import resource="spring-dao.xml"/>
    <import resource="spring_service.xml"/>
    <import resource="spring_mvc.xml"/>
    

配置文件到此结束

5. 实现书籍的增删改查

5.1 展示所有书籍

  1. allBooks.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>
            </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('booksList')}">
                        <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>
    
  2. BooksController

    @RequestMapping("/allBook")
    public String getBooksList(Model model){
        List<Books> booksList = booksService.getBooksList();
        model.addAttribute("booksList",booksList);
        return "allBooks";
    }
    

5.2 添加书籍

  1. allBooks.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>
    
  2. BooksController

    @RequestMapping("/toAddBook")
    public String toAddPaper() {
        return "addBook";
    }
    
    @RequestMapping("/addBook")
    public String addPaper(Books books) {
        System.out.println(books);
        booksService.addBooks(books);
        return "redirect:/book/allBook";
    }
    

5.3 修改书籍

  1. 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()}"/>
            书籍数量:<input type="text" name="bookCounts" value="${book.getBookCounts()}"/>
            书籍详情:<input type="text" name="detail" value="${book.getDetail()}"/>
            <input type="submit" value="提交"/>
        </form>
    
    </div>
    
  2. BooksController

    @RequestMapping("/toUpdateBook")
    public String roUpdateBook(Model model,int id){
        Books books = booksService.queryBooksByID(id);
        model.addAttribute("book",books);
        return "updateBook";
    }
    
    @RequestMapping("/updateBook")
    public String updateBook(Books book){
        booksService.updateBooks(book);
        return "redirect:/book/allBook";
    }
    

5.4 删除书籍

  1. BooksController

    @RequestMapping("/del/{bookID}")
    public String deleteBook(@PathVariable("bookID") int id){
        booksService.deleteBooksByID(id);
        return "redirect:/book/allBook";
    }
    
上一篇:求整数序列中出现次数最多的数


下一篇:对darknet源码进行修改,改变保存模型的步数及命名