前言
无论怎样使用@RequestMapping映射,路由始终无法令人满意,使用thymeleaf处理动态路由就舒服多了。
resouce/static
resource/static是默认静态web目录之一。
如果存在resource/static/index.html,浏览器输入http://domain:port/index.html
即可访问到。
有时候,我们希望/index也指向index.html,这时只需要把/index映射到index.html:
@RequestMapping(value = "/index", method = RequestMethod.GET)
public String index() {
return "/index.html";
}
现在考虑一个场景:
访问/login,若已登录,返回index.html;未登录,返回login.html。
伪代码如下:
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String index() {
if (已登录) return "/index.html";
return "/login.html";
}
如果未登录的用户登录,返回的是login.html;如果是已登录的用户,返回的是index.html,但是!地址栏是http://domain:port/login
,地址栏与页面内容不相符的诡异情况出现了。
重定向可以解决这个问题。把控制器代码改成以下:
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String index() {
if (已登录) return "redirect:/index.html";
return "/login.html";
}
这样如果登录态未过期,直接跳转到index.html。访问静态目录需要把文件名写全,动态则不需要。
resource/templates
resource/templates
是引入thymeleaf后的默认动态web目录。
把login.html
和index.html
放到templates目录下,控制器改成以下:
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String index() {
if (已登录) return "redirect:/index";
return "/login";
}
如上实现的功能与使用静态路由实现的一致,并且还能通过Model
对象动态渲染html(具体见Spring boot中如何使用Model进行传值以及Thymeleaf的用法)。