Spring Boot學習——Controller的使用

       本文主要記錄幾個註釋的使用方法。html

       1. @Controller : 處理http請求spring

       2. @RequestMapping : 配置URL映射瀏覽器

       3. @RestController : 組合註解,spring 4以後新加的註解,至關於@Controller和@ResponseBody配合使用app

       4. @PathVariable : 獲取URL中的數據spring-boot

       5. @RequestParam : 獲取請求的參數的值ui

       6. @GetMapping/@PostMapping : 組合註解spa

 

       使用方法:code

       1. @Controllerxml

              須要與模板配合使用。htm

              pom.xml 中添加模板依賴,代碼以下:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

              在resources下建立文件夾templates,在templates下建立index.html,index.html內容隨便寫。

              編輯Java類,代碼以下:

@Controller
public class HelloController {
    @RequestMapping(value="/say", method=RequestMethod.GET)
    public String sayHello(@PathVariable("id") int myId){
        return "index";
    }
}

              在瀏覽器中訪問http://127.0.0.1:8080/say便可看到index.html頁面內容

       2. @RequestMapping

              上面代碼已經使用了該註解。

       3. @RestController

              組合註解,至關於@Controller和@ResponseBody配合使用

       4. @PathVariable

              獲取URL中的數據,代碼以下:

@RestController
public class HelloController {
  @RequestMapping(value="/say/{id}",method=RequestMethod.GET)
    public String sayHello(@PathVariable("id") int myId){
        return  "myId is " + myId;
    }
}

              在瀏覽器中訪問http://127.0.0.1:8080/say/111便可查看結果

       5. @RequestParam

              獲取請求的參數的值,代碼以下:

@RestController
public class HelloController {
    @RequestMapping(value ="/say", method=RequestMethod.GET)
    public String sayHello( @RequestParam("id") int myId){
        return  "myId is " + myId;
    }
}

              在瀏覽器中訪問http://127.0.0.1:8080/say?id=111便可查看結果

              也能夠設置參數的默認值,代碼以下:

@RestController
public class HelloController {
    @RequestMapping(value ="/say", method=RequestMethod.GET)
    public String sayHello( @RequestParam( value = "id", required = false, defaultValue = "0") int myId){
        return  "myId is " + myId;
    }
}

              這樣能夠不傳參數id。在瀏覽器中訪問http://127.0.0.1:8080/say便可查看結果

       6. @GetMapping/@PostMapping

              組合註解

              @GetMapping(value = "/say") 至關於 @RequestMapping(value = "/say", method = RequestMethod.GET)

              @PostMapping(value = "/say") 至關於 @RequestMapping(value = "/say", method = RequestMethod.POST)

              除此以外,還有組合註解@PutMapping、@DeleteMapping等等。

相關文章
相關標籤/搜索