Spring Boot 學(xué)習(xí)之路三 Controller

注解 用途
@Controller 處理http請求
@RestController spring 4 新加注解,@RestController = @Controller + @ResponseBody ,
@RequestMapping 配置url映射
@PathVariable 獲取url中的數(shù)據(jù)
@RequestParam 獲取請求參數(shù)的值
@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中的數(shù)據(jù),這里我沒假設(shè)url 里面有一個(gè)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

結(jié)果

@PathVariable 的使用.png

@RequestParam 的使用

@RequestParam 用來獲取請求參數(shù)的值 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

結(jié)果:


@RequestParam 使用

@RequestParam 還可以有一些設(shè)置,required 是否必傳,defaultValue 默認(rèn)值

@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")

等價(jià)于

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

其他的也一樣

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容