SpringBoot(三) 转发/重定向
这是spring boot自学笔记三,上文记录了如何接收浏览器发送的请求。前文提过,我不喜欢网上的学习流程,是按照自己的习惯来学习的。按照习惯,登录页面提交数据后,我们要重定向到主页。因此,在这篇文章中记录如何对请求进行重定向。
在我查找了中文互联网后,我发现有三种跳转的方法,下面一一介绍。
首先需要注意,所有跳转的类不可以使用**@RestController**,要使用@Controller。前者返回的都是json格式不会做特定处理。
跳转模板文件页面
所谓的模板文件,就是Resources→templates的文件,spring会渲染里面的静态页面,因为考虑到前后端分离,所以我不打算学这个部分,所以没讲。
@RequestMapping("/t")
public String ss2() {
return "s";
}
浏览器输入localhost:8080/t,可以看到跳转到了模板目录下的s.html,但是地址栏的URL没有改变
是否可以跳转静态资源目录下的html或者其他的@Controller(比如最起初的(/hello)响应)?
不可以,我尝试了一下,无论是return “hello”,还是return “index.html"都不行,会报错。
Error resolving template [hello], template might not exist or might not be accessible by any of the configured Template Resolvers
看报错信息:无法处理模板文件hello,它可能不存在或者无法被配置模板解析
显然,这样单纯的return,是只能和模板文件(templates)关联起来的。
redirect & forward
redirect(重定向),forward(转发)
两者写法上相似,可以转发到静态页面和@Controller(比如最起初的(/hello)响应)
@RequestMapping("/r")
public String ss() {
// return "redirect:/hello";
return "redirect:index.html";
}
@RequestMapping("/f")
public String ss1() {
// return "forward:/hello";
return "forward:index.html";
}
重定向是用户行为,重新请求到新的页面,即请求两次,URL会改变。
转发是服务器行为,请求一次,URL不会改变。