SpringMvc處理模型資料(也就是從資料庫中查詢出來的資料放到請求域中)

來源:互聯網
上載者:User

標籤:system   div   入參   spring   擷取值   模型   getc   log   目標   

這講的是從資料庫中查詢到的資料,存放到請求域中。然後頁面上直接可以從請求域中擷取值。

有4種方式:

  1):ModelAndView   是作為一個對象。

 1 /** 2      * 目標方法的傳回值可以是 ModelAndView 類型。  3      * 其中可以包含視圖和模型資訊 4      * SpringMVC 會把 ModelAndView 的 model 中資料放入到 request 域對象中.  5      * @return 6      */ 7     @RequestMapping("/testModelAndView") 8     public ModelAndView testModelAndView(){ 9         String viewName = SUCCESS;10         ModelAndView modelAndView = new ModelAndView(viewName);11         12         //添加模型資料到 ModelAndView 中.13         modelAndView.addObject("time", new Date());14         15         return modelAndView;16     }

從頁面上擷取:

    time: ${requestScope.time }

2:Model和Map   這兩個作為參數給傳進去。

1 @RequestMapping("/testMap")2     public String testMap(Map<String, Object> map){3         System.out.println(map.getClass().getName()); 4         map.put("names", Arrays.asList("Tom", "Jerry", "Mike"));5         return SUCCESS;6     }

3:@ModelAttribute

/**
     * 1. 有 @ModelAttribute 標記的方法, 會在每個目標方法執行之前被 SpringMVC 調用!
     * 2. @ModelAttribute 註解也可以來修飾目標方法 POJO 類型的入參, 其 value 屬性值有如下的作用:
     * 1). SpringMVC 會使用 value 屬性值在 implicitModel 中尋找對應的對象, 若存在則會直接傳入到目標方法的入參中.
     * 2). SpringMVC 會一 value 為 key, POJO 類型的對象為 value, 存入到 request 中.
     */
    @ModelAttribute
    public void getUser(@RequestParam(value="id",required=false) Integer id,
            Map<String, Object> map){
        System.out.println("modelAttribute method");
        if(id != null){
            //類比從資料庫中擷取對象
            User user = new User(1, "Tom", "123456", "[email protected]", 12);
            System.out.println("從資料庫中擷取一個對象: " + user);
            
            map.put("user", user);
        }
    }

 

SpringMvc處理模型資料(也就是從資料庫中查詢出來的資料放到請求域中)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.