@ModelAttribute

  • @ModelAttribute:
    該注解通常在Controller上的某個(gè)方法上,此方法會(huì)首先被調(diào)用,并將方法作為Mode的屬性,然后再調(diào)用對(duì)應(yīng)的Controller處理方法。

    利用postman做測(cè)試,localhost:8988/1633c318f09f4071a1609cb5b1a952c5/get.json

      @Resource
      private UserMapper userMapper;
    
      @ModelAttribute
      public User findByUserId(@PathVariable String id){
    
          return userMapper.selectByPrimaryKey(id);
      }
    
      @GetMapping("/{id}/get.json")
      @ResponseBody
      public Boolean getUser(Model model){
    
        if(model.containsAttribute("user")){
    
            return true;
        }else{
    
            return false;
        }
      }
    

    注:對(duì)于HTTP請(qǐng)求,會(huì)先調(diào)用findByUserId方法獲取user,并添加到模型里面使用,使用ModelAttribute可以向一個(gè)Controller中需要的公共模型中添加數(shù)據(jù)。

    如果findByUserId僅添加一個(gè)對(duì)象到Model中,可以寫成如下形式:

    @ModelAttribute
    public User findByUserId(@PathVariable String id){
    
         return userMapper.selectByPrimaryKey(id);
    }
    

    Model和ModelView的區(qū)別:
    Model:是每次請(qǐng)求中都存在的默認(rèn)參數(shù),利用其addAttribute()方法即可將[服務(wù)器]的值傳遞到j(luò)sp頁(yè)面中;
    ModelAndView:包含modelview兩部分,使用時(shí)需要自己實(shí)例化,利用ModelMap用來傳值,也可以設(shè)置view的名稱

    具體可以參考:
    https://blog.csdn.net/opera95/article/details/78498812
    https://blog.csdn.net/lpq374606827/article/details/78764139

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容