SpringMVC的五种请求传参方式

SpringMVC的五种请求传参方式
1、传统传参方式
  方法参数中使用request,通过request.getParameter(“参数名”),再封装到bean中

复制代码
@RequestMapping("/test01")
public ModelAndView test01(HttpServletRequest request){
String username = request.getParameter(“username”);
String password = request.getParameter(“password”);

  System.out.println(username);
  System.out.println(password);
  return null;

}
复制代码
2、简单类型参数和RequestParam注解
  如果请求参数和Controller方法的形参同名,可以直接接收

如果请求参数和Controller方法的形参不同名,可以使用@RequestParam注解贴在形参前,设置对应的参数名称

复制代码
@RequestMapping("/test02_1")
public ModelAndView test02_1(String username,String password){
System.out.println(username);
System.out.println(password);
return null;
}
@RequestMapping("/test02_2")
public ModelAndView test02_2(@RequestParam(“username”) String name,@RequestParam(value = “password”,defaultValue = “1234987”) String pwd){
//使用了@RequestParam的参数不能传空值
// required:表示是否必须要传值
// defaultValue:当没有该请求参数时,SpringMVC给请求参数的默认值
System.out.println(name);
System.out.println(pwd);
return null;
}
复制代码
3、对象传参
  此时能够自动把参数封装到形参的对象上

注意:1、请求参数必须和对象的属性同名

2、此时对象会直接放入request作用域中,名称为类型首字母小写

3、@ModelAttribute设置请求参数绑定到对象中并传到视图页面,设置key值

复制代码
@RequestMapping("/test03")
public ModelAndView test03(@ModelAttribute(“stu”) Student student){
/可以使用对象作为方法的形参,同时接受接受前台的多个请求参数
SpringMVC会基于同名匹配,将请求参数的值注入对应的对象中的属性中
@ModelAttribute起名字key值
/
System.out.println(student);
ModelAndView mv = new ModelAndView();
mv.setViewName(“test2”);
return mv;
}
复制代码
4、数组和List集合类型参数
  当前台页面传来的参数是参数名相同,参数值不同的多个参数时,可以直接封装到方法的数组类型的形参中,也可以直接封装到对象的集合属性中。

比如批量删除时传来的参数。

复制代码
RequestMapping("/test04")
public ModelAndView test04(String id[]){
/对于参数名相同的多个请求参数,可以直接使用数组作为方法的形参接收
可以使用对象中的集合属性接收
/
for (String i : id) {
System.out.println(i);
}
return null;
}
复制代码
复制代码
@RequestMapping("/test05")
public ModelAndView test05(Student student){
System.out.println(student.getId().size());
for (String i : student.getId()) {
System.out.println(i);
}
return null;
}
复制代码
5、使用Restful
  Restful是一种软件架构风格,严格上说是一种编码风格,其充分利用 HTTP 协议本身语义从而提供了一组设计原则和约束条件。

主要用于客户端和服务器交互类的软件,该风格设计的软件可以更简洁,更有层次,更易于实现缓存等机制。 在后台,RequestMapping标签后,可以用{参数名}方式传参,同时需要在形参前加注解@PathVarible,假如前台的请求地址为localhost:8080/delete/3

@RequestMapping("/delete/{id}")
public ModelAndView test4(@PathVariable(“id”)Long id){
System.out.println(“delete”);
System.out.println(id);
return null;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值