Spring(Web)
Spring 완전정복 - 1 / Controller
kjy0349
2022. 4. 19. 18:33
Spring에서 페이지를 띄우는 여러 방법
1. 정적 페이지, MVC와 템플릿 엔진
위 그림과 같이 동작하는데, 각각의 경우에 따라 다르게 동작한다.
- 정적 페이지를 호출 할 경우 -> http://localhost:8080/hello.html
GetMapping에 localhost에서 호출한 이름의 컨트롤러가 없을 경우, 따로 컨트롤러를 거치지 않고 static 디렉터리 하위에 있는 html 웹 페이지를 띄움. (html 파일의 이름으로 호출해야함.)
따로 컨트롤러가 없기 때문에, 코드는 없음. - 컨트롤러가 있을 경우 -> http://localhost:8080/hello-mvc
localhost에서 호출한 이름의 GetMapping 어노테이션이 있다면, 컨트롤러에서 해당 부분을 실행한 후 return하게되면 ViewResolver로 return한 이름이 넘어가게되어 template 디렉터리 하위의 html 페이지를 코드에 따라 변경한 후, 띄움.
컨트롤러가 있든 없든, 정적 페이지 호출은 항상 *.html과 같이 파일 이름을 호출하는 형식이기 때문에, 컨트롤러와 겹칠 경우는 없다.
이렇게 쓸 일은 없겠지만..
@GetMapping("hello.html")과 같은 형식으로 컨트롤러 호출을 하고 static 패키지에도 hello.html이 있다면, GetMapping 어노테이션이 우선적으로 작동해 template 패키지에 있는 hello.html을 viewResolver가 호출하게 된다.
@GetMapping("hello") // 실제 웹에서 접근 할 때 쓰는 페이지 키워드
public String hello(@RequestParam("name") String name, Model model) {
model.addAttribute("name", name);
return "hello"; // 웹에서 표시 할 때 사용할 html 파일의 이름
}
2. ResponseBody 어노테이션을 활용한 API 방식
위에서 사용한 GetMapping 어노테이션과 함께 ResponseBody 어노테이션을 함께 써주게되면, 컨트롤러에서 return한 값이 ViewResolver로 넘어가 띄울 html 파일을 찾는게 아닌 바로 화면에 return한 값을 띄우게 된다.
- 객체가 아닌 String을 return하여, 컨트롤러에서 StringConverter로 넘겨주는 경우
@GetMapping("hello-string")
@ResponseBody
public String helloString(@RequestParam("name") String name) {
return "hello " + name;
}
ResponseBody 어노테이션이 추가되어, 따로 html 페이지를 찾지 않고 return한 값을 바로 띄우게 됨.
- 객체를 return하여, 컨트롤러에서 JsonConverter로 넘겨주는 경우위와 같은 경우지만, String이 아닌 객체 형태로 return했으므로 JsonConverter로 넘어가게되어, JSON 형태로 화면에 띄움.
{"name" : "hello"} -> key : value 형태
@GetMapping("hello-api")
@ResponseBody
public Hello helloApi(@RequestParam("name") String name) {
Hello hello = new Hello();
hello.setName(name);
return hello;
}
static class Hello {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
++ 추가적으로 생각 한 것은,
public class HelloController {
public final Param para = new Param();
@GetMapping("hello-api")
@ResponseBody
public Param helloApi(@RequestParam("name") String name) {
para.setName(name);
return para;
}
static class Param {
private String name;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
}
}
와 같은 형태로 코드를 쓰면, 바뀌는 name에대한 정보를 갖고 있는 Param 객체를 여러번 호출하지 않을 수 있다는 생각이 들었다.