在学习spring boot时,遇到了一些问题,当我需要向前端发送一个视图的时候,return + 视图名无法返回视图,也就是前端无法打印出这个视图,只能以字符串形式将视图名打印到浏览器端,如图所示
首先,添加依赖,必须要添加一个模板才可以,要不然浏览器无法解析(本文添加的是thymeleaf模板引擎)
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
package com.wcc.spring_boot_testthymeleaf.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
@RestController
public class HelloController {
@RequestMapping("/success1")
public String success1(){
return "success";
}
@RequestMapping("/success")
public ModelAndView success(){
return new ModelAndView("success");
}
}
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>成功!!!</h1>
<!-- <!–th:text将div中的文本内容设置为${}–>
<div th:text="${hello}">123</div>-->
</body>
</html>
访问http://localhost:8080/success1时的运行结果
访问http://localhost:8080/success时的运行结果
上面两张截图是在@RestController注解下的两种不同返回类型所返回的界面,上面的那张截图的方法返回的是String类型,下面的那张截图的方法返回的是ModelAndView 类型,造成了两种不同的结果
当将@RestController注解换成@Controller注解时,代码和截图如下:
package com.wcc.spring_boot_testthymeleaf.Controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class HelloController {
@RequestMapping("/success1")
public String success1(){
return "success";
}
@RequestMapping("/success")
public ModelAndView success(){
return new ModelAndView("success");
}
}
访问http://localhost:8080/success1时的运行结果
访问http://localhost:8080/success时的运行结果
发现两种访问都会定位到success.html页面,不会出现打印html文件名称的字符的情况。n
那么,造成这种情况的根本原因是什么呢?
据官方文档显示:A convenience annotation that is itself annotated with @Controller and @ResponseBody.
1)如果使用@RestController注解,则Controller中的方法无法返回jsp页面,配置的视图解析器InternalResourceViewResolver则不起作用,返回的内容就是Return 里的内容(String/JSON),也就是只有返回类型是ModelAndView类型才能返回视图到前端,若返回其他类型都会以字符串的形式在前端显示
2)如果使用@Controller注解,如果需要返回JSON,XML或自定义mediaType内容到页面,则需要在对应的方法上加上@ResponseBody注解。