springMVC中的数据传递方式与JSP和Struts2相比,更加的简单。具体有什么样的区别呢?我们通过下面这张图来对比就知道了。
随手画的,有些错别字,不用太在意.....
接下来,进入正题,springMVC中的常用数据传递方式有以下三种:
一、基本数据类型
二、自定义类型
三、地址栏传递
第二种最常用,分页时使用第三种。
具体实现步骤如下:
一、基本数据类型,使用@RequestParam接收数据,注意表单元素的name属性和@RequestParam的值要一一对应
1.1)创建login.jsp页面
1
2
3
4
5
6
7
|
< body >
< form action = "login1.form" method = "post" >
账号:< input name = "loginid" type = "text" />< br />
密码:< input name = "loginpwd" type = "password" />< br />
< input type = "submit" value = "登录" />
</ form >
</ body >
|
1.2)在MyController中新建login1方法
1
2
3
4
5
6
7
8
|
@RequestMapping ( "/login1" )
public String lgoin1( @RequestParam ( "loginid" ) String username,
@RequestParam ( "loginpwd" ) String userpwd){
System.out.println( "账号:" +username);
System.out.println( "密码:" +userpwd);
return "index.jsp" ;
}
|
1.3)访问login.jsp并提交数据,在地址栏输入http://localhost:8888/spDemo/login.jsp,并输入账号和密码。
从上面的代码应该可以看出私人定制是多么的好用了吧,哇哈哈哈哈·····
二、自定义类型,使用@ModelAttribute来接收数据
2.0)新建User类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
public class User {
private String loginid;
private String loginpwd;
public String getLoginid() {
return loginid;
}
public void setLoginid(String loginid) {
this .loginid = loginid;
}
public String getLoginpwd() {
return loginpwd;
}
public void setLoginpwd(String loginpwd) {
this .loginpwd = loginpwd;
}
} |
2.1)在MyController中新建login2方法
1
2
3
4
5
6
|
@RequestMapping ( "/login2" )
public String login2( @ModelAttribute ( "user" ) User use){
System.out.println( "账号:" +use.getLoginid());
System.out.println( "密码:" +use.getLoginpwd());
return "index.jsp" ;
}
|
2.2)修改login.jsp中form的action属性为login2
1
2
3
4
5
|
< form action = "login2.form" method = "post" >
账号:< input name = "loginid" type = "text" />< br />
密码:< input name = "loginpwd" type = "password" />< br />
< input type = "submit" value = "登录" />
</ form >
|
2.3)访问login.jsp并提交数据
以属性的方式来传递数据是不是更加的清晰简单明了!!!
三、地址栏传递,使用@PathVariable来接收数据。
3.1)在MyController中新建login2方法
1
2
3
4
5
6
7
|
@RequestMapping ( "/login_{idx}_{no}" )
public String login3( @PathVariable ( "idx" ) int index, @PathVariable ( "no" ) int number){
System.out.println( "值1:" +index);
System.out.println( "值2:" +number);
return "index.jsp" ;
}
|
2.2)在地址栏输入http://localhost:8888/spDemo/login_13_250.form进行访问。
OK,到这儿springMVC数据传递中的接收数据就告一阶段,细心的客官应该已经发现,他喵的只能接收数据,不能继续向index.jsp页面传递啊!!!
莫急莫急,欲知如何继续向下一页面传递数据,我们下一篇再来分解!!!