创建spring boot项目
通过[http://start.spring.io/]创建springboot项目。
下载到本地后,通过开发工具(idea、eclipse)导入成maven项目。
此时,DemoApplication为启动类(通过@SpringBootApplication声明为启动类)
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
此时,pom文件是最干净的版本。
添加web(controller)层
pom文件中需要添加
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
创建controller的package时需要注意:
当需要创建其他的controller层是,需在DemoApplication同目录下创建package。这样,当启动的时候,才会加载到这些类
。如下图
后台请求跳转页面
需要在pom文件中添加:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
后台请求肯定对应的是controller层。这就涉及到对注解的理解。
@RestController
相当于 @Controller + @ResponseBody
该注解 方法method 返回类型是String时候则返回string,返回对象时,则将对象转换成json字符串返回。
@Controller
如果返回到页面,则方法的返回类型可以为String(静态页面的名称)和ModelAndView对象(非静态页面)。
在application.yml配置文件中,添加关于模板的配置:
spring.thymeleaf.prefix
(前台页面的目录:可以是在resource目录下新建目录,”classpath:/目录名/”,也可以创建src的同级目录static,”/目录名/”。)
spring.thymeleaf.suffix
(前台页面的后缀)
默认的thymeleaf配置是resource目录下的”/thymeleaf/”。
当请求页面的结果是
首先确定请求的jsp的目录在static还是在resource,然后确定spring boot关于thymeleaf的配置是否正确。注意启动日志,观察是否出现
类似。若是,则注意相关配置。