restful風格url


 
         
  • GET: 獲取資源
  • POST:創建或更新資源
  • PUT: 創建或更新資源
  • DELETE:刪除資源
  • HEAD:獲取資源的元數據,不常用
  • OPTIONS:獲取信息,關於資源的哪些屬性是客戶端可以改變的, 不常用

restful的增刪改查后端Java代碼:
    /**
     * 跳轉至詳情編輯頁面
     * @param model
     * @param id
     * @return
     */
    @RequestMapping({"/toEditNewsDetails/{id}","/toEditNewsDetails"})
    public String toEditNewsDetails(Model model, @PathVariable(value = "id",required = false) String id){
       LOGGER.info("傳遞過來的id:"+id);
        News news = newsMapper.selectByPrimaryKey(!StringUtils.isEmpty(id) ? Integer.parseInt(id) : -1);
        model.addAttribute("news",news);
        return "editDetails";
    }

    /**
     * 新增用戶
     *
     * @param news
     * @return
     */
    @RequestMapping(method = RequestMethod.POST)
//    @ResponseBody
    public String addUser(News news) {
//        Map<String,Object> res = new HashMap<String, Object>();
        try {
            LOGGER.info("進入方法addUser");
            news.setInsertTime(new Date());
            news.setUpdateTime(new Date());
            news.setIsDelete(false);
            news.setViews(0);
            int insert = newsMapper.insert(news);
            //res.put("status","succ");
            return "editDetails";
        } catch (Exception e) {
            e.printStackTrace();
            return "添加異常,請聯系管理員!";
        }
    }

    /**
     * 編輯修改
     * @param news
     * @param bindingResult
     * @return
     */
    @RequestMapping(method = RequestMethod.PUT)
    //@ResponseBody
    public String updateNews(News news,BindingResult bindingResult){//
        try {
            LOGGER.info("傳入參數:" + news);
            news.setUpdateTime(new Date());
            newsMapper.updateByPrimaryKey(news);

            return "editDetails";
        } catch (Exception e) {
            e.printStackTrace();
            return "更改異常,請聯系管理員!";
        }
    }

    /**
     * 刪除
     * @param model
     * @param id
     * @return
     */
    @RequestMapping(method = RequestMethod.DELETE)
    @ResponseBody
    public Map<String,Object> deleteNews(Model model, String id){
            Map<String,Object> res = new HashMap<String, Object>();
        try {
            int i = newsMapper.updateIsDelePrimaryKey(!StringUtils.isEmpty(id) ? Integer.parseInt(id) : -1);
            System.out.println("刪除結果為:"+(i==1?true:false));
            res.put("status","succ");
            return res;
        } catch (Exception e) {
            e.printStackTrace();
            res.put("status","error");
            res.put("msg",e.getMessage());
            return res;
        }
    }

 前端thymeleaf代碼:

//點擊確定,修改或添加
function confir(){
    //獲取富文本編輯器的內容,和獲取普通div內容一樣。
    var cont = $("#editor").html();
    var titleEditor = $("#titleEditor").val();
    // console.log(cont);

    var news_id = $("#confirmBtn").attr("news_id");
    var methodType = "";
    if ([[${news}]] != null) {
        var data_news = [[${news}]];//日期字段已轉換為字符串,傳遞到后端日期接收,或對象接收對象中共日期字段,需要轉換為日期類型傳遞過去。已測試后端接收到日期。
        methodType = 'PUT';
    }else {
        var data_news = {};
        methodType = 'POST';
    }
    var newsInput = $("#newsInput").val();
    //console.log(newsInput);
    console.log(data_news);
    data_news.content = cont;
    data_news.title = titleEditor;//"<b>"+titleEditor+"</b>";
    var formEle = document.getElementById("myForm");
    formEle.action = baseUrl+"/news";///updateNews
    var formData = new FormData(formEle);
    Object.keys(data_news).forEach((key) => {
        var obj = data_news[key];
        if(isNaN(obj)&&!isNaN(Date.parse(obj))){
            console.log("obj是日期格式!")
            formData.append(key, getDateByTimeStr(obj));
        }else{
            formData.append(key, obj);
        }
    });
    console.log(formData.get("insertTime"));
    //formEle.submit();
    //提交表單

    var xhr = new XMLHttpRequest();
    //設置響應返回的數據格式
    xhr.responseType = "json";
    if(false){

    }
    xhr.open(methodType, baseUrl+"/news", true);
    xhr.onload = function () {
        if (xhr.status == 200) {
            cancel();
        }else{
            console.log('An error occurred!'+xhr.status);
        }
        /* xhr.ontimeout = function(e) {
       console.log("請求超時");
         };*/
        xhr.onerror = function(e) {
            alert(e);
        };
    };

    xhr.send(formData);
}

 

該種寫法不夠完美,寫多個方法並且匹配的不是相同的url.強迫症表示不能接受

@PathVariable設置為空的問題(需要設置required=false否則為空會報錯)

// 127.0.0.1:8080/dep/test  查詢全部
    // 127.0.0.1:8880/dep/test/1     查詢ID為1
   @ApiOperation(value="測試同時實現查詢所有和根據id查詢", notes="測試同時實現查詢所有和根據id查詢")
    @RequestMapping(value = {"/test/{id}","/test"},method = RequestMethod.GET)
    public Object deps(@PathVariable( value = "id",required = false) String id) {
        if(StringUtils.isEmpty(id)){ // ID為空查全部
            return depService.queryAll();
        }else { // 不為空根據id查詢
            return depService.queryById(id);
        }
    }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM