Spring MVC--------處理方法返回值的可選類型

對於Spring MVC處理方法支持支持一系列的返回方式: 

(1)ModelAndView 
(2)Model 
(3)ModelMap 
(4)Map 
(5)View 
(6)String 
(7)Voidsession

(8)Objectmvc

 

一,ModelAndViewapp

  @RequestMapping("/threadRequest*")
    public ModelAndView threadRequest(){
        ModelAndView mv=new ModelAndView();
        mv.setViewName("index");
        mv.addObject("user","王五");
        return mv;
    }

經過ModelAndView構造方法能夠指定返回的頁面名稱,也能夠經過setViewName()方法跳轉到指定的頁面 , 
使用addObject()設置須要返回的值,addObject()有幾個不一樣參數的方法,能夠默認和指定返回對象的名字。 
調用addObject()方法將值設置到一個名爲ModelMap的類屬性,ModelMap是LinkedHashMap的子類, jsp

二,Model url

Model是一個接口, 其實現類爲ExtendedModelMap,繼承了ModelMap類。spa

model.addAttribute("pojo", pojo);excel

三,ModelMap code

Model 是一個接口, 其實現類爲ExtendedModelMap,繼承了ModelMap類。 對象

四,Map blog

@RequestMapping("/show")  
    public Map<String, String> getMap() {  
        Map<String, String> map = new HashMap<String, String>();  
        map.put("key1", "value-1");  
        map.put("key2", "value-2");  
        return map;  
    }  

 

五,View 

能夠返回pdf excel

六,String 

@RequestMapping("/RequestMethod")
    public String index(Model model) {
        String retVal = "user/index";
        List<User> users = userService.getUsers();
        model.addAttribute("users", users);

        return retVal;
    }

一、若是返回值爲null,那麼以請求名做爲視圖名進行跳轉

二、若是指定返回值,那麼按照指定返回值做爲視圖名進行跳轉,能夠經過model,modeMap攜帶數據。

三、若是返回值帶有forward或者redirect前綴,那麼將會進行相應的請求或重定向,不過不能經過mvc的數據模型攜帶數據,能夠經過ServletApi攜帶數據。

 

七,Void

 @RequestMapping("/index")
    public void firstRequest(HttpServletRequest request, HttpServletResponse response,HttpSession session) throws ServletException, IOException {

        UserInfo info=new UserInfo();
        info.setUser_id(1);
        info.setUser_name("張三");
        /**
         * Json格式傳遞
         */
        response.setCharacterEncoding("UTF-8");
        String value=JSON.toJSONString(info);
        response.getWriter().write(value);
    }

 

八,Object

 

   @RequestMapping("/fourthRequest")
    @ResponseBody   //響應體返回數據時,除了手動裝換JSON格式字符串之外能夠使用jackson
    public Object fourthRequest(){
        List<UserInfo> userList=new ArrayList<>();
        UserInfo info=new UserInfo();
        info.setUser_id(1);
        info.setUser_name("張三");
        UserInfo info2=new UserInfo();
        info2.setUser_id(2);
        info2.setUser_name("李四");
        userList.add(info);
        userList.add(info2);
        return userList;
    }

 

1.當方法返回值爲Null時,默認將請求路徑當作視圖  /jsp/thread/secondRequest.jsp  若是說沒有試圖解析器,若是返回值爲Null攜帶數據只能用JSON
2.當方法返回值爲String類型字符串時,就是視圖的邏輯名稱
3.當返回對象或者集合數據時,要使用Json格式字符串,可選fastJson手動轉換,也能夠使用jackson自動轉換


小結: 


1.使用 String 做爲請求處理方法的返回值類型是比較通用的方法,這樣返回的邏輯視圖名不會和請求 URL 綁定,具備很大的靈活性,而模型數據又能夠經過 ModelMap 控制。 
2.使用void,map,Model 時,返回對應的邏輯視圖名稱真實url爲:prefix前綴+視圖名稱 +suffix後綴組成。 
3.使用String,ModelAndView返回視圖名稱能夠不受請求的url綁定,ModelAndView能夠設置返回的視圖名稱


目前我只知道這八種,若是還有能夠在下方留言,評論,我會對其進行補充,謝謝你們!
相關文章
相關標籤/搜索