package com.boventech.learning.controller; import java.util.HashMap; import java.util.Map; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import com.boventech.learning.entity.User; /** * MVCReturn * @author peng.xia * */ @Controller @RequestMapping("/MVCReturn") public class SpringMVCReturnController { @RequestMapping(value="/index1",method=RequestMethod.GET) public ModelAndView index(){ ModelAndView modelAndView = new ModelAndView("/user/index"); modelAndView.addObject("name", "xxx"); return modelAndView; } //對於ModelAndView構造函數可以指定返回頁面的名稱,也可以通過setViewName方法來設置所需要跳轉的頁面; @RequestMapping(value="/index2",method=RequestMethod.GET) public ModelAndView index2(){ ModelAndView modelAndView = new ModelAndView(); modelAndView.addObject("name", "xxx"); modelAndView.setViewName("/user/index"); return modelAndView; } //返回的是一個包含模型和視圖的ModelAndView對象; /** * Model一個模型對象, * 主要包含spring封裝好的model和modelMap,以及java.util.Map, * 當沒有視圖返回的時候視圖名稱將由requestToViewNameTranslator決定; * @return */ @RequestMapping(value="/index3",method=RequestMethod.GET) public Map<String, String> index3(){ Map<String, String> map = new HashMap<String, String>(); map.put("1", "1"); //map.put相當於request.setAttribute方法 return map; } //響應的view應該也是該請求的view。等同於void返回。 //返回String //通過model進行使用 @RequestMapping(value="/index4",method = RequestMethod.GET) public String index(Model model) { String retVal = "user/index"; User user = new User(); user.setName("XXX"); model.addAttribute("user", user); return retVal; } //通過配合@ResponseBody來將內容或者對象作為HTTP響應正文返回(適合做即時校驗); @RequestMapping(value = "/valid", method = RequestMethod.GET) @ResponseBody public String valid(@RequestParam(value = "userId", required = false) Integer userId, @RequestParam(value = "name") String name) { return String.valueOf(true); } //返回字符串表示一個視圖名稱,這個時候如果需要在渲染視圖的過程中需要模型的話,就可以給處理器添加一個模型參數,然后在方法體往模型添加值就可以了, @RequestMapping(method=RequestMethod.GET) public void index5(){ ModelAndView modelAndView = new ModelAndView(); modelAndView.addObject("xxx", "xxx"); } //返回的結果頁面還是:/type //這個時候我們一般是將返回結果寫在了HttpServletResponse 中了,如果沒寫的話, //spring就會利用RequestToViewNameTranslator 來返回一個對應的視圖名稱。如果這個時候需要模型的話,處理方法和返回字符串的情況是相同的。 }