Spring Boot 学习之Controller

 

注解用途
@Controller处理http请求
@RestControllerspring 4 新加注解,@RestController = @Controller + @ResponseBody ,
@RequestMapping配置url映射
@PathVariable获取url中的数据
@RequestParam获取请求参数的值
@GetMapping组合注解

@RequestMapping 的使用

@RequestMapping 可以放在Controller 的类上,也可以放在方法上

/**
 * Created by Administrator on 2017/5/28.
 */
@RestController
@RequestMapping("/hello")
public class GetManInfo {
    
    @Autowired
    private ManInfoProperties manInfoProperties;

    @RequestMapping(value = "/getManInfo",method= RequestMethod.GET)
    public  String getManInfo(){
        return manInfoProperties.getAge();
    }

}

请求路径: 类上的路径+ 方法上的 路径,这里是

 http://127.0.0.1:8081/hello/getManInfo

也可以不要类上的路径

/**
 * Created by Administrator on 2017/5/28.
 */
@RestController
public class GetManInfo {
    
    @Autowired
    private ManInfoProperties manInfoProperties;

    @RequestMapping(value = "/getManInfo",method= RequestMethod.GET)
    public  String getManInfo(){
        return manInfoProperties.getAge();
    }

}

请求路径: 方法上的 路径,这里是

 http://127.0.0.1:8081/getManInfo

@PathVariable 的使用

@PathVariable是获取url中的数据,这里我没假设url 里面有一个id

@RestController
public class GetManInfo {
    @RequestMapping(value = "/hello/{id}" , method = RequestMethod.GET)
   public  String getId(@PathVariable("id") int id){
       return "id:"+id;
   }
}

试一试

http://127.0.0.1:8081/hello/18

结果

@PathVariable 的使用.png

@RequestParam 的使用

@RequestParam 用来获取请求参数的值 post 和 get ,put 等等都可以

@RestController
public class GetManInfo {
    @RequestMapping(value = "/hello" , method = RequestMethod.GET)
   public  String getId(@RequestParam int id){

       return "id:"+id;
   }
}

请求:

http://127.0.0.1:8081/hello?id=18

结果:

 

@RequestParam 使用

@RequestParam 还可以有一些设置,required 是否必传,defaultValue 默认值

@RestController
public class GetManInfo {
    @RequestMapping(value = "/hello" , method = RequestMethod.GET)
   public  String getId(@RequestParam( value = "id" , required = false,defaultValue = "0") int id){

       return "id:"+id;
   }
}

组合注释的使用( @GetMapping 、 @PostMapping、@PutMapping、@DeleteMapping 等等)

以@GetMapping 为例

    @GetMapping(value = "/hello")

等价于

  @RequestMapping(value = "/hello" , method = RequestMethod.GET)

其他的也一样

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值