SpringMVC——整合SSM

SpringMVC——整合SSM

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

SpringMVC——整合SSM_第1张图片

2.基本环境搭建

  1. 新建一个Maven项目(命名为:ssm-01)!,并添加web支持。

  2. 先按照下面的目录图建立各种文件

    SpringMVC——整合SSM_第2张图片

    SpringMVC——整合SSM_第3张图片

  3. 导入相关的pom依赖

<dependencies>

    
    <dependency>
        <groupId>org.projectlombokgroupId>
        <artifactId>lombokartifactId>
        <version>1.18.10version>
        <scope>providedscope>
    dependency>

    
    <dependency>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-properties-migratorartifactId>
        <version>2.2.2.RELEASEversion>
    dependency>
    
    <dependency>
        <groupId>junitgroupId>
        <artifactId>junitartifactId>
        <version>4.12version>
    dependency>
    
    <dependency>
        <groupId>mysqlgroupId>
        <artifactId>mysql-connector-javaartifactId>
        <version>5.1.47version>
    dependency>
    
    <dependency>
        <groupId>com.mchangegroupId>
        <artifactId>c3p0artifactId>
        <version>0.9.5.2version>
    dependency>

    
    <dependency>
        <groupId>javax.servletgroupId>
        <artifactId>servlet-apiartifactId>
        <version>2.5version>
    dependency>
    <dependency>
        <groupId>javax.servlet.jspgroupId>
        <artifactId>jsp-apiartifactId>
        <version>2.2version>
    dependency>
    <dependency>
        <groupId>javax.servletgroupId>
        <artifactId>jstlartifactId>
        <version>1.2version>
    dependency>

    
    <dependency>
        <groupId>org.mybatisgroupId>
        <artifactId>mybatisartifactId>
        <version>3.5.2version>
    dependency>
    <dependency>
        <groupId>org.mybatisgroupId>
        <artifactId>mybatis-springartifactId>
        <version>2.0.2version>
    dependency>

    
    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-webmvcartifactId>
        <version>5.1.9.RELEASEversion>
    dependency>
    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-jdbcartifactId>
        <version>5.1.9.RELEASEversion>
    dependency>
dependencies>
  1. Maven资源过滤设置
<build>
    <resources>
        <resource>
            <directory>src/main/javadirectory>
            <includes>
                <include>**/*.propertiesinclude>
                <include>**/*.xmlinclude>
            includes>
            <filtering>falsefiltering>
        resource>
        <resource>
            <directory>src/main/resourcesdirectory>
            <includes>
                <include>**/*.propertiesinclude>
                <include>**/*.xmlinclude>
            includes>
            <filtering>falsefiltering>
        resource>
    resources>
build>
  1. 建立基本结构和配置框架
  • com.cm.pojo

  • com.cm.dao

  • com.cm.service

  • com.cm.controller

  • mybatis-config.xml



<configuration>

configuration>
  • applicationContext.xml

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

beans>

