乐优商城(02)--商品分类
樂優商城(02)–商品分類
一、創建數據庫
導入sql文件,運行之
得到以下數據表:
二、頁面實現
2.1、url請求分析
找到頁面Category.vue,目錄路徑為:src/pages/item/Category.vue
商品分類使用了樹狀結構,而這種結構的組件vuetify并沒有提供,這里自定義了一個樹狀組件:
<template><v-card><v-flex xs12 sm10><v-tree url="/item/category/list":isEdit="isEdit"@handleAdd="handleAdd"@handleEdit="handleEdit"@handleDelete="handleDelete"@handleClick="handleClick"/></v-flex></v-card> </template>修改url請求配置,按下圖進行修改
點擊商品管理下的分類管理子菜單,在瀏覽器控制臺可以看到:
2.2、后臺接口實現
在leyou-item-iterface導入依賴
<dependency><groupId>javax.persistence</groupId><artifactId>persistence-api</artifactId><version>1.0</version> </dependency>實體類Category
編寫時,可以對照數據庫的字段進行分析
@Table(name="tb_category") public class Category {@Id@GeneratedValue(strategy=GenerationType.IDENTITY)private Long id;private String name;private Long parentId;private Boolean isParent; // 注意isParent生成的getter和setter方法需要手動加上Isprivate Integer sort;// getter和setter略 }controller
編寫一個controller一般需要知道四個內容:
- 請求方式:決定我們用GetMapping還是PostMapping
- 請求路徑:決定映射路徑
- 請求參數:決定方法的參數
- 返回值結果:決定方法的返回值
-
請求方式:Get
-
請求路徑:/api/item/category/list。其中/api是網關前綴,/item是網關的路由映射,真實的路徑應該是/category/list
-
請求參數:pid=0,根據tree組件的說明,應該是父節點的id,第一次查詢為0,那就是查詢一級類目
-
返回結果:json數組
service層
-
接口代碼
/*** 分類業務層接口*/ public interface CategoryService {/*** 根據父節點 id查詢商品類目* @param pid* @return*/List<Category> queryCategoryByPid(Long pid); } -
實現類代碼
/*** 分類業務實現類*/ @Service public class CategoryServiceImpl implements CategoryService {@Autowiredprivate CategoryMapper categoryMapper;/*** 根據父節點 id查詢商品類目** @param pid* @return*/@Overridepublic List<Category> queryCategoryByPid(Long pid) {Category category = new Category();category.setParentId(pid);return this.categoryMapper.select(category);} }
mapper層代碼
使用通用mapper簡化開發
/*** category類的通用mapper*/ public interface CategoryMapper extends Mapper<Category> { }要注意,并沒有在mapper接口上聲明@Mapper注解,在啟動類上添加一個掃描包功能:
@SpringBootApplication @EnableDiscoveryClient @MapperScan("com.leyou.item.mapper") //注意一定要選擇tk.mybatis包的注解 public class LeyouItemApplication {public static void main(String[] args) {SpringApplication.run(LeyouItemApplication.class,args);} }啟動測試,記得啟動nginx
-
不經過網關直接訪問:http://localhost:8081/category/list?pid=0
-
經過網關測試:http://api.leyou.com/api/item/category/list?pid=0
-
后臺管理頁面查看,發現跨域問題
2.3、解決跨域問題
2.3.1、問題說明
跨域:瀏覽器對于javascript的同源策略的限制 。
以下情況都屬于跨域:
| 域名不同 | www.jd.com 與 www.taobao.com |
| 域名相同,端口不同 | www.jd.com:8080 與 www.jd.com:8081 |
| 二級域名不同 | item.jd.com 與 miaosha.jd.com |
如果域名和端口都相同,但是請求路徑不同,不屬于跨域,如:
www.jd.com/item
www.jd.com/goods
http和https也屬于跨域
而我們剛才是從manage.leyou.com去訪問api.leyou.com,這屬于二級域名不同,跨域了。
為什么有跨域問題?
跨域不一定都會有跨域問題。
因為跨域問題是瀏覽器對于ajax請求的一種安全限制:一個頁面發起的ajax請求,只能是與當前頁域名相同的路徑,這能有效的阻止跨站攻擊。
因此:跨域問題 是針對ajax的一種限制。
解決跨域問題的方案
-
Jsonp
最早的解決方案,利用script標簽可以跨域的原理實現。
限制:
- 需要服務的支持
- 只能發起GET請求
-
nginx反向代理
思路是:利用nginx把跨域反向代理為不跨域,支持各種請求方式
缺點:需要在nginx進行額外配置,語義不清晰
-
CORS
規范化的跨域請求解決方案,安全可靠。
優勢:
- 在服務端進行控制是否允許跨域,可自定義規則
- 支持各種請求方式
缺點:
- 會產生額外的請求
CORS解決跨域
CORS是一個W3C標準,全稱是"跨域資源共享"(Cross-origin resource sharing)。
它允許瀏覽器向跨源服務器,發出XMLHttpRequest請求,從而克服了AJAX只能同源使用的限制。
CORS需要瀏覽器和服務器同時支持。目前,所有瀏覽器都支持該功能,IE瀏覽器不能低于IE10。
-
瀏覽器端:
目前,所有瀏覽器都支持該功能(IE10以下不行)。整個CORS通信過程,都是瀏覽器自動完成,不需要用戶參與。
-
服務端:
CORS通信與AJAX沒有任何差別,因此你不需要改變以前的業務邏輯。只不過,瀏覽器會在請求中攜帶一些頭信息,我們需要以此判斷是否允許其跨域,然后在響應頭中加入一些信息即可。這一般通過過濾器完成即可
2.3.2、原理簡單刨析
瀏覽器會將ajax請求分為兩類,其處理方案略有差異:簡單請求、特殊請求。
只要同時滿足以下兩大條件,就屬于簡單請求。:
(1) 請求方法是以下三種方法之一:
- HEAD
- GET
- POST
(2)HTTP的頭信息不超出以下幾種字段:
- Accept
- Accept-Language
- Content-Language
- Last-Event-ID
- Content-Type:只限于三個值application/x-www-form-urlencoded、multipart/form-data、text/plain
當瀏覽器發現發起的ajax請求是簡單請求時,會在請求頭中攜帶一個字段:Origin.
Origin中會指出當前請求屬于哪個域(協議+域名+端口)。服務會根據這個值決定是否允許其跨域。
如果服務器允許跨域,需要在返回的響應頭中攜帶下面信息:
Access-Control-Allow-Origin: http://manage.leyou.com Access-Control-Allow-Credentials: true Content-Type: text/html; charset=utf-8- Access-Control-Allow-Origin:可接受的域,是一個具體域名或者*(代表任意域名)
- Access-Control-Allow-Credentials:是否允許攜帶cookie,默認情況下,cors不會攜帶cookie,除非這個值是true
有關cookie:
要想操作cookie,需要滿足3個條件:
- 服務的響應頭中需要攜帶Access-Control-Allow-Credentials并且為true。
- 瀏覽器發起ajax需要指定withCredentials 為true
- 響應頭中的Access-Control-Allow-Origin一定不能為*,必須是指定的域名
不符合簡單請求的條件,會被瀏覽器判定為特殊請求,,例如請求方式為PUT。
預檢請求
特殊請求會在正式通信之前,增加一次HTTP查詢請求,稱為"預檢"請求(preflight)。
瀏覽器先詢問服務器,當前網頁所在的域名是否在服務器的許可名單之中,以及可以使用哪些HTTP動詞和頭信息字段。只有得到肯定答復,瀏覽器才會發出正式的XMLHttpRequest請求,否則就報錯。
一個“預檢”請求的樣板:
OPTIONS /cors HTTP/1.1 Origin: http://manage.leyou.com Access-Control-Request-Method: PUT Access-Control-Request-Headers: X-Custom-Header Host: api.leyou.com Accept-Language: en-US Connection: keep-alive User-Agent: Mozilla/5.0...與簡單請求相比,除了Origin以外,多了兩個頭:
- Access-Control-Request-Method:接下來會用到的請求方式,比如PUT
- Access-Control-Request-Headers:會額外用到的頭信息
預檢請求的響應
服務的收到預檢請求,如果許可跨域,會發出響應:
HTTP/1.1 200 OK Date: Mon, 01 Dec 2008 01:15:39 GMT Server: Apache/2.0.61 (Unix) Access-Control-Allow-Origin: http://manage.leyou.com Access-Control-Allow-Credentials: true Access-Control-Allow-Methods: GET, POST, PUT Access-Control-Allow-Headers: X-Custom-Header Access-Control-Max-Age: 1728000 Content-Type: text/html; charset=utf-8 Content-Encoding: gzip Content-Length: 0 Keep-Alive: timeout=2, max=100 Connection: Keep-Alive Content-Type: text/plain除了Access-Control-Allow-Origin和Access-Control-Allow-Credentials以外,這里又額外多出3個頭:
- Access-Control-Allow-Methods:允許訪問的方式
- Access-Control-Allow-Headers:允許攜帶的頭
- Access-Control-Max-Age:本次許可的有效時長,單位是秒,過期之前的ajax請求就無需再次進行預檢了
如果瀏覽器得到上述響應,則認定為可以跨域,后續就跟簡單請求的處理是一樣的了。
2.3.3、問題解決
兩種方式:
-
直接使用SpringMVC寫好的CORS的跨域過濾器:CorsFilter ,內部已經實現了剛才所講的判定邏輯
在leyou-gateway中編寫一個配置類,并且注冊CorsFilter:
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.reactive.CorsWebFilter; import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;@Configuration public class LeyouCorsConfig {@Beanpublic CorsWebFilter corsFilter() {//1.添加CORS配置信息CorsConfiguration config = new CorsConfiguration();//1) 允許的域,不要寫*,否則cookie就無法使用了config.addAllowedOrigin("http://manage.leyou.com");//2) 是否發送Cookie信息config.setAllowCredentials(true);//3) 允許的請求方式config.addAllowedMethod("OPTIONS");config.addAllowedMethod("HEAD");config.addAllowedMethod("GET");config.addAllowedMethod("PUT");config.addAllowedMethod("POST");config.addAllowedMethod("DELETE");config.addAllowedMethod("PATCH");// 4)允許的頭信息config.addAllowedHeader("*");//2.添加映射路徑,我們攔截一切請求UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();configSource.registerCorsConfiguration("/**", config);//3.返回新的CorsFilter.return new CorsWebFilter(configSource);} } -
使用SpringCloudGateway中配置文件的方式
spring:cloud:gateway:# 跨域配置globalcors:cors-configurations:'[/**]': # 允許跨域訪問的資源allowedOrigins: "http://manage.leyou.com" #跨域允許來源allowedMethods: #允許跨域的方法- GET- POST- OPTIONS- HEAD- PUT- DELETE- PATCH重啟測試,訪問成功
三、功能完善
目前只完成了查詢功能,還需要添加增、刪、改功能
3.1、異步查詢工具axios
異步查詢數據,自然是通過ajax查詢,但jQuery與MVVM的思想不吻合,而且ajax只是jQuery的一小部分。因此不可能為了發起ajax請求而去引用這么大的一個庫,所以使用Vue官方推薦的ajax請求框架:axios。
入門
axios的GET請求語法:
axios.get("/item/category/list?pid=0") // 請求路徑和請求參數拼接.then(function(resp){// 成功回調函數}).catch(function(){// 失敗回調函數}) // 參數較多時,可以通過params來傳遞參數 axios.get("/item/category/list", {params:{pid:0}}).then(function(resp){})// 成功時的回調.catch(function(error){})// 失敗時的回調axios的POST請求語法: (新增一個用戶)
axios.post("/user",{name:"Jack",age:21}).then(function(resp){}).catch(function(error){})注意:POST請求傳參,不需要像GET請求那樣定義一個對象,在對象的params參數中傳參。post()方法的第二個參數對象,就是將來要傳遞的參數 。
配置
而在項目中,已經引入了axios,并且進行了簡單的封裝,在src下的http.js中:
import Vue from 'vue' import axios from 'axios' import config from './config' // config中定義的基礎路徑是:http://api.leyou.com/api axios.defaults.baseURL = config.api; // 設置axios的基礎請求路徑 axios.defaults.timeout = 3000; // 設置axios的請求時間Vue.prototype.$http = axios;// 將axios賦值給Vue原型的$http屬性,這樣所有vue實例都可使用該對象通過簡單封裝后,以后使用this.$http就可以發起相應的請求。
3.2、QS工具
QS是一個第三方庫,即Query String,請求參數字符串 。
什么是請求參數字符串?例如: name=jack&age=21
QS工具可以便捷的實現 JS的Object與QueryString的轉換。
通過this.$qs獲取這個工具。
為什么要使用qs?
因為axios處理請求體的原則會根據請求數據的格式來定:
-
如果請求體是對象:會轉為json發送
-
如果請求體是String:會作為普通表單請求發送,但需要我們自己保證String的格式是鍵值對。
如:name=jack&age=12
所以在使用axios傳遞參數時,需要把json轉換成拼接好的字符串
3.3、增加分類
3.3.1、實現邏輯
首先將新添加的節點信息存入數據庫,后修改父節點相關信息
3.3.2、前端邏輯代碼
在/pages/item/Category.vue中完善handleAdd方法,傳入的參數是node,即當前節點的詳細信息,使用qs進行轉換,然后發送請求
handleAdd(node) {this.$http({method: 'post',url: '/item/category',data: this.$qs.stringify(node)}).then(() => {}).catch(() => {});}3.3.3、后臺接口
controller
- 請求方式:新增使用PostMapping
- 請求路徑:/api/item/category。其中/api是網關前綴,/item是網關的路由映射,真實的路徑應該是/category
- 請求參數:節點參數(node)
- 返回值結果:如果添加成功就返回201 CREATED
service
接口:
/*** 增加一個新的分類* @param category* @return*/ void addCategory(Category category);實現類:
/*** 增加一個新的分類** @param category* @return*/ @Override public void addCategory(Category category) {//首先將id置位空category.setId(null);//將該分類添加this.categoryMapper.insert(category);//將該節點的父節點的isParent設置為trueCategory parent = new Category();parent.setIsParent(true);parent.setId(category.getParentId());this.categoryMapper.updateByPrimaryKeySelective(parent); }3.4、修改分類
3.4.1、實現邏輯
因為修改只能修改分類的名字,所以比較簡單,直接更新數據庫中對應id的name即可。
3.4.2、前端邏輯代碼
在/pages/item/Category.vue中完善handleEdit方法,傳入的參數是id和name,即要修改的節點id及新的name,先構造一個json,然后使用qs進行轉換,最后發送請求
handleEdit(id, name) {const node = {id : id,name : name}this.$http({method: 'put',url: '/item/category',data:this.$qs.stringify(node)}).then(() =>{}).catch(() =>{this.$message("修改失敗!")})},需要注意的是項目中提供的tree組件在進行修改時會發生錯誤,原因是位于/src/components/tree/TreeItem.vue中,afterEdit方法中if條件中的判斷出了問題,應該是this.beginEdit,而不是this.model.beginEdit
afterEdit() {if (this.beginEdit) {this.beginEdit = false;this.handleEdit(this.model.id, this.model.name);} }3.4.3、后臺代碼
controller
- 請求方式:修改使用PutMapping
- 請求路徑:/api/item/category。其中/api是網關前綴,/item是網關的路由映射,真實的路徑應該是/category
- 請求參數:節點參數(node)
- 返回值結果:如果添加成功就返回202 ACCEPTED
service
接口:
/*** 修改一個分類* @param category* @return*/ void updateCategory(Category category);實現類:
/*** 修改一個分類** @param category* @return*/ @Override @Transactional public void updateCategory(Category category) {this.categoryMapper.updateByPrimaryKeySelective(category); }3.5、刪除分類
3.5.1、實現邏輯
刪除邏輯稍微復雜,涉及多幾個節點以及另外一張表tb_category_brand。中間表:tb_category_brand,是用來維護分類和品牌的對應關系的,一個分類下會有多個品牌,某個品牌可能屬于不同的分類。所以中間表中保存的數據就是category_id和brand_id,而且category_id中保存的是最底一層的類目id,也就是分類的葉子節點id
-
首先要確定被刪節點是父節點、子節點還是葉子節點。如果是父節點,那么刪除所有附帶子節點以及葉子節點,然后要維護中間表。
-
如果是子節點,那么刪除自己還刪除葉子節點,然后判斷父節點孩子的個數,如果不為0,則不做任何修改;如果為0,則修改父節點isParent的值為false,最后維護中間表。
-
如果刪除的是葉子節點,則直接刪除自己,同時判斷該節點的兄弟節點個數,如果不為0,則不做任何修改;如果為0,則修改父節點isParent的值為false。
當對中間表進行修改的時候,那么就需要找出當前節點下所有的葉子節點(如果是父節點),然后刪除中間表中的對應數據。
3.5.2、前端邏輯代碼
handleDelete(id) {this.$http.delete("/item/category/cid/"+id).then(() =>{//this.$message("刪除成功!");}).catch(() =>{//this.$message("刪除失敗!")}) }3.5.3、后臺代碼
controller
- 請求方式:刪除使用DeleteMapping
- 請求路徑:/api/item/category/cid/{cid}。其中/api是網關前綴,/item是網關的路由映射,真實的路徑應該是/category/cid/{cid}
- 請求參數:請求參數為cid,使用@PathVariable(“cid”)獲取
- 返回值結果:如果添加成功就返回200 OK
service
接口:
/*** 刪除一個分類* @param cid*/ void deleteCategory(Long cid);實現類:
/*** 刪除一個分類** @param cid*/ @Override @Transactional public void deleteCategory(Long cid) {//查詢當前id的分類信息Category category = this.categoryMapper.selectByPrimaryKey(cid);//三級目錄即父節點->子節點->葉子節點//若當前節點是葉子節點,中間表的數據是保存葉子節點和品牌之間的關系if (!category.getIsParent()){//查詢該節點的所有兄弟節點包括自己List<Category> categoryList = queryAllNode(category.getParentId());//若節點數量等于1if (categoryList.size() == 1){//修改父節點的isParent為falseCategory parent = new Category();parent.setId(category.getParentId());parent.setIsParent(false);this.categoryMapper.updateByPrimaryKeySelective(parent);}//直接刪除中間表的數據this.categoryMapper.deleteByCategoryIdInCategoryBrand(cid);//刪除本節點this.categoryMapper.deleteByPrimaryKey(cid);//子節點}else if (category.getIsParent() && category.getParentId() != 0){//先查詢該節點下的所有葉子節點List<Category> categories = queryAllNode(cid);categories.forEach(cate -> {//再刪除該節點下的所有的葉子節點this.categoryMapper.deleteByPrimaryKey(cate.getId());//再維護葉子節點在中間表的數據this.categoryMapper.deleteByCategoryIdInCategoryBrand(cate.getId());});//查詢本節點是否有兄弟節點List<Category> categoryList = queryAllNode(category.getParentId());//若節點數量等于1if (categoryList.size() == 1){//修改父節點的isParent為falseCategory parent = new Category();parent.setId(category.getParentId());parent.setIsParent(false);this.categoryMapper.updateByPrimaryKeySelective(parent);}//刪除本節點this.categoryMapper.deleteByPrimaryKey(cid);//父節點}else {//先查詢該節點下的所有子節點List<Category> categories = queryAllNode(cid);categories.forEach(cate -> {//再查詢子節點下的所有葉子節點List<Category> categories1 = queryAllNode(cate.getId());//刪除葉子節點和中間表的數據categories1.forEach(cate1 ->{this.categoryMapper.deleteByCategoryIdInCategoryBrand(cate1.getId());this.categoryMapper.deleteByPrimaryKey(cate1.getId());});this.categoryMapper.deleteByPrimaryKey(cate.getId());});//再刪除本節點this.categoryMapper.deleteByPrimaryKey(cid);} }/*** 查詢同一個父類id下的所有子分類* @param cid* @return*/ private List<Category> queryAllNode(Long cid){Example example = new Example(Category.class);example.createCriteria().andEqualTo("parentId",cid);return this.categoryMapper.selectByExample(example); }mapper
public interface CategoryMapper extends Mapper<Category> {@Delete("DELETE FROM tb_category_brand WHERE category_id = #{cid}")void deleteByCategoryIdInCategoryBrand(@Param("cid") Long id);}四、遇到的問題
問題描述
假設在圖書、音像、電子書刊分類下新增一個分類名為Node1。點擊新增按鈕,然后修改名字為Node1。此時這個節點已經插入到數據庫中,但是這個節點的信息在新增完畢后并沒有同步到前端頁面當中,所以當前節點的id = 0。那么,以Node1作為父節點,在新增子節點時就會產生問題,因為Node1的id沒有同步,一直是0,所以在創建它的子節點時,子節點的parentId就為0了,即發生新增失敗。
解決方法
因為數據庫中tb_category這個表的id字段是自增的,所以在新增前可以獲取數據庫中最后一條數據的id,在構造新節點時,給id賦的值就是最后一條數據的id加1
同時對增加功能進行優化,必須在選中(即必須點擊父節點)的情況下才能進行新增。
4.1、前端代碼修改
先發送請求獲取數據庫中最后一條記錄,然后得到id,構造新節點,插入。
addChild: function () {this.$http.get(this.url,{params: {pid:-1}}).then(resp => {let child = {id: resp.data[0].id+1,name: '新的節點',parentId: this.model.id,isParent: false,sort:this.model.children? this.model.children.length + 1:1};if (this.isSelected) {if (!this.model.isParent) {Vue.set(this.model, 'children', [child]);this.model.isParent = true;this.open = true;this.handleAdd(child);} else {if (!this.isFolder) {this.$http.get(this.url, {params: {pid: this.model.id}}).then(resp => {Vue.set(this.model, 'children', resp.data);this.model.children.push(child);this.open = true;this.handleAdd(child);});} else {this.model.children.push(child);this.open = true;this.handleAdd(child);}}}else {this.$message.error("選中后再操作!");}});},4.2、后臺代碼修改
controller
@GetMapping("/list") public ResponseEntity<List<Category>> queryCategoryByPId(@RequestParam(value = "pid",defaultValue = "0") Long pid){//請求不合法,響應400的狀態碼if (pid == null){return ResponseEntity.badRequest().build();}//如果pid的值為-1那么需要獲取數據庫中最后一條數據if (pid == -1){List<Category> lastList = this.categoryService.queryLast();return ResponseEntity.ok(lastList);}//得到分類List<Category> categories = this.categoryService.queryCategoryByPid(pid);//categories為空,數據未找到,響應404狀態碼if (CollectionUtils.isEmpty(categories)){return ResponseEntity.notFound().build();}//成功獲取返回200狀態碼//將查詢得到的數據傳入,會被轉換為json數據return ResponseEntity.ok(categories); }service
/*** 查詢當前數據庫中最后一條數據* @return*/ List<Category> queryLast();實現類:
/*** 查詢當前數據庫中最后一條數據** @return*/ @Override public List<Category> queryLast() {return this.categoryMapper.selectLast(); }mapper
@Select("SELECT * FROM tb_category WHERE id = (SELECT MAX(id) FROM tb_category)") List<Category> selectLast();總結
以上是生活随笔為你收集整理的乐优商城(02)--商品分类的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 可信计算 沈昌祥_沈昌祥院士:用主动免疫
- 下一篇: 21 Fragment和短语法应用