SpringBoot controller返回静态页面

一般Spring里面@RequestMapping注释的方法返回为两种形式,一种是以json格式的数据给前端,让前端进行处理。另一种是返回一个视图,或者说一个静态页面,通过页面的路径(相对于根目录,SpringBoot默认静态资源根目录为src/main/resources/templates)。但是这两种如何分别呢。

在SpringBoot里面是使用thymeleaf返回页面,需要引入thymeleaf依赖

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>

可以在application.properties文件里面配置(也可以不设置,以下是默认的)

spring.thymeleaf.cache=true
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html

要想返回json格式,就要关闭thymeleaf(不要引入依赖),并且用@RestController来注释类。(注意如果要返回页面,不能用@RestController,而应该使用@Controller)

猜你喜欢

转载自blog.csdn.net/qq_22038259/article/details/89354547