初次做SpringBoot,要解决页面跳转的问题,这个问题我弄了大半天,弄好后,其实也不算个事,写出来给大家提个醒!
其实不要使用spring boot的@RestController注解,直接使用spring原来的注解@Controller就可以了。
@Controller //主要是这条语句
public class ActionController {
@RequestMapping(value = "/action",method = RequestMethod.GET)
public String index(){
return "login";
}
}
为什么呢?
@RestController注解,相当于@Controller+@ResponseBody两个注解的结合,
但使用@RestController这个注解,就不能返回jsp,html页面,视图解析器无法解析jsp,html页面。
把@ResetController修改为@Controller即可跳转页面。
备注: @Responsebody后,返回结果直接写入HTTP response body中,不会被解析为跳转路径,所以你总是看到是打印字符串的效果,不是跳转效果。
--------------------------------
如果你想跳转后使用 thymeleaf [taim li:f] 来达到以前jsp获取Model值这样的效果(thymeleaf是什么?你自行百度),那么,你得在maven中加依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
然后,在配置文件:application.yml或application.property中加配置:
spring.thymeleaf.prefix:classpath: /templates/
spring.thymeleaf.suffix: .html
spring.thymeleaf.mode: HTML
spring.thymeleaf.encoding: utf-8
spring.thymeleaf.cache: false
再写控制类时把Model加在参数中:
@Controller public class ActionController { @RequestMapping(value = "/action",method = RequestMethod.GET) public String index(Model model){ model.addAttribute("aaa","我是一个兵"); model.addAttribute("bbb","来自老百姓!"); return "index"; } }
它就会跳转到 /templates/index.html这个网页上去了。
你的index.html如果想显示"我是一个兵","来自老百姓"的值的话,网页应该这样写:
<!DOCTYPE HTML> <html xmlns:th="http://www.thymeleaf.org"> <!-- 听说这一句要,但我没有要这个标签,也能用 --> <head> <body> <h1>AAAAindex.jspsdfasd</h1> <p>Today is: <span th:text="${aaa}">13 february 2011</span>.</p> <!-- 不能直接${aaa},而应该写在一个标签中 --> @{${aaa}}<br> <!--这里是取不到值的 --> ${aaa}<br> <!--这里是取不到值的 --> ${bbb} <!--这里是取不到值的 --> </body> </html>
-------------------------------------------
如果你不想使用 thymeleaf ,你想直接用原来的ssm的做法,又想把模板都放在springboot 的 template模板之下,那么 不要上面的thymeleaf配置,直接用原来的MVC配置也可以(我的测试是不要下面两句也可以):
spring.mvc.view.prefix: /resources/templates/
spring.mvc.view.suffix: .html
有的版本是是没有mvc的:
spring.view.prefix: /resources/templates/
spring.view.suffix: .html
控制类仍然用上面的,这样它也可以跳转到 /templates/login.html这个网页上去。