對于springMVC處理方法支持支持一系列的返回方式:
ModelAndView
Model
ModelMap
Map
View
String
Void
ModelAndView
@RequestMapping(method=RequestMethod.GET) public ModelAndView index(){ ModelAndView modelAndView = new ModelAndView("/user/index"); modelAndView.addObject("xxx", "xxx"); return modelAndView; } PS:對于ModelAndView構造函數可以指定返回頁面的名稱,也可以通過setViewName方法來設置所需要跳轉的頁面; PPS:返回的是一個包含模型和視圖的ModelAndView對象; @RequestMapping(method=RequestMethod.GET) public ModelAndView index(){ ModelAndView modelAndView = new ModelAndView(); modelAndView.addObject("xxx", "xxx"); modelAndView.setViewName("/user/index"); return modelAndView; }

Model
一個模型對象,主要包含spring封裝好的model和modelMap,以及java.util.Map,當沒有視圖返回的時候視圖名稱將由requestToViewNameTranslator決定;
@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返回。
String
對于String的返回類型,筆者是配合Model來使用的;
@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響應正文返回(適合做即時校驗); @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的時候,則響應的視圖頁面為對應著的訪問地址
@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 來返回一個對應的視圖名稱。如果這個時候需要模型的話,處理方法和返回字符串的情況是相同的。
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
