SpringMvc Controller中几种参数的绑定

1•SpringMVC默认支持的绑定类型有:

2•HttpServletRequest对象:通过request对象可以获取参数信息

3•HttpServletResponse对象:通过response对象可以处理响应信息

4•HttpSession对象:获取session中存储的对象

5•Model/ModelMap:Model是一个接口,ModelMap是一个接口的实现。作用是将模型数据填充到request域。

直接在controller中定义一个变量,但是此种传输方式有一个限制就是参数名和请求中的参数名必须保持一致,否则是接收不到数据的。

Controller : public void controllerTest(Integer id){}

request : http://localhost:8080/springMvcTest/controllerTest?id=2;

使用@RequestParam进行参数绑定,在使用这个注解进行绑定的时候,参数名无需和请求中的参数名保持一致。 

Controller : public void controllerTest(@RequestParam(value="id") Integer goods_id){}

@RequestParam(value="id") Integer goods_id 表示将请求中的id属性绑定到goods_id这个参数上

 

传递对象参数

要求页面中input标签的name属性值和controller的pojo形参中的属性名称一致,即可将页面中数据绑定到pojo

Controller : public void controllerTest(User user){}

实体类:

public class User{

private String name;

private String realName;

private String pwd;

}

jsp页面:

<form action="" method="post">

<input name="name" type="text"/>

<input name="realName" type="text"/>

......

</form>

 

/**

   * 测试参数为HttpSession

   * @param session

   * @return

   */

  @RequestMapping("/testSession")

  public String testSession(HttpSession session){

  session.setAttribute("message", "zhanghw--haha");

  return "hello";

  }

/**

   * 测试参数为Model

   * @param model

   * @return

   */

  @RequestMapping("/testString2")

  public String testString2(Model model){

  //传递数据到hello.jsp上

  model.addAttribute("message", "Test String2");

  //request.setAttribute("message", "Test String");

  return "hello";//指定逻辑视图名,通过视图解析器解析为jsp物理路径

  } 

/**

   * 测试简单参数

   * @param id

   * @return

   */

  @RequestMapping("/testParameter")

  public String testParameter(Integer id){

  System.out.println(id);

  return "hello";

  }

 

/**

   * 测试注解简单参数

   * @param gid

   * @return

   */

  @RequestMapping("/testRequestParam")

  public String testRequestParam(@RequestParam(value="id")Integer gid){

  System.out.println(gid);

  return "hello";

  }

 

/**

   * 测试对象参数

   * @param user

   * @return

   */

  @RequestMapping("/testObjectParam")

  public String testObjectParam(User user){

  System.out.println(user.getName());

  System.out.println(user.getRealName());

  System.out.println(user.getPwd());

  return "hello";

  }

 

 

模拟用户注册,测试对象参数

<form action="${pageContext.request.contextPath}/testObjectParam.action" method="post">

  用户名:<input type="text" name="name">

  真实姓名:<input type="text" name="realName">

  密码:<input type="password" name="pwd">

  <input type="submit" value="注册">

</form><br>

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值