spring boot(4)-html和templates
来源:互联网 发布:朕是什么意思网络此意 编辑:程序博客网 时间:2024/06/05 02:08
静态页面
spring boot项目只有src目录,没有webapp目录,会将静态访问(html/图片等)映射到其自动配置的静态目录,如下
/static
/public
/resources
/META-INF/resources
比如,在resources建立一个static目录和index.htm静态文件,访问地址 http://localhost:8080/index.html
如果要从后台跳转到静态index.html,代码如下。
@Controllerpublic class HtmlController {@GetMapping("/html")public String html() {return "/index.html";}
动态页面
动态页面需要先请求服务器,访问后台应用程序,然后再转向到页面,比如访问JSP。spring boot建议不要使用JSP,默认使用Thymeleaf来做动态页面。
在pom.xml 中添加Thymeleaf组件
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId></dependency>
TemplatesController.java
package hello; import javax.servlet.http.HttpServletRequest;import org.springframework.stereotype.*; import org.springframework.web.bind.annotation.*; @Controllerpublic class TemplatesController { @GetMapping("/templates")String test(HttpServletRequest request) {//逻辑处理request.setAttribute("key", "hello world");return "/index";} }
@RestController:上一篇中用于将返回值转换成json
@Controller:现在要返回的是一个页面,所以不能再用@RestController,而用普通的@Controller/
request.setAttribute("key", "hello world"):这是最基本的语法,向页面转参数 key和value。
return "/index": 跳转到 templates/index.html动态页面,templates目录为spring boot默认配置的动态页面路径。
index.html 将后台传递的key参数打印出来
<!DOCTYPE html><html><span th:text="${key}"></span></html>
访问http://localhost:8080/templates
这只是一个最基本的传参,templates标签和JSP标签一样,也可以实现条件判断,循环等各种功能。不过我在上一篇讲过,建议用静态html+rest替代动态页面,所以关于templates在此不做详细介绍
动态和静态区别
静态页面的return默认是跳转到/static/index.html,当在pom.xml中引入了thymeleaf组件,动态跳转会覆盖默认的静态跳转,默认就会跳转到/templates/index.html,注意看两者return代码也有区别,动态没有html后缀。
重定向
如果在使用动态页面时还想跳转到/static/index.html,可以使用重定向return "redirect:/index.html"。
@GetMapping("/html")public String html() {return "redirect:/index.html";}
- spring boot(4)-html和templates
- spring boot(4)-html和templates
- spring boot-html和templates
- HTML Templates
- spring boot + html 页面
- spring boot 返回 html
- Spring boot 访问html
- spring-boot websocket 配置和实现(包括html)
- spring boot 直接返回HTML
- STS (Spring tools stuite)使用Gradle创建Spring Boot整合templates做网站示例
- spring boot和spring boot简单区别
- templates/list.html
- spring boot初学hello world访问templates报Whitelabel Error Page 404
- spring boot直接返回静态html
- Spring boot(14) 监控spring boot的运行spring boot actuator和spring boot admin
- Spring Boot和Spring Cloud架构学习(二)--Spring Boot
- Shadow DOM 与 HTML Templates
- spring boot和mybatis整合
- Win10 64位系统设置JAVA环境
- html5第八课时,flex的基础应用
- 利用SSH端口转发作内网穿透
- 框架学习---1、angular简易demo~~购物车
- 用C语言模仿Python函数
- spring boot(4)-html和templates
- HDU 1702 ACboy needs your help again!(栈和队列的试用)
- android webview native与JavaScript相互调用 java与JavaScript相互调用
- Java异常体系结构
- caffe SilenceLayer
- c语言环境下如何创建一个外部函数
- [Algorithm]九章五.DFS
- 一只小蜜蜂...
- 如何解决sublime text3中文出现乱码