3.Mybatis层编写

  1. 数据库配置文件 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
  1. IDEA关联数据库

  2. 编写MyBatis的核心配置文件

    
    
    <configuration>
        
        <typeAliases>
            <package name="com.kuang.pojo"/>
        typeAliases>
        <mappers>
            <mapper resource="com/kuang/dao/BookMapper.xml"/>
        mappers>
    
    configuration>
    
  3. 编写数据库对应的实体类 com.kuang.pojo.Books

    使用lombok插件!

    package com.cm.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;
    }
    
  4. 编写dao层的 BookMapper接口!

    package com.cm.dao;
    
    import com.cm.pojo.Books;
    
    import java.util.List;
    
    public interface BookMapper {
           
    
        //增加一个Book
        int addBook(Books book);
    
        //根据id删除一个Book
        int deleteBookById(int id);
    
        //更新Book
        int updateBook(Books books);
    
        //根据id查询,返回一个Book
        Books queryBookById(int id);
    
        //查询全部Book,返回list集合
        List<Books> queryAllBook();
    
        // 根据书名查询数据
        Books queryBooksByName(String bookName);
    }
    
  5. 编写接口对应的 BookMapper.xml 文件,需要导入MyBatis的包!

    
    
    
    <mapper namespace="com.cm.dao.BookMapper">
    
        
        <insert id="addBook" parameterType="Books">
            insert into ssmbuild.books(bookName,bookCounts,detail)
            values (#{bookName}, #{bookCounts}, #{detail})
        insert>
    
        
        <delete id="deleteBookById" 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>
    
        
        <select id="queryBookById" resultType="Books">
            select * from ssmbuild.books
            where bookID = #{bookID}
        select>
    
        
        <select id="queryAllBook" resultType="Books">
            SELECT * from ssmbuild.books
        select>
    
        
        <select id="queryBooksByName" resultType="Books">
            select * from ssmbuild.books where bookName = #{bookName}
        select>
    mapper>
    
  6. 编写Service层的接口和实现类

    接口:
    package com.cm.service;
    
    import com.cm.pojo.Books;
    
    import java.util.List;
    
    //BookService:底下需要去实现,调用dao层
    public interface BookService {
           
        //增加一个Book
        int addBook(Books book);
        //根据id删除一个Book
        int deleteBookById(int id);
        //更新Book
        int updateBook(Books books);
        //根据id查询,返回一个Book
        Books queryBookById(int id);
        //查询全部Book,返回list集合
        List<Books> queryAllBook();
        // 根据书名查询数据
        Books queryBooksByName(String bookName);
    }
    
    实现类:
    package com.cm.service;
    
    import com.cm.dao.BookMapper;
    import com.cm.pojo.Books;
    
    import java.util.List;
    
    public class BookServiceImpl implements BookService {
           
    
        //调用dao层的操作,设置一个set接口,方便Spring管理
        private BookMapper bookMapper;
    
        public void setBookMapper(BookMapper bookMapper) {
           
            this.bookMapper = bookMapper;
        }
    
        public int addBook(Books book) {
           
            return bookMapper.addBook(book);
        }
    
        public int deleteBookById(int id) {
           
            return bookMapper.deleteBookById(id);
        }
    
        public int updateBook(Books books) {
           
            return bookMapper.updateBook(books);
        }
    
        public Books queryBookById(int id) {
           
            return bookMapper.queryBookById(id);
        }
    
        public List<Books> queryAllBook() {
           
            return bookMapper.queryAllBook();
        }
    
        public Books queryBooksByName(String bookName) {
           
            return bookMapper.queryBooksByName(bookName);
        }
    }
    

4.编写Spring层

  1. 配置Spring整合MyBatis,我们这里数据源使用c3p0连接池

  2. 编写Spring整合Mybatis的相关的配置文件: spring-dao.xml

    
    <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: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}"/>
    
            
            <property name="maxPoolSize" value="30"/>
            <property name="minPoolSize" value="10"/>
            
            <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"/>
            
            <property name="configLocation" value="classpath:mybatis-config.xml"/>
        bean>
    
        
        
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            
            <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
            
            <property name="basePackage" value="com.cm.dao"/>
        bean>
    
    beans>
    
  3. Spring整合service

    
    <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:component-scan base-package="com.cm.service" />
        <import resource="spring-dao.xml"/>
    
    
        
        <bean id="BookServiceImpl" class="com.cm.service.BookServiceImpl">
            <property name="bookMapper" ref="bookMapper"/>
        bean>
    
    
        
        <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
            
            <property name="dataSource" ref="dataSource" />
    bean>
    

