1. 情况一
今天用SpringBoot 写代码遇到了一个非常基础的错误,好久没写代码了,都忘记了怎么启动一个SpringBoot项目。我就想简单的让页面显示Hello,World
结果由于粗心,出现这么简单的错误,
错误代码示范:
@Controller
public class View {
@RequestMapping("/hello")
public String hello() {
return "Hello World!";
}
}
我想让浏览器界面显示“Hello,World",但是呢,用错了注解,这里就要讲一下@RestController 和@Controller 的区别了
在controller层中,如果我们需要返回一个页面用@Controller,如果需要返回数据用@RestController
@Controller 是用来返回一个jsp或者html页面
@RestController 是返回Json或者Xml数据
或者我们在需要返回Json或者xml形式数据的方法上面,加上@ResponseBody注解,也可以实现
@Controller
public class View {
@RequestMapping("/hello")
@ResponseBody
public String hello() {
return "Hello World!";
}
}
或者直接使用@RestController
@RestController
public class View {
@RequestMapping("/hello")
public String hello() {
return "Hello World!";
}
}
2、情况二
除了注解错误,还有以下可能造成这种错误:
SpringBoot的启动类和Controller层包位置放置错误,SpringBoot启动类默认自动扫描与启动类在同个包以及子包下的Bean,也就是要把启动类放在最外层包。
如果不在这个范围,就在@SpringBootApplication注解中加入扫描路径,如下:
@SpringBootApplication(scanBasePackages="XXX")
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
基本上就这么个情况。