@RestController = @ResponseBody + @Controller
@Controller中的方法无法返回jsp页面,或者html,配置的视图解析器 InternalResourceViewResolver不起作用,返回的内容就是Return 里的内容。
@Mapping + @ResponseBody 也会出现同样的问题。
①去除@ResponseBody 或 将含有Rest的注解换成对应的原始注解;
②不通过String返回,通过ModelAndView对象返回,上述例子可将return语句换成return new ModelAndView("index")
。
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>hellotitle>
head>
<body>
你好!初学者,我是SpringBoot的简单启动页面!
body>
html>
@Controller
public class HelloController {
@RequestMapping("/map1")
public String index() {
return "index.html";
}
@RequestMapping("/map2")
public String map2() {
return "index2.html";
}
}
http://localhost:8080/index.html 成功返回
http://localhost:8080/map1 成功返回
http://localhost:8080/index2.html 404返回
http://localhost:8080/map1 404返回
[Ref] SpringBoot如何返回页面
如果使用spring-boot-starter-parent
,就无需引入依赖
spring:
mvc:
view:
suffix: .html
static-path-pattern: /**
web:
resources:
static-locations: classpath:/templates/,classpath:/static/
http://localhost:8080/index.html 成功返回
http://localhost:8080/index.htm2 成功返回
http://localhost:8080/map1 报404
http://localhost:8080/map2 报404
调用接口需要 redirect
@Controller
public class HelloController {
@RequestMapping("/map1")
public String index() {
return "redirect:index.html";
}
@RequestMapping("/map2")
public String map2() {
return "redirect:index2.html";
}
}
http://localhost:8080/index.html 成功返回
http://localhost:8080/index.htm2 成功返回
http://localhost:8080/map1 成功返回
http://localhost:8080/map2 成功返回
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-thymeleafartifactId>
<version>2.1.6.RELEASEversion>
dependency>
http://localhost:8080/index.html 成功返回
http://localhost:8080/index2.html 404返回
spring:
thymeleaf:
prefix: classpath:/static/
suffix: .html
cache: false #关闭缓存
但是缺点是智能配置一个,配置谁谁好用
配置 prefix: classpath:/static/
http://localhost:8080/map1 成功返回
http://localhost:8080/map2 404返回
配置 prefix: classpath:/templates/
http://localhost:8080/map1 404返回
http://localhost:8080/map2 成功返回
SpringBoot如何返回页面