A beginner working with Thymeleaf wanted to know the difference in behavior between @Controller and @RestController, so I investigated it.
Start sprintboot and access the following URL. http://localhost:8080/γγ
@ Controller
With the following code http://localhost:8080/list When you access main/resources/templates/list_display.html The html of is displayed on the screen. (The character string "list_display" is not displayed as it is)
@Controller
public class AppController {
@GetMapping("list")
public String from_list(){
return "list_display";
}
}
@ RestController
On the other hand, create the following controller file and use @RestController to create the following controller file. http://localhost:8080/person When you access
@RestController
public class SampleController {
@GetMapping("person")
public Person person() {
return new Person(123, "hogehoge", 40);
}
}
The following string is returned as is. {"id":123,"name":"hogehoge","age":40}
(Create a separate Person class like the one below)
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@NoArgsConstructor
@AllArgsConstructor
@Data
public class Person {
Integer id;
String name;
Integer age;
}
--If you want to display the html file in resource / on the screen, @RestController --If you just want to output a character string, @Controller
Let's use.
ββIt's easy, but I've put it together for my memorandum.
Recommended Posts