Controller的三種返回類型中html
ModelAndView類型 帶數據帶跳轉頁面ajax
String 跳轉頁面不帶數據json
void 一般是ajax格式請求時使用app
controller方法中定義ModelAndView對象並返回,對象中可添加model數據、指定view。jsp
controllerpost
@RequestMapping("/test") public ModelAndView test(){ ModelAndView mav=new ModelAndView("hello");//經過ModelAndView構造方法能夠指定返回的頁面名稱,也能夠經過setViewName()方法跳轉到指定的頁面 mav.addObject("time", new Date()); mav.getModel().put("name", "caoyc"); return mav; }
JSPurl
time:${requestScope.time}
<br/>
name:${name }
controller方法返回字符串能夠指定邏輯視圖名,經過視圖解析器解析爲物理視圖地址。spa
@RequestMapping(value = "saveRegSigned") public String saveRegSigned(MeetingReg meetingReg, HttpServletRequest request, HttpServletResponse response, Model model) throws Exception { meetingReg.setMeetingId(Utils.getMeetingId(request)); Map<String, Object> resultMap = regService.saveRegSigned(meetingReg); model.addAttribute("resultMap", resultMap); return "modules/meeting/signed/RegSignedReturnPage"; }
JSPcode
<div class="code_reg">
<ul>
<li>註冊號:${resultMap.regCode}</li>
<li>註冊類型:${resultMap.regType}</li>
</ul>
</div>
void htm
若是返回值爲空,則響應的視圖頁面對應爲訪問地址
@RequestMapping("/index") public void index() { return; }
對應的邏輯視圖名爲"index"
Map
@RequestMapping("/demo2/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; }
在jsp頁面中可直經過${key1}得到到值, map.put()至關於request.setAttribute方法。
對應的邏輯視圖名爲../demo2/show+suffix
返回其餘object類型同map
1.使用 String 做爲請求處理方法的返回值類型是比較通用的方法,這樣返回的邏輯視圖名不會和請求 URL 綁定,具備很大的靈活性,而模型數據又能夠經過 ModelMap 控制。
2.使用void,map,Model 時,返回對應的邏輯視圖名稱真實url爲:prefix前綴+視圖名稱 +suffix後綴組成。
3.使用String,ModelAndView返回視圖名稱能夠不受請求的url綁定,ModelAndView能夠設置返回的視圖名稱。
參考http://www.cnblogs.com/xiepeixing/p/4243801.html
在controller方法形參上能夠定義request和response,使用request或response指定響應結果:
一、使用request轉向頁面,以下:
request.getRequestDispatcher("頁面路徑").forward(request, response);
二、也能夠經過response頁面重定向:
response.sendRedirect("url")
三、也能夠經過response指定響應結果,例如響應json數據以下: response.setCharacterEncoding("utf-8"); response.setContentType("application/json;charset=utf-8"); response.getWriter().write("json串");