SpringMVC中 @RequestParam,@PathVariable,@RequestBody的使用

SpringMVC中,@RequestParam,@PathVariable,@RequestBody的使用

  • @RequestParam

HTML

<form action="demo" method="post">
<input type="text" name="name">
<input type="text" name="location">
<input type="submit">
<input type="checkbox"  name="h" value="h12">
<input type="checkbox"  name="h" value="h2">
<input type="checkbox"  name="h" value="h3">
<input type="checkbox"  name="h" value="h4">
</form>

Controllor

@RequestMapping("demo")
       public String demo1(@RequestParam(value="name")String  name1,@RequestParam(value="h")List<String>h) {
             System.out.println("demo1");
             System.out.println(name1+h);
             return "Main.jsp";
       }
  • @RequestParam(value="name")String name1 里面的value指的是匹配的参数名是name,
    为了简化,可以这样写@RequestParam String name,前提是能保证String后面的变量名和参数名是一样的

  • @RequestParam(value="h")List<String>h可以接受复杂参数。

  • @RequestBody传递的是json字符串,用在参数前

  • 可以直接传递pojo比如:

@RequestMapping(value="demo",method = RequestMethod.POST)
  @ResponseBody
  public Peoplle demo1(Peoplle peoplle) {
  	System.out.println(peoplle);
  	return peoplle;
  }
打印出来的数据 `Peoplle [name=张三, location=里斯]`
  • 当参数为空的时候,防止报错,可以设置默认值
@RequestMapping("demo")
       public String demo1(@RequestParam(defaultValue="null") Peoplle peoplle) {
         System.out.println("demo1");
         System.out.println(peoplle);

         return "Main.jsp";
  • 强制参数不能为空,否则报错
       @RequestMapping("demo")
       public String demo1(@RequestParam(required=true) Peoplle peoplle) {
             System.out.println("demo1");
             System.out.println(peoplle);
             return "Main.jsp";
       }
  • @PathVariable
    直接看代码吧

http://localhost:8080/HelloSpringMVC2/demo/da

@Controller
public class DemoControler {

   @RequestMapping("/demo/{id}")
   public void demo1(@PathVariable String id) {
   	System.out.println(id);
   }

console:da

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值