<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
我们先在tempates文件夹中也新建一个hello.html但内容不同,然后先试一下直接访问该页面。输入http://localhost:8080/hello.html:
结果显然访问的是静态问价夹里面的那个hello.html
然后我们现在再试一下用controller:
似乎无法访问到hello.html了。。。这是因为:
静态页面的return默认是跳转到/static/index.html,当在pom.xml中引入了thymeleaf组件,动态跳转会覆盖默认的静态跳转,默认就会跳转到/templates/index.html,注意看两者return代码也有区别,动态没有html后缀。
也就是我们要这样改controller:
@Controller
public class HelloController {
@RequestMapping("/Hi")
public String sayHello() {
return "hello";
}
}
然后就可以成功跳转了
然后我们看看返回一点数据在前端利用Thyemleaf来拿:
@Controller
public class HelloController {
@RequestMapping("/Hi")
public ModelAndView sayHello() {
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("hello");
modelAndView.addObject("key", 12345);
//System.out.println("test");
return modelAndView;
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"/>
<title>Insert title here</title>
</head>
<body>
<h1>this is the hello.html in templates</h1>
<span th:text="${key}"></span>
</body>
</html>
效果:
如果不想返回视图,则用@RestController
如果用了静态模板你还想返回static中的页面,那么就要用重定向:
如果在使用动态页面时还想跳转到/static/index.html,可以使用重定向return "redirect:/index.html"。
return "redirect:hello.html";
几点tips:
1.拦截的url最后不要跟视图重合,否则会抛出Circular view path异常,我之前就是
@Controller
public class HelloController {
@RequestMapping("/hello")
public String sayHello() {
return "hello.html";
}
}
长按二维码向我转账
受苹果公司新规定影响,微信 iOS 版的赞赏功能被关闭,可通过二维码转账支持公众号。
阅读
好看
已推荐到看一看
你的朋友可以在“发现”-“看一看”看到你认为好看的文章。
取消
分享想法到看一看
确定
最多200字,当前共字
微信扫一扫
关注该公众号