Spring Boot 整合 Spring MVC的基本步骤

Spring Boot 整合Spring MVC 过程

关系图:
image.png
image.png
image.png
image.png
这种关系图的程序代码的书写代码的顺序是从右边往左边写!
要理解Spring MVC 的操作理解:
做这些用到了mybatis 的整合,这样简化了jdbc连接数据库的操作
下面是书写的代码:
-- Application.properties

close banner

spring.main.banner-mode=off

Spring DateSource

spring.datasource.url=jdbc:mysql:///dbgoods?serverTimezone=GMT%2B8&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=root

spring mybatis

mybatis.mapper-locations=classpath:/mapper/goods/GoodsMapper.xml

spring log

logging.level.com.cy=debug

server

server.port=80
server.servlet.context-path=/binbin

spring thymleaf

spring.thymeleaf.prefix=classpath:/templates/pages/
spring.thymeleaf.suffix=.html
spring.thymeleaf.cache=false
--GoodsMapper.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.cy.pj.goods.dao.GoodsDao">
<delete id="deleteObjects">

   delete from tb_goods
   where id in <!-- (1,2,3,4,5) -->
   <foreach collection="ids"
            open="("
            close=")"
            separator=","
            item="id">
           #{id}
   </foreach>

</delete>
</mapper>
Goods.java
package com.cy.pj.goods.pojo;

import java.util.Date;

public class Goods {

 private Long id;//id bigint primary key auto_increment
 private String name;//name varchar(100) not null
 private String remark;//remark text
 private Date createdTime;//createdTime datetime
public Long getId() {
    return id;
}
public void setId(Long id) {
    this.id = id;
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public String getRemark() {
    return remark;
}
public void setRemark(String remark) {
    this.remark = remark;
}
public Date getCreatedTime() {
    return createdTime;
}
public void setCreatedTime(Date createdTime) {
    this.createdTime = createdTime;
}
@Override
public String toString() {
    return "Goods [id=" + id + ", name=" + name + ", remark=" + remark + ", createdTime=" + createdTime + "]";
}
 

}
GoodsDao(interface)
package com.cy.pj.goods.dao;

import java.util.List;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
/*

  • @Mapper 用于描述(做标记)数据层访问接口,用于告诉mybatis框架,
    使用此注解描述的接口为底层创建实现类,在实现类中基于mybatis API 实现与数据库的交互
    这个类的对象最后 交给spring来管理
    */

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import com.cy.pj.goods.pojo.Goods;

@Mapper
public interface GoodsDao {

@Select("select * from tb_goods")
List<Goods>findGoods();
/**
 *     基于id执行商品信息的删除, 在mybatis中假如sql映射比较简单
 *     可以直接以注解方法进行定义
 * @param id
 * @return
 */
/**
 * 基于id去查找商品信息
 * @param id
 * @return
 */
@Select("select * from tb_goods where id=#{id}")
Goods findById(Integer id);
@Update("update tb_goods set name=#{name},remark=#{remark} where id=#{id}")
int UpdateGoods(Goods goods);
@Delete("delete from tb_goods where id=#{id}")
int deleteById(Integer id);
/**
 *         基于多个id执行商品删除业务操作
 *         ids可变参数,用于接受传入的商品id值
 */
int deleteObjects(@Param("ids")Integer...ids);
@Insert("insert into tb_goods(name,remark,createdTime) values (#{name},#{remark},now())" )

int insertGoods(Goods goods);

}

GoodsService(interface)
package com.cy.pj.goods.service;

import java.util.List;

import com.cy.pj.goods.pojo.Goods;

/**

  • 商品模块的业务层接口,负责具体业务标准定义
  • @author Bin and Legend

*
*/
public interface GoodsService {

