在刚开始写Spring-boot入门的时候,被刚写的项目卡住了,
@Controller
public class MyController {
@RequestMapping(value = {"/","/index.html"},method = RequestMethod.GET)
public String toIndex(){
return "index";
}
}
运行后出现下页面,而没有到index页面![在这里插入图片描述](https://img-blog.csdnimg.cn/c3f3c997ec7e4faab232cf07c755dcec.png)
查找并排查原因,
1、以为是@Controller与@RestController的问题。
排查:两者的区别在于:@Controller+@ResponseBody 相当于@Controller,
执行方法:于是将@Controller改为@ResponseBody。运行之后虽然没有报错,但是页面只返回了index。而同样没有跳到index页面。
2、两个注解还有区别就是 参考此文章知道本次遇到的问题跟两个注解没有关系,我的写法是没有问题的,在路径对(Controller层和Application在相同路径下)的情况下,就需要找其他的解决方法。
后边一遍一遍排查之后发现,其实只要是配置没有出错(当然包括thymeleaf依赖、依赖包版本是否冲突等),接下来 我将所有的代码及配置放上:
pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>2.7.4</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.24</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.3.13</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.13</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.6.1</version>
</dependency>
<!-- thymeleaf 模板-->
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
<version>3.0.11.RELEASE</version>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-java8time</artifactId>
<version>3.0.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>net.sourceforge.nekohtml</groupId>
<artifactId>nekohtml</artifactId>
<version>1.9.22</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
application.yml中什么也没有
Controller层:
@Controller
public class MyController {
@RequestMapping(value = {"/","/index.html"})
public String toIndex(){
return "index";
}
}
此时在resources文件夹中,放到自己的主页就可以,其中static中放入js、css、素材等文件,templates中存放html文件。
想要查看代码可在码云上查看