Spring Boot學習——Controller的使用


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

       1. @Controller : 處理http請求

       2. @RequestMapping : 配置URL映射

       3. @RestController : 組合注解,spring 4之后新加的注解,相當於@Controller和@ResponseBody配合使用

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

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

       6. @GetMapping/@PostMapping : 組合注解

 

       使用方法:

       1. @Controller

              需要與模板配合使用。

              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等等。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM