springmvc-ssm整合

6 篇文章 0 订阅
2 篇文章 0 订阅


本文将通过完整的书籍的增删改查进行程序的讲解,以便后续学习使用!如有不妥之处,还请小伙伴们指出,共同进步!
springmvc的整合将基于mybatis,然后通过spring,springmvc进行简化操作!!

一、整合mybatis

1、新建maven项目,然后导入相应的依赖

 <dependencies>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.12</version>
        </dependency>
        <!--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>
        <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
            <version>1.1.2</version>
        </dependency>
        <!--Mybatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.2</version>
        </dependency>

        <!--Spring-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.1.9.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.1.9.RELEASE</version>
        </dependency>
    </dependencies>
    <!--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>

2、根据对应的数据库建立对应的实体类

`ssmbuild``books`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,'从进门到进牢');

建立pojo包,然后建立对应的实体类Books

package com.zhou.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

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

}

3、建立核心配置文件

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>
    <!--由spring 接管-->
    <!--<properties resource="db.properties"/>-->
<typeAliases>
    <package name="com.zhou.pojo"/>
</typeAliases>
    <!--<environments default="development">-->
        <!--<environment id="development">-->
            <!--<transactionManager type="JDBC"/>-->
            <!--<dataSource type="POOLED">-->
                <!--<property name="driver" value="${driver}"/>-->
                <!--<property name="url" value="${url}"/>-->
                <!--<property name="username" value="${user}"/>-->
                <!--<property name="password" value="${password}"/>-->
            <!--</dataSource>-->
        <!--</environment>-->
    <!--</environments>-->
    <mappers>
        <mapper resource="com/zhou/mapper/BookMapper.xml"/>
    </mappers>
</configuration>

在此处注释掉的内容为后续mybatis测试数据库提供了一定的支持,后续由于有spring,则被spring接管,便被注释掉了!!
数据源文件:db.properties

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

此处注释是由于测试时,总说用户和密码的问题,为防止名字和一些参数混淆,所以直接在后面采用固定的写法,所以注释掉

4、编写mapper层与数据库对应的接口和xml文件

BookMapper

package com.zhou.mapper;

import com.zhou.pojo.Books;

import java.util.List;

public interface BookMapper {
   //查询全部书
    List<Books> getAllBooks();
    //根据id 查询书
    Books getBookByID(int id);
    //增加书籍
    int addBook(Books books);
    //根据id删除书籍
    int deleteBook(int id);
    //修改书籍
    int updateBook(Books books);

}

BookMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zhou.mapper.BookMapper">
<!--根据对应的接口编写对应的xml-->
    <select id="getAllBooks" resultType="Books">
        select * from ssmbuild.books
    </select>
    <select id="getBookByID" resultType="Books">
        select * from ssmbuild.books where bookID=#{id}
    </select>
    <!--主键会自增!!!-->
    <insert id="addBook" parameterType="Books">
        insert into ssmbuild.books(bookName,bookCounts,detail)values (#{bookName},#{bookCounts},#{detail});
    </insert>
    <delete id="deleteBook" parameterType="int">
        delete from ssmbuild.books where bookID=#{bookID}
    </delete>
    <update id="updateBook" parameterType="Books">
        update ssmbuild.books
        set bookName=#{bookName},bookCounts=#{bookCounts},detail=#{detail}
        where bookID=#{bookID}
    </update>
</mapper>

mybatis整合完毕,进行相应的测试:

 @org.junit.Test
    public void Test1() throws IOException {
       // InputStream is = BookMapper.class.getClassLoader().getResourceAsStream("db.properties");
      String resource="mybatis-config.xml";
        InputStream is = Resources.getResourceAsStream(resource);
        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);
        SqlSession sqlSession = sessionFactory.openSession();
        BookMapper bookMapper = sqlSession.getMapper(BookMapper.class);
        List<Books> allBooks = bookMapper.getAllBooks();
        for (Books allBook : allBooks) {
            System.out.println(allBook);
        }
    }

