DrMaemi / blog

1 stars 0 forks source link

[Spring Boot] Web MVC #189

Open DrMaemi opened 2 months ago

DrMaemi commented 2 months ago

프로젝트에 다음 의존성을 추가해주어야 한다.

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

main 클래스

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {

        SpringApplication.run(DemoApplication.class, args);
    }
}

BasicController.java

@RestController
public class BasicController {

    @GetMapping("/")
    public String index() {

        return "Hello world";
    }

    @GetMapping("/greeting")
    public String greeting(@RequestParam(name = "name", required = false, defaultValue = "") String name) {

        return String.format("Welcome, %s", name);
    }

    @GetMapping("/pathVar/{var}")
    public String pathVar(@PathVariable(required = false) Long var) {

        return String.format("Path Var : %d", var);
    }
}

@RestController 대신 @Controller 를 사용하면 return 하는 String 에 따른 html 페이지를 resources/ 하위에서 탐색해 반환해주는 것 같다. (thymeleaf 의존성을 추가해서 html 파일을 thymeleaf 문법으로 작성해둔다.)

@RequestParam

greeting()@RequestParam 을 위와 같이 설정하면 http://localhost:8080/greeting?name=UserName 와 같이 URL에 접속했을 때 Welcome, UserName 문자열을 반환한다.

@PathVariable

http://localhost:8080/pathVar/2 URL 로 접속하면 Path Var : 2 문자열을 반환한다. http://localhost:8080/pathVar/UserName URL 로 접속하면 400 에러(There was an unexpected error (type=Bad Request, status=400).)를 발생시킨다.

A. 참조