博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Springboot的static和templates区别
阅读量:4677 次
发布时间:2019-06-09

本文共 2268 字,大约阅读时间需要 7 分钟。

static和templates部分参考博客:https://blog.csdn.net/wangb_java/article/details/71775637

热部署参考博客:https://www.cnblogs.com/cx-code/p/8686453.html

 

SpringBoot里面没有我们之前常规web开发的WebContent(WebApp),它只有src目录

在src/main/resources下面有两个文件夹,static和templates   springboot默认  static中放静态页面,而templates中放动态页面

 

静态页面:

 这里我们直接在static放一个hello.html,然后直接输入http://localhost:8080/hello.html便能成功访问

(好像可以新建一个public文件夹,也可以放静态文件)

也可以通过controller跳转:

@Controllerpublic class HelloController {    @RequestMapping("/Hi")    public String sayHello() {        return "hello.html";    }    }

然后输入http://localhost:8080/Hi就可以成功访问

 

 

动态页面:

动态页面需要先请求服务器,访问后台应用程序,然后再转向到页面,比如访问JSP。spring boot建议不要使用JSP,默认使用Thymeleaf来做动态页面。

现在pom中要添加Thymeleaf组件

org.springframework.boot
spring-boot-starter-thymeleaf

 

我们先在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:

@Controllerpublic class HelloController {    @RequestMapping("/Hi")    public String sayHello() {        return "hello";    }    }

然后就可以成功跳转了

 

 

然后我们看看返回一点数据在前端利用Thyemleaf来拿:

@Controllerpublic class HelloController {    @RequestMapping("/Hi")    public ModelAndView sayHello() {        ModelAndView modelAndView = new ModelAndView();        modelAndView.setViewName("hello");        modelAndView.addObject("key", 12345);        //System.out.println("test");        return modelAndView;    }    }
Insert title here

this is the hello.html in templates

效果:

 

 

 

如果不想返回视图,则用@RestController

 

 

如果用了静态模板你还想返回static中的页面,那么就要用重定向:

如果在使用动态页面时还想跳转到/static/index.html,可以使用重定向return "redirect:/index.html"。

return "redirect:hello.html";

 

 

 

几点tips:

1.拦截的url最后不要跟视图重合,否则会抛出Circular view path异常,我之前就是

@Controllerpublic class HelloController {    @RequestMapping("/hello")    public String sayHello() {        return "hello.html";      }    }

 

然后就报错说会有个循环视图的错误,反正以后注意就是。

 

2.每次改完都要重新停止应用,再重新启动很烦~但springboot有个叫热部署的东西,就是说在项目中修改代码可以不用重新停止应用再重新启动,可以自动重启,这里我们用的是devtools:

具体见博客:https://www.cnblogs.com/cx-code/p/8686453.html

转载于:https://www.cnblogs.com/ysq0908/p/10676016.html

你可能感兴趣的文章
线上服务故障处理原则
查看>>
孪生兄弟状态模式与策略模式有什么区别,究竟该如何选择
查看>>
ヘルプ
查看>>
centos7 添加开机启动项
查看>>
luogu【P2745】[USACO5.3]窗体面积Window Area
查看>>
Codeforces 346D Robot Control(01BFS)
查看>>
CSS3学习笔记--media query 响应式布局
查看>>
NHibernate.3.0.Cookbook第四章第2节的翻译
查看>>
19.C#逐一介绍IEnumerable和IEnumerable<T>中的扩展方法(10.3-10.5)
查看>>
听说最近你读过不少书
查看>>
linux之Ubuntu下Django+uWSGI+nginx部署
查看>>
【转】Struts1.x系列教程(2):简单的数据验证
查看>>
HTML head元素
查看>>
requireJS
查看>>
Poj3667Hotel线段树
查看>>
待嫁闺中:PPTV的辛酸史
查看>>
作用域
查看>>
CSS文本方向
查看>>
Dev Grid拖拽移动行
查看>>
Read
查看>>