Day03 SpringBoot中Controller中各种注解的使用

RestController注解的使用

@RestController 等同于 @Controller和@ResponseBody

在某个方法上写@RestController ,则此方法的return返回的是json

@RestController
public class HelloController {

    @RequestMapping(value="/hello",method= RequestMethod.GET)
    public String sayHello(){
        return "hello";
    }
}

//上面代码等价于下面代码
@Controller
@ResponseBody
public class HelloController {

    @RequestMapping(value="/hello",method= RequestMethod.GET)
    public String sayHello(){
        return "hello";
    }
}

@RequestMapping 配置url映射

@RequestMapping此注解即可以作用在控制器的某个方法上,也可以作用在此控制器类上。

几种参数绑定

  • 1.无参类型
 @RequestMapping(value="/helloparam2",method= RequestMethod.GET)
 public String helloParam(){
        return "hello";
    }
@RequestMapping(value="/helloparam/{id}",method= RequestMethod.GET)
    public String helloParam(@PathVariable("id") Integer id){
        return "id:"+id;
    }
@RequestMapping(value="/helloparam3",method= RequestMethod.GET)
    //第一个id是与url地址参数相对应,第二个myid随意起名字
    //设置默认值,若不传id,则使用默认值
    public String helloParam3(@RequestParam(value = "id", required = false, defaultValue = "0") Integer myid){
        return "id:"+myid;
    }
    //若没有required = false, defaultValue = "0",则代表未设置默认值

@GetMapping 简化@RequestMapping书写

@GetMapping则代表get方式请求
@PostMapping则代表post方式请求
后续会说到以下几种
@PutMapping
@DeleteMapping

//简化@RequestMapping书写
    @GetMapping(value = "/helloparam4")
    public String helloParam4(@RequestParam(value = "id", required = false, defaultValue = "0") Integer myid){
        return "id:"+myid;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值