@SpringBootApplication
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
@RestController = @Controller + @ResponseBody
the class as a web route controller handing HTTP requests
@RestController
@RestController
@RequestMapping("/api")
public class MyRestController {
//http://localhost:8080/api/hello
@GetMapping("/hello")
public String hello() {
return "Hello, World!";
}
//http://localhost:8080/api/welcome
@GetMapping("/welcome")
public String hello() {
return "Welcome to there!";
}
}
//we can without @RequestMapping("/api") to reach the page.
//http://localhost:8080/hello
//http://localhost:8080/welcome
@Controller + @ResponseBody
In this case, we should have a "greetPage.html"
file in your resources/templates folder with the HTML content. After entering http://localhost:8080/greet
, you can achieve the content in "greetPage.html"
.
If you don’t have "greetPage.html"
file, the page will prompt an error
@Controller
public class GreetingController {
@GetMapping("/greet")
public String greet() {
return "greetPage";
}
}
With @ResponseBody
, you can achieve the content “greetPage”
in the page, even if you don’t have the "greetPage.html"
file in your project.
@Controller
public class GreetingController {
@GetMapping("/greet")
@ResponseBody
public String greet() {
return "greetPage";
}
}
If you use @RestController
, you don’t need to consider the issue.
@RestController
public class GreetingController {
@GetMapping("/greet")
public String greet() {
return "greetPage";
}
}
Summary
@RestController |
@Controller + @ResponseBody |
|
---|---|---|
purpose | building RESTful APIs that return data (JSON, XML, etc.) directly | traditional web applications that return views |
Data | Y | |
View(HTML) | Y | |
generic | Y |
@RequestParam
@PathVariable
Example:
http://localhost:8080/api/v1/student/{id}?{parameter}
http://localhost:8080/api/v1/student/1?name=&[email protected]
since @RequestParam
sets to false, we can pass optional data to the path and update the email only.