帶你逐步深入瞭解SSM框架——淘淘商城專案之實現商品新增
1. 課程計劃
完成商品新增功能
1、商品類目選擇
2、圖片上傳
3、圖片伺服器搭建
4、kindEditor富文字編輯器的使用
5、商品新增功能
2. 實現商品類目選擇功能
2.1. 需求
在商品新增頁面,點選“選擇類目”顯示商品類目列表:
2.2. 實現步驟:
1、 按鈕新增點選事件,彈出視窗,載入資料顯示tree
2、 將選擇類目的元件封裝起來,通過TT.iniit()初始化,最終呼叫initItemCat()方法進行初始化
3、 建立資料庫、以及tb _item_cat表,初始化資料
4、 編寫Controller、Service、Mapper
2.3. EasyUI tree資料結構
資料結構中必須包含:
Id:節點id
Text:節點名稱
State:如果不是葉子節點就是close,葉子節點就是open。Close的節點點選後會在此傳送請求查詢子專案。
可以根據parentid查詢分類列表。
2.4. Mapper
使用逆向工程生成的mapper檔案。
2.5. Service
@Service publicclass ItemCatServiceImpl implements ItemCatService { @Autowired private TbItemCatMapperitemCatMapper; @Override public List<TbItemCat> getItemCatList(LongparentId) throws Exception { TbItemCatExample example = new TbItemCatExample(); //設定查詢條件 Criteria criteria = example.createCriteria(); //根據parentid查詢子節點
criteria.andParentIdEqualTo(parentId //返回子節點列表 List<TbItemCat> list = itemCatMapper.selectByExample(example); returnlist; } } |
2.6. Controller
@Controller @RequestMapping("/item/cat") publicclass ItemCatController { @Autowired private ItemCatServiceitemCatService; @SuppressWarnings({"rawtypes", "unchecked" }) @RequestMapping("/list") @ResponseBody //如果id為null是使用預設值,也就是parentid為0的分類列表 publicList categoryList(@RequestParam(value="id", defaultValue="0") LongparentId) throws Exception { List catList = new ArrayList(); //查詢資料庫 List<TbItemCat> list = itemCatService.getItemCatList(parentId); for (TbItemCattbItemCat : list) { Map node = new HashMap<>(); node.put("id", tbItemCat.getId()); node.put("text", tbItemCat.getName()); //如果是父節點的話就設定成關閉狀態,如果是葉子節點就是open狀態 node.put("state", tbItemCat.getIsParent()?"closed":"open"); catList.add(node); } returncatList; } } |
3. 圖片上傳
3.1. 圖片伺服器
3.1.1. 傳統專案中的圖片管理
傳統專案中,可以在web專案中新增一個資料夾,來存放上傳的圖片。例如在工程的根目錄WebRoot下建立一個images資料夾。把圖片存放在此資料夾中就可以直接使用在工程中引用。
優點:引用方便,便於管理
缺點:
1、如果是分散式環境圖片引用會出現問題。
2、圖片的下載會給伺服器增加額外的壓力
傳統圖片管理方式在分散式環境中的問題:
3.1.2. 分散式環境的圖片管理
分散式環境一般都有一個專門的圖片伺服器存放圖片。
我們使用虛擬機器搭建一個專門的伺服器來存放圖片。在此伺服器上安裝一個nginx來提供http服務,安裝一個ftp伺服器來提供圖片上傳服務。
3.1.3. 搭建圖片伺服器
第一步:安裝vsftpd提供ftp服務
詳見:vsftpd安裝手冊.doc
第二步:安裝nginx提供http服務
詳見:nginx安裝手冊.doc
3.1.4. 測試圖片伺服器
1. ftp服務測試。
a)使用ftp客戶端
b)使用java程式
ftp可以需要依賴commons-net-3.3.jar包。
publicstatic void main(String[]args) throws Exception { FTPClient ftpClient = new FTPClient(); ftpClient.connect("192.168.25.200"); ftpClient.login("ftpuser", "ftpuser"); FileInputStream inputStream = new FileInputStream(new File("D:\\Documents\\Pictures\\pics\\21.jpg")); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); ftpClient.storeFile("123.jpg", inputStream); inputStream.close(); ftpClient.logout(); } |
2. http服務測試
a) 瀏覽器測試
3.1.5. SpringMVC中實現圖片上傳
上傳思路:
第一步:
匯入common-fileupload的依賴
<!-- 檔案上傳元件 --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> </dependency> |
第二步:
在SpringMVC配置檔案中新增檔案上傳解析器
<!-- 定義檔案上傳解析器 --> <beanid="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 設定預設編碼 --> <property name="defaultEncoding"value="UTF-8"></property> <!-- 設定檔案上傳的最大值5MB,5*1024*1024 --> <property name="maxUploadSize"value="5242880"></property> </bean> |
3.1.6. Service實現
1. 獲取資源配置檔案的內容
第一步:
建立資源配置檔案
FILI_UPLOAD_PATH=D:/temp/imagestest/webapps/images IMAGE_BASE_URL=http://localhost:9000/images |
第二步:
在Spring(taotao-manage-servlet.xml)容器中載入資原始檔
第二步:
在Service中獲取資源配置:
@Value("${FILI_UPLOAD_PATH}") private StringFILI_UPLOAD_PATH; @Value("${IMAGE_BASE_URL}") private StringIMAGE_BASE_URL; |
2. 圖片名生成策略
時間+隨機數:
/** *圖片名生成 */ publicstatic String genImageName() { //取當前時間的長整形值包含毫秒 longmillis = System.currentTimeMillis(); //long millis = System.nanoTime(); //加上三位隨機數 Random random = new Random(); intend3 = random.nextInt(999); //如果不足三位前面補0 String str = millis + String.format("%03d",end3); returnstr; } |
使用UUID:
UUID.randomUUID(); |
3. Service實現
@Service publicclass PictureServiceImpl implements PictureService { @Value("${IMAGE_BASE_URL}") private StringIMAGE_BASE_URL; @Value("${FILI_UPLOAD_PATH}") private StringFILI_UPLOAD_PATH; @Value("${FTP_SERVER_IP}") private StringFTP_SERVER_IP; @Value("${FTP_SERVER_PORT}") private IntegerFTP_SERVER_PORT; @Value("${FTP_SERVER_USERNAME}") private StringFTP_SERVER_USERNAME; @Value("${FTP_SERVER_PASSWORD}") private StringFTP_SERVER_PASSWORD; @Override public PictureResult uploadFile(MultipartFileuploadFile) throws Exception { // 上傳檔案功能實現 String path = savePicture(uploadFile); // 回顯 PictureResult result = new PictureResult(0,IMAGE_BASE_URL + path); returnresult; } private String savePicture(MultipartFileuploadFile) { String result = null; try { // 上傳檔案功能實現 // 判斷檔案是否為空 if (uploadFile.isEmpty()) returnnull; // 上傳檔案以日期為單位分開存放,可以提高圖片的查詢速度 String filePath = "/" + new SimpleDateFormat("yyyy").format(new Date()) +"/" + new SimpleDateFormat("MM").format(new Date()) +"/" + new SimpleDateFormat("dd").format(new Date()); // 取原始檔名 String originalFilename = uploadFile.getOriginalFilename(); // 新檔名 String newFileName = IDUtils.genImageName() + originalFilename.substring(originalFilename.lastIndexOf(".")); // 轉存檔案,上傳到ftp伺服器 FtpUtil.uploadFile(FTP_SERVER_IP,FTP_SERVER_PORT, FTP_SERVER_USERNAME,FTP_SERVER_PASSWORD, FILI_UPLOAD_PATH, filePath, newFileName, uploadFile.getInputStream()); result = filePath + "/" + newFileName; } catch (Exceptione) { e.printStackTrace(); } returnresult; } } |
3.1.7. Controller實現
@Controller @RequestMapping("/pic") publicclass PictureController { @Autowired private PictureServicepictureService; @RequestMapping("/upload") @ResponseBody public PictureResult uploda(MultipartFileuploadFile) throws Exception { //呼叫service上傳圖片 PictureResult pictureResult = pictureService.uploadFile(uploadFile); //返回上傳結果 returnpictureResult; } } |
3.1.8. 前端JS實現圖片上傳
1. Js實現邏輯
KindEditor 4.x 文件
上傳圖片使用kindeditor的上傳元件實現。
2. 上傳圖片請求url:
3. 返回值
參考文件:
返回格式(JSON)
//成功時 { "error" : 0, "url" : "http://www.example.com/path/to/file.ext" } //失敗時 { "error" : 1, "message" : "錯誤資訊" } |
返回值資料型別:
publicclass PictureResult { /** *上傳圖片返回值,成功:0 失敗:1 */ private Integererror; /** *回顯圖片使用的url */ private Stringurl; /** *錯誤時的錯誤訊息 */ } |
4. kindeditor(富文字編輯器)的使用
4.1. kindeditor的使用過程:
1、匯入js:
2、定義多行文字(不可見、給定name)
3、呼叫TT.createEditor
4、效果
4.2. 取文字編輯器中的內容
將編輯器的內容設定到原來的textarea控制元件裡。
editor.sync();
5. 新增商品實現
5.1. js編寫邏輯
//提交表單 function submitForm(){ //有效性驗證 if(!$('#itemAddForm').form('validate')){ $.messager.alert('提示','表單還未填寫完成!'); return ; } //取商品價格,單位為“分” $("#itemAddForm [name=price]").val(eval($("#itemAddForm [name=priceView]").val()) * 100); //同步文字框中的商品描述 itemAddEditor.sync(); //取商品的規格 /* var paramJson = []; $("#itemAddForm .params li").each(function(i,e){ var trs = $(e).find("tr"); var group = trs.eq(0).text(); var ps = []; for(var i = 1;i<trs.length;i++){ var tr = trs.eq(i); ps.push({ "k" : $.trim(tr.find("td").eq(0).find("span").text()), "v" : $.trim(tr.find("input").val()) }); } paramJson.push({ "group" : group, "params": ps }); }); //把json物件轉換成字串 paramJson = JSON.stringify(paramJson); $("#itemAddForm [name=itemParams]").val(paramJson); */ //ajax的post方式提交表單 //$("#itemAddForm").serialize()將表單序列號為key-value形式的字串 $.post("/item/save",$("#itemAddForm").serialize(),function(data){ if(data.status == 200){ $.messager.alert('提示','新增商品成功!'); } }); } |
5.2. 提交請求的資料格式
$("#itemAddForm").serialize()將表單序列號為key-value形式的字串
以post 的形式將表單的內容提交。
請求的url:
/item/save
返回的結果:
淘淘自定義返回結果:
1、狀態碼
2、響應的訊息
3、響應的資料
/** * 淘淘商城自定義響應結構 */ publicclass TaotaoResult { // 定義jackson物件 privatestatic final ObjectMapperMAPPER = new ObjectMapper(); // 響應業務狀態 private Integerstatus; // 響應訊息 private Stringmsg; // 響應中的資料 private Objectdata; publicstatic TaotaoResult build(Integer status, String msg, Object data) { returnnew TaotaoResult(status,msg, data); } publicstatic TaotaoResult ok(Object data) { returnnew TaotaoResult(data); } publicstatic TaotaoResult ok() { returnnew TaotaoResult(null); } public TaotaoResult() { } publicstatic TaotaoResult build(Integer status, String msg) { returnnew TaotaoResult(status,msg, null); } public TaotaoResult(Integerstatus, String msg, Objectdata) { this.status =status; this.msg =msg; this.data =data; } public TaotaoResult(Objectdata) { this.status = 200; this.msg ="OK"; this.data =data; } // public Boolean isOK() { // return this.status == 200; // } public Integer getStatus() { returnstatus; } publicvoid setStatus(Integer status) { this.status =status; } public String getMsg() { returnmsg; } publicvoid setMsg(String msg) { this.msg =msg; } public Object getData() { returndata; } publicvoid setData(Object data) { this.data =data; } /** * 將json結果集轉化為TaotaoResult物件 * * @param jsonDatajson資料 * @param clazz TaotaoResult中的object型別 * @return */ publicstatic TaotaoResult formatToPojo(StringjsonData, Class<?> clazz) { try { if (clazz ==null) { returnMAPPER.readValue(jsonData, TaotaoResult.class); } JsonNode jsonNode = MAPPER.readTree(jsonData); JsonNode data = jsonNode.get("data"); Object
obj =
|