5.SpringMVC层

  1. web.xml

    
    <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">
    
        
        <servlet>
            <servlet-name>DispatcherServletservlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
            <init-param>
                <param-name>contextConfigLocationparam-name>
                <param-value>classpath:applicationContext.xmlparam-value>
            init-param>
            <load-on-startup>1load-on-startup>
        servlet>
        <servlet-mapping>
            <servlet-name>DispatcherServletservlet-name>
            <url-pattern>/url-pattern>
        servlet-mapping>
    
        
        <filter>
            <filter-name>encodingFilterfilter-name>
            <filter-class>
                org.springframework.web.filter.CharacterEncodingFilter
            filter-class>
            <init-param>
                <param-name>encodingparam-name>
                <param-value>utf-8param-value>
            init-param>
        filter>
        <filter-mapping>
            <filter-name>encodingFilterfilter-name>
            <url-pattern>/*url-pattern>
        filter-mapping>
    
        
        <session-config>
            <session-timeout>15session-timeout>
        session-config>
    
    web-app>
    
  2. spring-mvc.xml

    
    <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/>
    
        
        <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>
    
        
        <context:component-scan base-package="com.cm.controller" />
    
    beans>
    
  3. Spring配置整合文件,applicationContext.xml

    
    <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/spring-dao.xml"/>
        <import resource="spring/spring-service.xml"/>
        <import resource="spring/spring-mvc.xml"/>
    
    beans>
    

6.编写 Controller 和 视图层

  1. Controller

    package com.cm.controller;
    
    import com.cm.pojo.Books;
    import com.cm.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 javax.servlet.http.HttpServletRequest;
    import java.util.ArrayList;
    import java.util.List;
    
    /*https://blog.kuangstudy.com*/
    
    @Controller
    @RequestMapping("/book")
    public class BookController {
           
    
        @Autowired
        @Qualifier("BookServiceImpl")
        private BookService bookService;
    
        @RequestMapping("/allBook")
        public String list(Model model) {
           
            List<Books> list = bookService.queryAllBook();
            model.addAttribute("list", list);
            return "allBook";
        }
    
        /*进入更改,给updateBook传递id这个参数*/
        @RequestMapping("/toUpdateBook")
        public String toUpdateBook(Model model, int id) {
           
            Books books = bookService.queryBookById(id);
            System.out.println(books);
            model.addAttribute("book", books);
            return "updateBook";
        }
    
        @RequestMapping("updateBook")
        public String updateBook(Model model, Books book) {
           
            System.out.println(book);
            bookService.updateBook(book);
            Books books = bookService.queryBookById(book.getBookID());
            model.addAttribute("books", books);
            return "redirect:/book/allBook";
        }
    
        @RequestMapping("/toAddBook")
        public String toAddBook() {
           
            return "addBook";
        }
    
        @RequestMapping("/addBook")
        public String addBook(Books books) {
           
            System.out.println(books);
            bookService.addBook(books);
            return "redirect:/book/allBook";
        }
    
        @RequestMapping("/del/{bookId}")
        public String deleteBook(@PathVariable("bookId") int id) {
           
            bookService.deleteBookById(id);
            return "redirect:/book/allBook";
        }
    
        @RequestMapping("/queryBook")
        public String queryBook(String queryBookName, Model model) {
           
            System.out.println("要查询的数据名称" + queryBookName);
            Books books = bookService.queryBooksByName(queryBookName);
            List<Books> list = new ArrayList<Books>();
    
            if(books == null) {
           
                model.addAttribute("error", "没有找到这本书");
                list = bookService.queryAllBook();
            }else {
           
                list.add(books);
                model.addAttribute("list", list);
            }
            return "allBook";
        }
    
        @RequestMapping("/login")
        public String login(String username, String password, HttpServletRequest request) {
           
            if(username.equals("张三") && password.equals("123456")) {
           
                System.out.println("用户名:"+username+"\t密码:"+password);
                request.setAttribute("username", username);
                request.setAttribute("password", password);
    
                return "allBook";
            }else {
           
                request.setAttribute("error", "用户名或密码不正确!");
                return "false";
            }
        }
    }
    
  2. 视图层

    index.jsp

    <%@ page language="java" contentType="text/html; charset=utf-8"
             pageEncoding="utf-8"%>
    
    
    
        
        Insert title here
    
    
    


    login.jsp

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    
    
        Title
    
    
    

    用户名:

    密码:

    false.jsp

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    
    
        登录失败
    
    
        

    ${error}

    allBook.jsp

    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    
    
        书籍列表
        
        
        
    
    
    
    
    <% String name = (String)request.getAttribute("username"); String pwd = (String)request.getAttribute("password"); %>

    用户名:<%=name %>

    密码:<%=pwd %>

    书籍编号 书籍名字 书籍数量 书籍详情 操作
    ${book.getBookID()} ${book.getBookName()} ${book.getBookCounts()} ${book.getDetail()} 更改 | 删除

    addBook.jsp

    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    
    
    
        新增书籍
        
        
        
    
    
    
    书籍名称:


    书籍数量:


    书籍详情:


    updateBook.jsp

    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    
    
        修改信息
        
        
        
    
    
    
    书籍名称: 书籍数量: 书籍详情:

小结

这个是我的第一个SSM整合案例;这里只实现了增删改查的基本操作。

你可能感兴趣的:(spring,java,mybatis,mysql,mvc)