javascript
SpringMVC Controller的返回类型
Controller的三種返回類型中
ModelAndView類型 帶數(shù)據(jù)帶跳轉(zhuǎn)頁面
String 跳轉(zhuǎn)頁面不帶數(shù)據(jù)
void 通常是ajax格式請求時使用
?
1返回ModelAndView
controller方法中定義ModelAndView對象并返回,對象中可添加model數(shù)據(jù)、指定view。
controller
@RequestMapping("/test") public ModelAndView test(){ModelAndView mav=new ModelAndView("hello");//通過ModelAndView構(gòu)造方法可以指定返回的頁面名稱,也可以通過setViewName()方法跳轉(zhuǎn)到指定的頁面mav.addObject("time", new Date());mav.getModel().put("name", "caoyc");return mav; }JSP
time:${requestScope.time}<br/>name:${name }?
2? ?返回字符串 ?
controller方法返回字符串可以指定邏輯視圖名,通過視圖解析器解析為物理視圖地址。
@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";}JSP
<div class="code_reg"><ul><li>注冊號:${resultMap.regCode}</li><li>注冊類型:${resultMap.regType}</li></ul></div>?
3? ?返回void
void?
如果返回值為空,則響應(yīng)的視圖頁面對應(yīng)為訪問地址
@RequestMapping("/index") public void index() {return; }對應(yīng)的邏輯視圖名為"index"
?
4返回map
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()相當(dāng)于request.setAttribute方法。
對應(yīng)的邏輯視圖名為../demo2/show+suffix
返回其他object類型同map
?
1.使用 String 作為請求處理方法的返回值類型是比較通用的方法,這樣返回的邏輯視圖名不會和請求 URL 綁定,具有很大的靈活性,而模型數(shù)據(jù)又可以通過 ModelMap 控制。
2.使用void,map,Model 時,返回對應(yīng)的邏輯視圖名稱真實url為:prefix前綴+視圖名稱 +suffix后綴組成。
3.使用String,ModelAndView返回視圖名稱可以不受請求的url綁定,ModelAndView可以設(shè)置返回的視圖名稱。
參考http://www.cnblogs.com/xiepeixing/p/4243801.html
????在controller方法形參上可以定義request和response,使用request或response指定響應(yīng)結(jié)果:
? ? 1、使用request轉(zhuǎn)向頁面,如下:
????request.getRequestDispatcher("頁面路徑").forward(request, response);
? ? ? 2、也可以通過response頁面重定向:
????response.sendRedirect("url")
? ? ?3、也可以通過response指定響應(yīng)結(jié)果,例如響應(yīng)json數(shù)據(jù)如下:
????response.setCharacterEncoding("utf-8");
????response.setContentType("application/json;charset=utf-8");
????response.getWriter().write("json串");
?
?
?
?
?
?
?
轉(zhuǎn)載于:https://www.cnblogs.com/miye/p/6970436.html
總結(jié)
以上是生活随笔為你收集整理的SpringMVC Controller的返回类型的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Drawable 添加过滤色,改变图片颜
- 下一篇: Spring Cloud基础教程