springMVC Controller层中请求参数的传递

Controller层中请求参数的传递

  1. 普通参数传输的传递
    直接在controller方法中以同前端参数名一致的方法形参即可,尽量保证数据类型一致。
@RequestMapping("lg5")
public void login5(String uname, int upwd, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    //方法的参数用于接收数据
    System.out.println("uname:" + uname);
    System.out.println("upwd:" + upwd);
    System.out.println("hello springmvc");
    request.setAttribute("uname",uname);
    request.getRequestDispatcher("success.jsp").forward(request,response);
}


  1. 对象数据参数传递
@RequestMapping("regist")
public String regist(User user){
    System.out.println(user);
    return "success.jsp";
}

  1. Checkbox参数传递
@RequestMapping("regist")
public String regist(User user,String[] hobby){
    System.out.println(user);
    for(String s: hobby){
        System.out.println(s);
    }
    return "success.jsp";
}

如果checkbox对应的数据也是user对象中的一个属性时,对象中可以使用String[] hobby作为对象的属性.

  1. 当前端参数和controller方法的参数名称不一致时处理方式
    在controller方法中使用@RequestParam注解,对方法的参数重新赋值
@RequestMapping("lg6")
public void login6(String uname, @RequestParam(name = "upwd") String upasswd, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    //方法的参数用于接收数据
    System.out.println("uname:" + uname);
    System.out.println("upwd:" + upasswd);
    System.out.println("hello springmvc");
    request.setAttribute("uname",uname);
    request.getRequestDispatcher("success.jsp").forward(request,response);
}


4.参数默认值设定

@RequestMapping("lg6")
public void login6(@RequestParam(defaultValue = "abc") String username, @RequestParam(name = "upwd") String upasswd, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    //方法的参数用于接收数据
    System.out.println("uname:" + username);
    System.out.println("upwd:" + upasswd);
    System.out.println("hello springmvc");
    request.setAttribute("uname",username);
    request.getRequestDispatcher("success.jsp").forward(request,response);
}


@RequestParam注解默认值设定是在页面没有传递相应数据的前提下有效,即参数列表中不包含该参数,接收的数据是null,往往用于分页的页码默认值设定。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值