二、编写service层

在实际业务中,service是业务层,可以调用mapper层,故编写service层的接口和实现类,方便spring的接管
BookService

package com.zhou.service;

import com.zhou.pojo.Books;

import java.util.List;

public interface BookService {
    //查询全部书
    List<Books> getAllBooks();
    //根据id 查询书
    Books getBookByID(int id);
    //增加书籍
    int addBook(Books books);
    //根据id删除书籍
    int deleteBook(int id);
    //修改书籍
    int updateBook(Books books);
}

BookServiceImpl

import java.util.List;
   @Service
public class BookServiceImpl implements BookService {
    @Autowired//自动将bean注入
   private BookMapper bookMapper;
    public List<Books> getAllBooks() {
        List<Books> allBooks = bookMapper.getAllBooks();
        return allBooks;
    }

    public Books getBookByID(int id) {
        return bookMapper.getBookByID(id);
    }

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

    public int deleteBook(int id) {
        return bookMapper.deleteBook(id);
    }

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

此处采用注解的方式,将mapper层的对应bean进行注入,简单高效!

三、spring整合

在这里将写四个配置文件:

applicationContext.xml 引入其他三个
spring-mapper.xml
spring-mvc.xml
spring-service.xml

spring-mapper.xml:需要引入数据元的配置文件,定义数据库连接池,获得sqlSession,方便操作直接数据库

<?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:property-placeholder location="classpath:db.properties"/>
    <!-- 2.数据库连接池 -->
    <!--数据库连接池
dbcp  半自动化操作  不能自动连接
c3p0  自动化操作(自动的加载配置文件 并且设置到对象里面)
    -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <!-- 配置连接池属性 -->
        <property name="driverClass" value="${driver}"/>
        <property name="jdbcUrl" value="${url}"/>
        <property name="user" value="root"/>
        <property name="password" value="123456"/>

        <!-- 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>
    <!--sessionFactory-->
    <bean class="org.mybatis.spring.SqlSessionFactoryBean" id="sessionFactory">
        <property name="dataSource" ref="dataSource"/>
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
    </bean>

    <!--session-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer" id="mapperScannerConfigurer">
        <property name="sqlSessionFactoryBeanName" value="sessionFactory"/>
        <property name="basePackage" value="com.zhou.mapper"/>
    </bean>
</beans>

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.zhou.service"/>
<!--<import resource="spring-mapper.xml"/>-->
    <bean class="com.zhou.service.BookServiceImpl">
        <!--<property name="bookMapper" ref="bookMapper"/>-->
    </bean>

    <!-- 配置事务管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- 注入数据库连接池 -->
        <property name="dataSource" ref="dataSource" />
    </bean>
</beans>

在此处进行了事务的配置,以及将mapper层的bean进行了注册,并且开启了自动扫描service层的包。

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: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">