        Goods findById(Integer id);
        List<Goods>findGoods();
        int deleteById(Integer id);
        int saveGoods(Goods goods);    
        int UpdateGoods(Goods goods);

}
GoodsServiceImpl
package com.cy.pj.goods.service.impl;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
/**

  • 业务层对象,后续会在此对象中执行
  • 1)核心业务(例如 : 点击购买商品信息,要生成点单项信息,扣减库存 ...)
  • 2)扩展业务 (例如 :事务控制,权限控制,日志记录)

*/
import org.springframework.stereotype.Service;

import com.cy.pj.goods.dao.GoodsDao;
import com.cy.pj.goods.pojo.Goods;
import com.cy.pj.goods.service.GoodsService;

//@Deprecated

@Service//是一个特殊的@Component 也可以用@Component
public class GoodsServiceImpl implements GoodsService{


private static final Logger log = LoggerFactory.getLogger(GoodsServiceImpl.class);

@Autowired
private GoodsDao goodsdao;
@Override
public List<Goods> findGoods() {
    
    return goodsdao.findGoods();
}

@Override
public int saveGoods(Goods goods) {
    // TODO Auto-generated method stub
    goods.setCreatedTime(new Date());
    return goodsdao.insertGoods(goods);
}
@Override
public int deleteById(Integer id) {
        long t1 = System.currentTimeMillis();
        int rows = goodsdao.deleteById(id);
        long t2 = System.currentTimeMillis();
        log.info("deleteById execute time : {}",(t2-t1));
        System.out.println(log.getClass().getName());
    return rows;
}
@Override
public Goods findById(Integer id) {
    
    return goodsdao.findById(id);
}
    
@Override
public int UpdateGoods(Goods goods) {
    // TODO Auto-generated method stub
    return goodsdao.UpdateGoods(goods);
}

}
GoodsController
/**

*/
package com.cy.pj.goods.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
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 com.cy.pj.goods.pojo.Goods;
import com.cy.pj.goods.service.GoodsService;

/**

  • @author Bin and Legend

*
*/
@Controller
@RequestMapping("/goods/")
public class GoodsController {

//http://localhost/goods/doDeleteById?id=12
@Autowired
private  GoodsService goodsService;
//执行删除操作
@RequestMapping("doDeleteById/{id}")
public String doDeleteById(@PathVariable Integer id) {
    goodsService.deleteById(id);    
    return "redirect:/goods/doGoodsUI";
}

@RequestMapping("doGoodsAddUI")
public String doGoodsAddUI() {
    return "goods-add";
}
@RequestMapping("doGoodsUI")
public String doGoodsUI(Model model) {
    List<Goods> list = goodsService.findGoods();
    model.addAttribute("goods", list);
    return "goods";//view name
}
@RequestMapping("doSaveGoods")
public String doSaveGoods(Goods goods){
    goodsService.saveGoods(goods);
    return "redirect:/goods/doGoodsUI" ;
}
@RequestMapping("doUpdateGoods")
public String doUpdateGoods(Goods goods){
    goodsService.UpdateGoods(goods);
    return "redirect:/goods/doGoodsUI" ;
}
@RequestMapping("doFindById/{id}")
public String doFindById(@PathVariable Integer id,Model model) {
    Goods goods = goodsService.findById(id);
    model.addAttribute("goods", goods);
    return "goods-update";
}
    //FAQ?
    //返回的viewname会给谁?谁调用doGoodsController就给谁(DispatcherServelt)
    //谁负责解析viewname V
    //解析到的结果会响应到哪里
}

goods.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>The Goods Page</h1>
添加商品

id name remark createdTime operation
1 AAAAAAA AA.... 2020/08/31 delete update

</body>
</html>
goods-add.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">

    ul li {list-style-type: none}

</style>
</head>
<body>

<h1>The Goods Add page</h1>
<form th:action="@{/goods/doSaveGoods}" method="p">
    <ul>
        <li>name:
        <li><input type="text" name="name">
        <li>remark:
        <li><textarea rows="3" cols="30" name="remark"></textarea>
        <li><input type="submit" value="Save Goods">
    </ul>
</form>

</body>
</html>
goods-update.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">

