spring boot을 웹서버로 작동시키기 위해서는 spring-boot-starter-web 추가해줘야 한다.
build.gradle.kts
dependencies {
implementation("org.springframework.boot:spring-boot-starter")
implementation("org.springframework.boot:spring-boot-starter-web") // 추가됨
testImplementation("org.springframework.boot:spring-boot-starter-test")
testRuntimeOnly("org.junit.platform:junit-platform-launcher")
}
gradle에 추가하고 나서 코키리 아이콘 눌러준다.
그리고 나서 아래와 같이 Controller 추가해주면 된다.
GET "/users" 예시:
package com.cozzin.homecompany;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class RootController {
@GetMapping("/users")
public ResponseEntity<String> getUser(@RequestParam(value = "email") String email) {
if (email == null || email.isEmpty()) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
.body("Email parameter is required");
}
return ResponseEntity.ok(
String.format("Your email is: %s", email)
);
}
}
package com.cozzin.workwell.controller
import com.cozzin.workwell.dto.CreateUserRequest
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
@RestController
@RequestMapping("/users")
class UsersController {
@PostMapping
fun createUser(@RequestBody request: CreateUserRequest): ResponseEntity<String> {
return ResponseEntity.ok("Hello")
}
}
package com.cozzin.workwell.dto
data class CreateUserRequest(
val name: String,
val password: String,
val email: String
)
$ curl -X POST -H "Content-Type: application/json" -d '{"name":"cozzin", "password":"password123", "email":"cozzin@example.com"}' http://localhost:8080/users
Hello%
https://it-techtree.tistory.com/entry/build-and-execute-springboot