對(duì)于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:對(duì)于ModelAndView構(gòu)造函數(shù)可以指定返回頁(yè)面的名稱,也可以通過(guò)setViewName方法來(lái)設(shè)置所需要跳轉(zhuǎn)的頁(yè)面; PPS:返回的是一個(gè)包含模型和視圖的ModelAndView對(duì)象; @RequestMapping(method=RequestMethod.GET) public ModelAndView index(){ ModelAndView modelAndView = new ModelAndView(); modelAndView.addObject("xxx", "xxx"); modelAndView.setViewName("/user/index"); return modelAndView; }

Model
一個(gè)模型對(duì)象,主要包含spring封裝好的model和modelMap,以及java.util.Map,當(dāng)沒(méi)有視圖返回的時(shí)候視圖名稱將由requestToViewNameTranslator決定;
@RequestMapping(method=RequestMethod.GET) public Map<String, String> index(){ Map<String, String> map = new HashMap<String, String>(); map.put("1", "1"); //map.put相當(dāng)于request.setAttribute方法 return map; } PS:響應(yīng)的view應(yīng)該也是該請(qǐng)求的view。等同于void返回。
String
對(duì)于String的返回類型,筆者是配合Model來(lái)使用的;
@RequestMapping(method = RequestMethod.GET) public String index(Model model) { String retVal = "user/index"; List<User> users = userService.getUsers(); model.addAttribute("users", users); return retVal; } 或者通過(guò)配合@ResponseBody來(lái)將內(nèi)容或者對(duì)象作為HTTP響應(yīng)正文返回(適合做即時(shí)校驗(yàn)); @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:返回字符串表示一個(gè)視圖名稱,這個(gè)時(shí)候如果需要在渲染視圖的過(guò)程中需要模型的話,就可以給處理器添加一個(gè)模型參數(shù),然后在方法體往模型添加值就可以了,
Void
當(dāng)返回類型為Void的時(shí)候,則響應(yīng)的視圖頁(yè)面為對(duì)應(yīng)著的訪問(wèn)地址
@Controller @RequestMapping(value="/type") public class TypeController extends AbstractBaseController{ @RequestMapping(method=RequestMethod.GET) public void index(){ ModelAndView modelAndView = new ModelAndView(); modelAndView.addObject("xxx", "xxx"); } } 返回的結(jié)果頁(yè)面還是:/type PS:這個(gè)時(shí)候我們一般是將返回結(jié)果寫(xiě)在了HttpServletResponse 中了,如果沒(méi)寫(xiě)的話,spring就會(huì)利用RequestToViewNameTranslator 來(lái)返回一個(gè)對(duì)應(yīng)的視圖名稱。如果這個(gè)時(shí)候需要模型的話,處理方法和返回字符串的情況是相同的。
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

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