ps:當model中存入了數據,如果使用重定向跳轉方式,那么SpringMVC會自動將model中的數據存放在地址欄中傳遞
-
向session作用域中存入數據,需要在類上加一個注解:
@SessionAttributes({"屬性名..."})
通過這個注解,可以指定將model中的那些命名屬性存入session作用域中一份
@Controller @RequestMapping("/model") public class ModelController { @RequestMapping("/modelTest1") public String modelTest1(Model model, HttpServletRequest request){ //向request作用域存入數據 request.setAttribute("rname","藍銀皇!"); //使用model向request作用域中存數據 model.addAttribute("mname","昊天錘!"); return "index"; }
@RequestMapping("/modelMap") public String modelMap(Model model){ //向request作用域存數據 Map<String, String> map = new HashMap<>(); map.put("dadada","大大大怪獸"); map.put("shudaixiong","樹袋熊"); model.addAllAttributes(map); return "success"; }
/** * 使用modelAndView進行數據和視圖的處理 * @return */ @RequestMapping("/mv") public ModelAndView modelAndView(){ ModelAndView mv = new ModelAndView(); //可以向作用域存入數據 mv.addObject("name","大大大怪獸"); //可以設置跳轉的視圖:參數書寫的方式與方法的返回值為String書寫的方式一樣 mv.setViewName("forward:/success.jsp"); return mv; }