springMVC参数绑定_接收表单数据

springmvc参数绑定过程

  • 从客户端请求key/value数据,经过参数绑定,将key/value数据绑定到controller方法的形参上。
  • springmvc中,接收页面提交的数据是通过方法形参来接收,而不是在controller类定义成员变量接收。

基本数据类型绑定

页面准备form表单如下:

<form action="<%=request.getContextPath()%>/login_no_send_400.do" method="post">
id:<input type="text" name="id"/><br>
username:<input type="text" name="username"/><br>
password:<input type="text" name="password"/><br>
sex:<input type="text" name="sex"/><br>
学费:<input type="text" name="price"/><br>
状态:<input type="text" name="state"/><br>
<input type="submit" name="Login"/><br>
</form>

在Controller中获取表单数据方式如下:
使用这种方式获取表单数据时,若是在表单提交如果没有给值,那么会报400错误!这样使得提交表单必须有值,否则出错;

@RequestMapping("login.do")
	public ModelAndView login(int id,String username,String password,char sex,double price,boolean state)
	{
		//我们这个方法怎么能够获取表单数据呢?
		//String idstr=request.getParameter("id");
		//int id=Integer.parseInt(idstr);
		System.out.println(id);
		System.out.println(username);
		System.out.println(password);
		System.out.println(sex);
		System.out.println(price);
		System.out.println(state);
		return null;
	}

既然以上的方式获取表单数据时,表单没有数据就会出现400的错误,那么使用基本数据类型的封装类型就不会出现此类问题。

//这个方法的参数绑定都是封装类型,那么允许数据为null,所以表单有数据为空,后台接收不会报400错误
	@RequestMapping("login_no_send_400.do")
	public ModelAndView login_no_send_400(Integer id,String username,String password,Character sex,Double price,Boolean state)
	{
		System.out.println(id);
		System.out.println(username);
		System.out.println(password);
		System.out.println(sex);
		System.out.println(price);
		System.out.println(state);
		return null;
	}

封装类型绑定(POJO绑定)

使用以上方式的获取表单数据显然有些不和理,将数据封装到对象里面才是Java应该,通过对象拿数据,这才是正确的做法。
那上面的表单来说,有id、username、password、sex、price、state这些属性,定义一个实体类。将这些属性加到实体中,在请求时Spring自动为我将表单的数据封装到对象中去。前提就是form表单的name属性要和类的属性一致。
定义实体类如下:

public class User {
	
	private Integer id;
	private String username;
	private String password;
	private Character sex;
	private Double price;
	private Boolean state;
	//get和set方法这里省略不写
}

通过对数据的封装,获取表单数据就简单得多。
至于spring是如何实现这个功能的,那就需要debug看源码就可以知道一二了。

	/*
	 * 这个方法限定请求方式必须是post
	 */
	@RequestMapping("register.do")
	public ModelAndView register(User user)  //轻松地拿到了form表单的数据
	{
		return null;
	}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

code_mo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值