1. 程式人生 > >spring mvc中接收表單提交的資料的幾種方式

spring mvc中接收表單提交的資料的幾種方式

spring mvc封裝資料的物件有session、request、ModelAndView、ModelMap、Model、Map

Map map,Model model,ModelMap mmap,ModelAndView mav,HttpServletRequest request 宣告變數 
request.getSession().setAttribute("test", "hello spring mvc!"); 
request.setAttribute("test", "hello spring mvc!"); 
mav.addObject("test","hello spring mvc!");
mmap.addAttribute("test", "hello spring mvc!"); 
model.addAttribute("test", "hello spring mvc!"); 
map.put("test","hello spring mvc!");

在跳轉頁面可以通過${test}方式取值,優先取Map、Model和ModelMap的,Map、Model和ModelMap是同一個東西,誰最後賦值的就取誰的,然後是request,最後是從session中獲取 假如想直接取request.getParameter("test"),則用${param.test}

例:

@Controller
@SessionAttributes(value="message")
public class IndexController{
	//1.使用request獲取頁面資料,並傳遞給跳轉頁面
	@RequestMapping(value="index1")
	public String hello1(HttpServletRequest request) {
		String s1=request.getParameter("userName");
		System.out.println(s1);
		request.setAttribute("message", s1);
		
		return "hello";
	}

    //2.使用ModelAndVies包裝返回頁面資料
	@RequestMapping(value="index2")
	public ModelAndView hello2(String userName) {
		System.out.println(userName);
		ModelAndView mav=new ModelAndView("hello");
		mav.addObject("message", userName);
		return mav;
	}
	
    //3.使用ModelMap包裝返回頁面資料
	@RequestMapping(value="index3")
    //@RequestParam("userName")String name  接收的引數為userName,為其起名為name
	public String hello3(@RequestParam("userName")String name,ModelMap mm) {
		System.out.println(name);
		String s3=name;
		mm.addAttribute("message", s3);
		return "hello";
	}

	//4.使用Model包裝返回頁面資料
	@RequestMapping(value="index4")
    //@RequestParam("userName")String name  接收的引數為userName,為其起名為name
	public String hello4(@RequestParam("userName")String name,Model model) {
		System.out.println(name);
		String s3=name;
		model.addAttribute("message", s3);
		return "hello";
	}
	
    //5.使用Map包裝返回頁面資料
	@RequestMapping(value="index4")
	public String hello5(String userName,Map map) {
		System.out.println(userName);
		String s4=userName;
		map.put("message", s4);
		return "hello";
	}

	//6.使用Map包裝物件
	@RequestMapping(value="index6")
	public String hello6(userInfo userinfo,Map map) {
		System.out.println(userinfo);
		Date date=new Date();
		userinfo.setDate(date);
		map.put("message", userinfo);
		return "hello";
	}
	
    //測試返回頁面取值對Map、Model、ModelMap、ruquest、session的設值的先後
	@RequestMapping(value="index7")
	public String hello7(HttpServletRequest request,HttpServletResponse response,Map map,Model model,ModelMap mm) {
		String s1=request.getParameter("userName");
		
		mm.addAttribute("message", "天明mm");
		model.addAttribute("message", "天明model");
		map.put("message","天明map");
		request.setAttribute("message", s1);
		
		return "hello";
	}
}