springMVC對於controller處理方法返回值的可選類型

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

  1. ModelAndView
  2. Model
  3. ModelMap
  4. Map
  5. View
  6. String
  7. Void

具體介紹

詳細介紹每一個返回類型的各個特點;

ModelAndView

1
2
3
4
5
6
@RequestMapping(method=RequestMethod.GET)
    public ModelAndView index(){
        ModelAndView modelAndView = new ModelAndView("/user/index");
        modelAndView.addObject("xxx", "xxx");
        return modelAndView;
    }

PS:對於ModelAndView構造函數可以指定返回頁面的名稱,也可以通過setViewName方法來設置所需要跳轉的頁面;

PPS:返回的是一個包含模型和視圖的ModelAndView對象;

1
2
3
4
5
6
7
@RequestMapping(method=RequestMethod.GET)
    public ModelAndView index(){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("xxx", "xxx");
        modelAndView.setViewName("/user/index");
        return modelAndView;
    }

對於ModelAndView類的屬性和方法

Model

一個模型對象,主要包含spring封裝好的model和modelMap,以及java.util.Map,當沒有視圖返回的時候視圖名稱將由requestToViewNameTranslator決定;

ModelMap

待續

Map

1
2
3
4
5
6
7
@RequestMapping(method=RequestMethod.GET)
    public Map<String, String> index(){
        Map<String, String> map = new HashMap<String, String>();
        map.put("1", "1");
        //map.put相當於request.setAttribute方法
        return map;
    }
PS:響應的view應該也是該請求的view。等同於void返回。

View

這個時候如果在渲染頁面的過程中模型的話,就會給處理器方法定義一個模型參數,然後在方法體裏面往模型中添加值。

String

對於String的返回類型,筆者是配合Model來使用的;

1
2
3
4
5
6
7
8
@RequestMapping(method = RequestMethod.GET)
    public String index(Model model) {
        String retVal = "user/index";
        List<User> users = userService.getUsers();
        model.addAttribute("users", users);
 
        return retVal;
    }

或者通過配合@ResponseBody來將內容或者對象作爲HTTP響應正文返回(適合做即時校驗);

1
2
3
4
5
6
7
@RequestMapping(value = "/valid", method = RequestMethod.GET)
    public @ResponseBody
    String valid(@RequestParam(value = "userId", required = false) Integer userId,
            @RequestParam(value = "logName") String strLogName) {
        return String.valueOf(!userService.isLogNameExist(strLogName, userId));
 
    }

ps:返回字符串表示一個視圖名稱,這個時候如果需要在渲染視圖的過程中需要模型的話,就可以給處理器添加一個模型參數,然後在方法體往模型添加值就可以了,

Void

當返回類型爲Void的時候,則響應的視圖頁面爲對應着的訪問地址

1
2
3
4
5
6
7
8
9
10
@Controller
@RequestMapping(value="/type")
public class TypeController extends AbstractBaseController{
 
    @RequestMapping(method=RequestMethod.GET)
    public void index(){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("xxx", "xxx");
    }
}

返回的結果頁面還是:/type

PS:這個時候我們一般是將返回結果寫在了HttpServletResponse 中了,如果沒寫的話,spring就會利用RequestToViewNameTranslator 來返回一個對應的視圖名稱。如果這個時候需要模型的話,處理方法和返回字符串的情況是相同的。

發佈了28 篇原創文章 · 獲贊 11 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章