Spring boot系列(四)Controller


Posted by newstart1117 on 2022-03-18

淺談Controller

在上一篇文章Spring boot系列(三)Hello World中,我們使用了controller,其中包含了@RestController、@GetMapping,網路上有很多很精準的解釋及說明,這裡我就用自己意思來表達,往後也會用這種方式,一方面是記錄我的想法,另一方面也可以有所不同。

什麼是Controller

用來回應瀏覽器、HTTP,可以回傳文字或網頁,也可限定HTTP連線請求種類,像是GET、POST、PUT...等等

@RestController

單純回傳文字,也可以用@Controller+@ResponseBody,下列兩段程式效果相同

@RestController
public class HelloController {

    @GetMapping("/")
    public String hello(){
        return "Hello World!";
    }
}
@Controller
public class HiController {

    @ResponseBody
    @GetMapping("/hi")
    public String hi(){
        return "Hi";
    }
}

@Controller

回傳一個網頁,除非像上述一樣加上@ResponseBody

前置,需先在pom.xml的dependencies裡面加入模板引擎,常見的有thymeleaf、freemaker...等等

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

Controller的程式碼則是:

  • 如果是用localhost:8080/hi,則只會看到純文字的hi
  • 如果是用localhost:8080/hiPage,則可以看到大大的HI,因為是載入hi.html
    P.S. 網頁hi.html檔案路徑,預設都是在src -> resourices -> templates底下
@Controller
public class HiController {

    @ResponseBody
    @GetMapping("/hi")
    public String hi(){
        return "hi";
    }

    @GetMapping("/hiPage")
    public String hiPage(){
        return "hi";
    }
}

HTTP請求狀態

通常用來對應取得、儲存、修改、刪除,並且根據不同的狀態,用不同指定參數方式,參數這部份,後續再用一篇來講述參數的部份

  • GET
  • POST
  • PUT
  • DELETE
      @GetMapping("/hi")
      @PostMapping("/hi")
      @PutMapping("/hi")
      @DeleteMapping("/hi")
    

#java #spring boot #Backend #controller







Related Posts

[React 04] props

[React 04] props

Day 182

Day 182

[Docker] Dockerfile and .dockerignore

[Docker] Dockerfile and .dockerignore


Comments