SpringMVC学习-页面传参

向页面传参

  1. 把参数放到Model,Map或ModelMap中
	@RequestMapping(value="/addUser")
	public String addUser(Model model,Map map1,Map<String,Object> map2,ModelMap modelMap){
		model.addAttribute("genders",Gender.values());
		map1.put("cities",UserService.listCitys());
		map2.put("skills",UserService.listSkills());
		modelMap.addAttribute("user",new User());	
		return "/databind/addUser";
	}

输入图片说明

2 参数放到ModelAndView中

	@RequestMapping(value="/modelAndView")
	public ModelAndView modelAndView(){
		ModelAndView mv=new ModelAndView();
		mv.setViewName("/databind/parameters");
		mv.addObject("title","modelAndView");
		mv.addObject("cities",UserService.listCitys());
		mv.addObject("skills",UserService.listSkills());			
		return mv;
	}

3 参数放到request或session中

	@RequestMapping(value="/sessionAttribute")
	public String sessionAttribute(HttpServletRequest request){
		request.setAttribute("title", "Hello World");
		HttpSession session=request.getSession();
		session.setAttribute("cities",UserService.listCitys());
		session.setAttribute("skills",UserService.listSkills());
		return "/databind/session";
	}

获取页面参数

1 从request 中获取

	@RequestMapping(value="/disPlayUser1")
	public void disPlayUser1(Writer writer,HttpServletRequest request) throws IOException{
			writer.write("username:"+request.getParameter("username")+"\n");
			writer.write("gender:"+request.getParameter("gender")+"\n");
			writer.write("birthday:"+request.getParameter("birthday")+"\n");
			writer.write("skills:"+Arrays.asList(request.getParameterMap().get("skills"))+"\n");
			writer.write("city:"+request.getParameter("city")+"\n");
			writer.write("description:"+request.getParameter("description")+"\n");
	}

2 通过参数传递 controller参数名和表单元素的name属性相同

<form action="disPlayUser2.mvc">  
	username:<input type="text" name="username">

@RequestMapping(value="/disPlayUser2")
public void disPlayUser2(Writer writer,String username,Gender gender,String birthday,
     String[] skills,String city,String description) throws IOException{//不能用List<String> skills
			writer.write("username:"+username+"\n");
			writer.write("gender:"+gender+"\n");
			writer.write("birthday:"+birthday+"\n");
			writer.write("skills:"+Arrays.asList(skills)+"\n");
			writer.write("city:"+city+"\n");
			writer.write("description:"+description);
	}

3 通过PO传递 如果使用springmvc标签库,设置表单的modelAttribute属性,path指定要绑定的属性名

<mvc:form  modelAttribute="user" action="saveUser.mvc">
        <mvc:label path="username">username:</mvc:label>

public void disPlayUser(Writer writer,User user) throws IOException{
		writer.write(user.toString());
	}

输入图片说明

转载于:https://my.oschina.net/Endless2010/blog/1507237

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值