请求处理过程![](https://i-blog.csdnimg.cn/blog_migrate/7572e54acccd91039771fb16ff371d75.png)
- 前端加载过程:
- 输入地址,先经过hosts文件进行解析:http://manage.leyou.com/#/item/brand——>http://127.0.0.1:80/#/item/brand
- 通过ip找到服务器地址(本机),进入80端口,被nginx监听捕获,转到http://127.0.0.1:9001(在Nginx中已设置)
- 再被webpack 监听捕获,到leyou-manage-web项目,根据#后面的路由路径/item/brand,找到页面,逐次响应回去给浏览器,显示页面(黑色部分结束)
- 发出异步请求,开始加载后端服务进程
- 后端加载过程:
- http://api.leyou.com/api/item/brand/page,同样经过hosts文件
- 经过nginx,转到10010端口
- 被zuul网关监听捕获,进入gateway项目,再被路由转发到item-service微服务
- 最后根据brand/page,进入controller进入相应方法,再逐步返回到浏览器加载出数据
前端分析
品牌新增
controller
还是一样,先分析四个内容:
-
请求方式:POST
-
请求路径:/brand
-
请求参数:brand对象,外加商品分类的id数组cids
-
返回值:无,只需要响应状态码
代码:
/**
* 新增品牌
* @param brand
* @param cids
*/
@PostMapping
public ResponseEntity<Void> saveBrand(Brand brand, @RequestParam("cids") List<Long> cids){
this.brandService.saveBrand(brand, cids);
return ResponseEntity.status(HttpStatus.CREATED).build();
}
Service
这里要注意,我们不仅要新增品牌,还要维护品牌和商品分类的中间表。
用forEach+lambda表达式遍历list集合
/**
* 新增品牌
*
* @param brand
* @param cids
*/
@Transactional
public void saveBrand(Brand brand, List<Long> cids) {
// 先新增brand
this.brandMapper.insertSelective(brand);
// 在新增中间表
cids.forEach(cid -> {
this.brandMapper.insertCategoryAndBrand(cid, brand.getId());
});
}
Mapper
通用Mapper只能处理单表,也就是Brand的数据,因此我们手动编写一个方法及sql,实现中间表的新增:
(用Mybatis注解实现插入)
public interface BrandMapper extends Mapper<Brand> {
/**
* 新增商品分类和品牌中间表数据
* @param cid 商品分类id
* @param bid 品牌id
* @return
*/
@Insert("INSERT INTO tb_category_brand(category_id, brand_id) VALUES (#{cid},#{bid})")
int insertBrandAndCategory(@Param("cid") Long cid, @Param("bid") Long bid);
}
QS工具
将对象转为jason格式