Spring 启动 - @RestController 注释被拾取,但当替换为 @Controller 注释时,它停止工作
Spring Boot - @RestController annotation gets picked up, but when replaced with @Controller annotation, it stops working
这是一个虚拟项目:-
BlogApplication.java
@SpringBootApplication
@RestController
public class BlogApplication {
public static void main(String[] args) {
SpringApplication.run(BlogApplication.class, args);
}
@GetMapping("/hello")
public String hello(@RequestParam(value = "name", defaultValue = "World") String name) {
return String.format("Hello %s!", name);
}
}
HtmlController.java
@Controller //does not work
OR
@RestController //works
public class HtmlController {
@GetMapping("/getHtmlFile")
public String getHtmlFile() {
return "Bit Torrent Brief";
}
}
为什么@RestController
可以映射getHtmlFile
,但是@Controller
returns命中/getHtmlFile
时404?
@RestController 是@Controller 和@ResponseBody 的组合。
当你使用@Controller时,你应该在你的方法之前写@ResponseBody return type
@Controller
public class HtmlController {
@GetMapping("/getHtmlFile")
public @ResponseBody String getHtmlFile() {
return "Bit Torrent Brief";
}
}
这有效。
这是一个虚拟项目:-
BlogApplication.java
@SpringBootApplication
@RestController
public class BlogApplication {
public static void main(String[] args) {
SpringApplication.run(BlogApplication.class, args);
}
@GetMapping("/hello")
public String hello(@RequestParam(value = "name", defaultValue = "World") String name) {
return String.format("Hello %s!", name);
}
}
HtmlController.java
@Controller //does not work
OR
@RestController //works
public class HtmlController {
@GetMapping("/getHtmlFile")
public String getHtmlFile() {
return "Bit Torrent Brief";
}
}
为什么@RestController
可以映射getHtmlFile
,但是@Controller
returns命中/getHtmlFile
时404?
@RestController 是@Controller 和@ResponseBody 的组合。 当你使用@Controller时,你应该在你的方法之前写@ResponseBody return type
@Controller
public class HtmlController {
@GetMapping("/getHtmlFile")
public @ResponseBody String getHtmlFile() {
return "Bit Torrent Brief";
}
}
这有效。