    ul li {list-style-type: none}

</style>
</head>
<body>

<h1>The Goods Add page</h1>
<form th:action="@{/goods/doUpdateGoods}" method="p">
    <input type="hidden" name="id" th:value="${goods.id}">
    <ul>
        <li>name:
        <li><input type="text" name="name" th:value="${goods.name}">
        <li>remark:
        <li><textarea rows="3" cols="30" name="remark" th:text="${goods.remark}"></textarea>
        <li><input type="submit" value="Save Goods">
    </ul>
</form>

</body>
</html>
后面的是测试类的结果:
DateSourceTests.java
package com.cy.pj.common.datasource;

import java.sql.Connection;

import javax.sql.DataSource;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
public class DataSourceTests {

/*
 * FAQ? 
 * 请问dataSource对象在运行时指向的具体对象类型是什么 两种:
 * 一:对象。getclass()。getname();通过反射来找到指向的具体对象 二:通过debug测试来,将鼠标指向该连接就可以看到具体对象
 *  请问dataSource对象是有谁帮你创建的?spring框架(基于底层的基本配置)DataSourceAutoConfiguration
 */
    @Autowired
    private DataSource datasource;
    //测试通过数据源DataSource对象获取一个连接
    @Test
    public void testConnection() throws Exception {

// //输出datasource变量指向的对象的类型
// System.out.println(datasource.getClass().getName());//com.zaxxer.hikari.HikariDataSource

            //请问获取连接的过程你了解吗
        //第一次获取连接时会检测连接池是否存在,假如不存在则创建并初始化池
        //基于Driver对象创建与数据库的连接,并将连接放在池中
        //最后从池中返回用户的需要的连接
        Connection conn = datasource.getConnection();
            System.out.println(conn);
    }

}
GoodsDaoTests.java
package com.cy.pj.goods.dao;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import com.cy.pj.goods.dao.GoodsDao;

@SpringBootTest
public class GoodsDaoTests {

    /**    关联数据层接口,并由spring为其进行值的注入
     *     FAQ?
     * 1)GoodsDao指向的对象是谁,由谁创建?由谁管理
     * 2)GoodsDao指向的内部对象会做什么事情? 基于mybatis API进行会话操作
     */
    @Autowired
    private GoodsDao goodsdao;
    @Test
    void testDeleteId() {
        int rows = goodsdao.deleteById(1);
        System.out.println("rows=" + rows);
    }
    @Test
    void testDeleteObject() {
        int rows = goodsdao.deleteObjects(2,3);
        System.out.println("rows=" + rows);
    }

}
GoodsServiceTests.java
package com.cy.pj.goods.service;
import java.util.List;

/**

  • FAQ?
  • 什么是耦合? 耦合性(Coupling),也叫耦合度,是对模块间关联程度的度量。耦合的强弱取决于模块间接口的复杂性、调用模块的方式以及通过界面传送数据的多少。

*/
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import com.cy.pj.goods.pojo.Goods;

@SpringBootTest
public class GoodsServiceTests {

    @Autowired//has a
private GoodsService goodsService;
    @Test
    void testFindGoods() {
        List<Goods> list = goodsService.findGoods();
        for(Goods g:list) {
            System.out.println(g);
        }
    }
    @Test
void testDeleteById() {
    int rows = goodsService.deleteById(10);
    System.out.println("rows=" +rows );
}
    

}
这一次的所需要的依赖注入,来自pom.xml文件中体现:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.3.0.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.cy</groupId>
<artifactId>CGB-SBOOT-04</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>CGB-SBOOT-04</name>
<description>Demo project for Spring Boot</description>

<properties>
    <java.version>1.8</java.version>
</properties>

<dependencies>
<!-- 此依赖提供了HikariCP连接池 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>
       <!-- 负责数据库的的驱动程序 -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
    <!-- 添加mybatis starter 依赖(SpringBoot 在这个依赖下提供mybatis的自动配置 -->
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.3</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>org.junit.vintage</groupId>
                <artifactId>junit-vintage-engine</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

</project>

阅读 117

推荐阅读