zoukankan      html  css  js  c++  java
  • SSM整合——实现书籍的增删改查

    ssm整合

    1、前提准备工作

    数据库

    CREATE DATABASE `ssmbuild`;
    USE ssmbuild;
    CREATE TABLE `books` (
        `bookid` INT(10) NOT NULL AUTO_INCREMENT COMMENT '书id',
        `bookname` VARCHAR(100) NOT NULL COMMENT '书名',
        `bookcount` INT(11) NOT NULL COMMENT '数量',
        `dateail` VARCHAR(200) NOT NULL COMMENT '描述',
         KEY `bookid` (`bookid`)
        )ENGINE=INNODB DEFAULT CHARSET=utf8;
    
    INSERT INTO books VALUE(1,'java',1,'从入门到放弃'),(2,'mysql',10,'从删除到跑路'),(3,'python',5,'从入门到大神');

    pom.xml(相关的iar导入和静态资源导入)

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.4</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.23</version>
        </dependency>
        <!--数据库连接池-->
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.5</version>
        </dependency>
        <!--jsp-->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.6</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.6</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.3.4</version>
        </dependency>
         <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <version>1.18.18</version>
            </dependency>
    </dependencies>
    <!--静态资源导入-->
    <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>

    连接数据库mysql,

    ssm整合mybatis层

     1、配置文件的编写    

    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>
    
        <mappers>
            ><mapper resource="mapper/BookMapper.xml"/>
        </mappers>
    
    </configuration>

    applicationContext.xml

    <?xml version="1.0" encoding="UTF-8" ?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:context="http://www.springframework.org/schema/context"
           xmlns:mvc="http://www.springframework.org/schema/mvc"
           xmlns:p="http://www.springframework.org/schema/p"
           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-4.0.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
            http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xs">
    </beans>

    database.properties 连接数据库,数据源

    jdbc.driver=com.mysql.cj.jdbc.Driver
    #如果使用的mysql8.0+ ,就要增加时区的配置:&serverTimezone=CMT
    jdbc.url=jdbc:mysql://localhost:3306/ssmbulid?useSSL=true&useUnicode=true&characterEncoding=utf8
    jdbc.username=root
    jdbc.password=123456

    2、创建pojo包,dao包,controller包,service包

    Books.java 实体类pojo

    package com.zy.pojo;
    import lombok.AllArgsConstructor;
    import lombok.Data;
    import lombok.NoArgsConstructor;
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class Books {
        private int bookid;
        private String bookname;
        private int bookcount;
        private String dateail;
    }

    BooksMapper.java 实体接口dao包

    package com.zy.dao;
    
    import com.zy.pojo.Books;
    import org.apache.ibatis.annotations.Param;
    import java.util.List;
    public interface BookMapper {
        //增加一本书
        int addbook(Books books);
        //删除一本书
        int deletebook(@Param("bookid") int id);
        //更新一本书
        int updatebook(Books books);
        //查询一本书
        Books selectbook(@Param("bookid") int id);
        //查询全部书
        List<Books> allbook();
    }

    对应的 BooksMapper.java接口的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.zy.dao.BookMapper">
        <insert id="addbook" parameterType="com.zy.pojo.Books">
            insert into books(bookname,bookcount,dateail)
            values (#{bookname},#{bookcount},#{dateail})
        </insert>
        <delete id="deletebook" parameterType="int">
            delete from books where bookid=#{bookid}
        </delete>
        <update id="updatebook" parameterType="com.zy.pojo.Books">
            update books set bookname=#{bookname},bookcount=#{bookcount},dateail=#{dateail}
             where bookid=#{bookid} ;
        </update>
        <select id="selectbook" resultType="com.zy.pojo.Books">
            select * from books where id=#{bookid}
        </select>
        <select id="allbook" resultType="com.zy.pojo.Books">
            select * from books
       </select>
    </mapper>

    BookService .java service层,用于调用dao层

    package com.zy.service;
    
    import com.zy.pojo.Books;
    import org.apache.ibatis.annotations.Param;
    
    import java.util.List;
    @service
    public interface BookService {
        //增加一本书
        int addbook(Books books);
        //删除一本书
        int deletebook( int id);
        //更新一本书
        int updatebook(Books books);
        //查询一本书
        Books selectbook(int id);
        //查询全部书
        List<Books> allbook();
    }

    对应的BookService .java接口的xml文件

    package com.zy.service;
    
    import com.zy.dao.BookMapper;
    import com.zy.pojo.Books;
    
    import java.util.List;
    
    public class BookServiceImpl implements BookService{
        //server调用dao层,组合dao
        private BookMapper bookMapper;
        public void setBookMapper(BookMapper bookMapper){
            this.bookMapper=bookMapper;
        }
        @Override
        public int addbook(Books books) {
            return bookMapper.addbook(books);
        }
    
        @Override
        public int deletebook(int id) {
            return bookMapper.deletebook(id);
        }
    
        @Override
        public int updatebook(Books books) {
            return bookMapper.updatebook(books);
        }
    
        @Override
        public Books selectbook(int id) {
            return bookMapper.selectbook(id);
        }
    
        @Override
        public List<Books> allbook() {
            return bookMapper.allbook();
        }
    }

    ssm整合spring层

    编写spring相关的配置文件,

    spring-dao.xml

    <?xml version="1.0" encoding="UTF-8" ?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:context="http://www.springframework.org/schema/context"
           xmlns:mvc="http://www.springframework.org/schema/mvc"
           xmlns:p="http://www.springframework.org/schema/p"
           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-4.0.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
            http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xs">
            <!--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"/>
                    <!--关闭连接后不自动commint-->
                    <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>
    
            <!--配置到接口的扫描包,动态的实现了到接口可以注入到spring容器中-->
            <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
                <!--注入salSessionFactory-->
                <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
                <!--要扫描的dao包-->
                <property name="basePackage" value="com.zy.dao"/>
    
            </bean>
    </beans>

    spring-service.xml

    <?xml version="1.0" encoding="UTF-8" ?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:context="http://www.springframework.org/schema/context"
           xmlns:mvc="http://www.springframework.org/schema/mvc"
           xmlns:p="http://www.springframework.org/schema/p"
           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-4.0.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
            http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xs">
    
        <!--1、扫描service下的包-->
        <context:component-scan base-package="com.zy.service"/>
    
        <!--2、将我们的所有业务类,注入到spring,可以通过配置或者通过注解实现-->
        <bean id="BookServiceImpl" class="com.zy.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>

    applicationContext.xml

    <?xml version="1.0" encoding="UTF-8" ?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:context="http://www.springframework.org/schema/context"
           xmlns:mvc="http://www.springframework.org/schema/mvc"
           xmlns:p="http://www.springframework.org/schema/p"
           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-4.0.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
            http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xs">
        
        <import resource="classpath:spring-dao.xml"/>
        <import resource="classpath:spring-service.xml"/>
    </beans>

    ssm整合springmvc层

    编写springmvc相关的配置文件,

    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>sprignmvc</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>-->
                 <param-value>classpath:com/zy/config/applicationContext.xml</param-value>
            </init-param>
            <load-on-startup>1</load-on-startup>
        </servlet>
        <servlet-mapping>
            <servlet-name>sprignmvc</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>

    spring-mvc.xml

    <?xml version="1.0" encoding="UTF-8" ?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:context="http://www.springframework.org/schema/context"
           xmlns:mvc="http://www.springframework.org/schema/mvc"
           xmlns:p="http://www.springframework.org/schema/p"
           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-4.0.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
            http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xs">
    
          <!--自动扫描包,让指定包下的注解生效,由IOC容器统一管理-->
        <context:component-scan base-package="com.zy.controller"/>
        <!--让spring mvc不处理静态资源-->
        <mvc:default-servlet-handler/>
        <!--支持mvc注解驱动
            在spring中一般采用@RequestMapping注解来完成映射关系
            要向使@RequestMapper注解生效
            必须向上下文中注册DefaultAnnotationHandlerMapping和一个
            AnnotationMethodHandlerAdapter实例
            这个两个实例分别在类级别和方法级别处理
            而annotation-driven配置帮助我们自动完成上述两个实例的注入-->
        <mvc:annotation-driven/>
        <!--4、视图解析器-->
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix" value="/WEB-INF/jsp/"/>
            <property name="suffix" value=".jsp"/>
        </bean>
    </beans>

    applicationContext.xml

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

    ssm整合:设置查询书籍功能

    BookController.java     编写controller的代码,

    package com.zy.controller;
    
    import com.zy.pojo.Books;
    import com.zy.service.BookService;
    import com.zy.service.BookServiceImpl;
    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.RequestMapping;
    
    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.allbook();
            model.addAttribute("list", list);
            return "allBook";
    
        }
    }

    编写前端代码

    index.jsp 首页

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
      <head>
        <title>首页</title>
        <style>
          h3{
            width: 180px;
            height: 38px;
            margin: 100px auto;
            text-align: center;
            line-height: 38px;
            background: skyblue;
            border-radius: 50px ;
          }
          a{
            text-decoration: none;
            color: black;
            font-size: 18px;
          }
        </style>
      </head>
      <body>
      <h3>
        <a href="${pageContext.request.contextPath}/book/allBook">进入书籍页面</a>
      </h3>
      </body>
    </html>

    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>
        <%--BootStrap美化界面--%>
    
        <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>
                        <samp>书籍列表---显示所有书籍</samp>
                    </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>
                    <tbody>
                        <%--书籍从数据库中查询出来,
                            从这个list中遍历出来:foreach--%>
                    <c:forEach var="book" items="${list}">
                        <tr>
                            <td>${book.bookid}</td>
                            <td>${book.bookname}</td>
                            <td>${book.bookcount}</td>
                            <td>${book.dateail}</td>
                        </tr>
                    </c:forEach>
                    </tbody>
                </table>
            </div>
        </div>
    
    </div>
    
    </body>
    </html>

    显示的结果为

    正在学习中,有错误的地方,请多多指教!
  • 相关阅读:
    java图片压缩 、图片缩放,区域裁剪,水印,旋转,保持比例。
    java树形菜单实现
    vue-resource的使用,前后端数据交互
    如何在IntelliJ IDEA中使用.ignore插件忽略不必要提交的文件
    Git以及TortoiseGit的下载安装使用
    springBoot总结
    idea如何设置类头注释和方法注释
    (document).height()与$(window).height()
    使用js对中文进行gbk编码
    JS中URL编码参数(UrlEncode)
  • 原文地址:https://www.cnblogs.com/16904985zy-aoyu/p/14637679.html
Copyright © 2011-2022 走看看