由@ModelAttribute想到的

有個哥們在公司裏作了兩天,匆匆忙忙完成了一個功能,跑路了,而後我就被指定接手了這個攤子。前端

功能很簡單,上傳一個固件升級文件,併爲固件提供一個下載連接。他的代碼是這麼寫的:java

package com.zk.controller;

import com.zk.model.Product;
import com.zk.service.ProductTemplateService;
import com.zk.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import java.io.File;
import java.io.IOException;

@RequestMapping("/file")
@RestController
public class FileController {

    @Value("${web.file-path}")
    private String filePath;

    @Autowired
    private ProductTemplateService productTemplateService;

    @Value("${myhost}")
    private String myhost;

    @PostMapping("/upload")
    @ResponseBody
    public Result upload(@RequestParam("file") MultipartFile file, @ModelAttribute Product product){
        
        Result result=Result.error("");
        //文件判空
        if(!file.isEmpty()){

            String fileName =file.getOriginalFilename().replace("-","");
            try {
                //建立文件
                File file1 = new File(filePath + fileName);

                //建立url
                String url=myhost+fileName;

                //封裝產品屬性
                product.setUrl(url);
                product.setFileName(fileName);


                //判斷目錄是否存在,不存在則建立
                if(!file1.exists()){
                    file1.mkdirs();
                }

                //寫入至本地
                file.transferTo(file1);

                result.setMsg("上傳成功");
            }catch (IOException e){
                e.printStackTrace();
                result.setMsg("上傳失敗");
            }
        }
        return result;
    }
}

方法參數中神奇地用到了@ModelAttribute, @ModelAttribute的主要做用是數據添加到Model對象中,用於視圖頁面的展現。web

它的詳細用法在此不作詳述,它是Spring MVC提供的註解,固然在Spring Boot中也可使用。spring

因此在這裏用@ModelAttribute顯得莫名其妙,咱們的服務器並無View,而實際上如今成熟的服務開發,特別是互聯網公司的服務端開發已經完全擺脫了MVC模式,視圖的工做有專業的前端進行開發,數據經過Ajax或者websocket的方式實現先後端的交互。服務器更多扮演的是一個Restful resource的角色,也所以,@RestController還持續使用,可是ModelAndView已經極少再用了。專業的人作專業的事,我想這也是MVC模式out的緣由吧,沒有幾個服務端開發人員會本身寫模板了,無論是古董JSP,仍是Spring Boot所支持的Thymeleaf。後端

看來攤子有點爛,代碼要大改!服務器

相關文章
相關標籤/搜索