    <!--扫描相关的bean-->
    <context:component-scan base-package="com.zhou.controller"/>
    <!--开启注解驱动-->
    <mvc:default-servlet-handler/>
    <mvc:annotation-driven/>
<!--<import resource="spring-service.xml"/>-->
    <!--视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
    <bean class="com.zhou.service.BookServiceImpl" id="bookService"/>
</beans>

此处的整合可以详细参考springmvc的博客
博客地址
applicationContext.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <import resource="spring-mapper.xml"/>
    <import resource="spring-mvc.xml"/>
    <import resource="spring-service.xml"/>
</beans>

四、springmvc整合

在这里必须将项目添加web的支持
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>
 <!--<param-value>classpath:spring-mvc.xml</param-value>-->
  </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>DispatcherServlet</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>

注意此处关联的配置文件为:applicationContext.xml
编写controller层
Bookcontroller

package com.zhou.controller;

import com.zhou.pojo.Books;
import com.zhou.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
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 {
    @Autowired
    private BookService bookService;

    @RequestMapping("/allbook")
    public String allbook(Model model) {
        System.out.println("Bookcontroller进来了");

        List<Books> list = bookService.getAllBooks();
        model.addAttribute("list",list);
        System.out.println(list);
        return "allBooks";
    }
   // 新增书籍
   @RequestMapping("/toaddBook")
   public String toaddBook(){
       return "addBook";
   }
    @RequestMapping("/addBookget")
    public String addBook(Books book){
        //注意是从前台获得增加的书籍,添加到后台
         bookService.addBook(book);
        System.out.println("增加的书:"+book);
        return "redirect:/book/allbook";
    }
    //修改书籍  携带书的id进行跳转
    @RequestMapping("/toupdateBook")
    public String toupdate(int id,Model model){
        //根据书的id进行查询
        Books book = bookService.getBookByID(id);
        System.out.println("修改的书籍为:"+book);
        model.addAttribute("updatebook",book);
        return "updateBook";
    }
    @RequestMapping("/updateBookget")
    public String update(Books book){
        bookService.updateBook(book);
       Books book1 = bookService.getBookByID(book.getBookID());
//        model.addAttribute("book1",book1);
        System.out.println("修改好的书籍为:"+book1);
        return "redirect:/book/allbook";
    }
//删除书籍
    @RequestMapping("/deleteBook")
    public String delete(int id){
        int i = bookService.deleteBook(id);
        System.out.println("删除的书籍"+i);
        return "redirect:/book/allbook";
    }
}

此处是书籍增删改查全部执行程序,接下来分开详细进行介绍,注意开程序编写时,要多进行调试,确实程序没有问题,才接着往下写!!

五、书籍的增删改查–前端和后端结合

index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>书籍列表</title>
  </head>
  <body>
  <a href="${pageContext.request.contextPath}/book/allbook">点击进入列表</a>
  </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>

</head>
<div style=" width:100% " >
    <table>
        <thead >
        <tr>
            <td>书籍编号</td>
            <td>书籍名称</td>
            <td>书籍数量</td>
            <td>书籍详情</td>
            <td>
                <a href="${pageContext.request.contextPath}/book/toaddBook">新增</a>

            </td>
        </tr>
        </thead>
        <tbody>
        <c:forEach var="book" items="${list}">
            <tr>
                <td>${book.bookID}</td>
                <td>${book.bookName}</td>
                <td>${book.getBookCounts()}</td>
                <td>${book.getDetail()}</td>
                <td>
                    <a href="${pageContext.request.contextPath}/book/toupdateBook?id=${book.bookID}">更改</a>
                    <a href="${pageContext.request.contextPath}/book/deleteBook?id=${book.bookID}">删除</a>
                </td>
            </tr>
        </c:forEach>
        </tbody>

    </table>
</div>

<body>

</body>
</html>

此处由于要循环遍历,所以引入了标签库
在这里插入图片描述
在这里插入图片描述
新增书籍:
在这里插入图片描述
addBook.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>新增书籍</title>

</head>
<body>
<form action="${pageContext.request.contextPath}/book/addBookget">
    书籍名称:<input type="text" name="bookName"><br>
    书籍数量:<input type="text" name="bookCounts"><br>
    书籍详情:<input type="text" name="detail"><br>
    <input type="submit" value="添加">
</form>
</body>
</html>

通过表单进行提交,由于id可以自增,所以不需要管!!
在这里插入图片描述
修改书籍
updateBook.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>修改书籍</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/book/updateBookget">
    
    <input type="hidden" name="bookID" value="${updatebook.getBookID()}">
    书籍名称:<input type="text" name="bookName" value="${updatebook.getBookName()}"><br>
    书籍数量:<input type="text" name="bookCounts"value="${updatebook.getBookCounts()}"><br>
    书籍详情:<input type="text" name="detail"value="${updatebook.getDetail()}"><br>
    <input type="submit" value="修改">
</form>
</body>
</html>

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
删除书籍:
删除书籍不需要进行页面跳转,所以直接在控制层根据id删除即可
在这里插入图片描述
以上就是项目的整体程序以及运行结果!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值