SpringMVC入门 (二) 数值传递

环境还是上一篇的环境 http://alleni123.iteye.com/admin/blogs/1985571
这里就演示一下如何跟前台传递以及接收数值.

1.接收数值
修改LoginController的hello方法内容如下:

@RequestMapping({"/hello","/"})
	public String hello(@RequestParam("username") String username){
		System.out.println("hello= "+username);
		return "hello";
	}

在浏览器中输入 项目地址+/hellomvc/hello?username=alleni
可以看到后台输出: hello alleni


2.传递数值
修改上面的方法:
       //这里去掉了@RequestParam("username"),不然会报错Required String parameter 'username' is not present。必须在请求中加入username的键值才行。
        @RequestMapping({"/hello","/"})
	public String hello(Map<String,String>context){
                context.put("username","eline");
		return "hello";
	}

在hello.jsp中加入:hello -> ${username}
打开浏览器,输入/hellomvc/hello,就可以看到context里面的数值被传到了页面上。

这里也可以用Spring提供的Model来传值:
	@RequestMapping({"/hello","/"})
	public String hello(@RequestParam("username") String username, Model model){
		//context.put("username", "eline");
		model.addAttribute("username", "eline");
		return "hello";
	}

Model和Map的作用是一样的,也是通过键值对来完成后台到前台的传值。进入Model源码就可以看到:
/**
	 * Return the current set of model attributes as a Map.
	 */
	Map<String, Object> asMap();



============================================
Model还有一个方法addAttribute(Object obj);
这里其实也是放置键值对到Model对象里面,只是key值由Spring通过对象类型来赋值。

比如我们输入 model.addAttribute(username);
这里Spring就会检测username的类型,得知是String以后,便将key设置成string.


这里举一个例子:
model.addAttribute(new User(1,"alleni"));
上面等价于:
mode.addAttribute("user",new User(1,"alleni"));
因为Spring查到参数是User类型,就把key设置成user了。


猜你喜欢

转载自alleni123.iteye.com/blog/1986709