初学Springboot(五)

前言

这次写Springboot的视图技术


提示:以下是本篇文章正文内容,下面案例可供参考

一、Spring Boot可整合的模板引擎技术

1. FreeMarker

2. Groory

3. Thymeleaf

4. Mustache

这次主要写的是常用的Thymeleaf

二、Thymeleaf的使用

1.Thymeleaf常用标签:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" media="all"
        href="../../css/gtvg.css" th:href="@{/css/gtvg.css}" />
<title>Title</title>
</head>
<body>
<p th:text="#{hello}">欢迎进入Thymeleaf的学习</p>
</body>
</html>

xmlns:th=“http://www.thymeleaf.org”

th:href="@{/css/gtvg.css}"

th:text="#{hello}"

xmlns:th:用于引入Thymeleaf模板引擎标签,使用关键字th标注标签是thymeleaf模板提供的标签

th:href:用于引入外联样式文件

th:text:用于动态显示文本内容
还有更多的

th:insert页面片段包含(类似JSP中的include标签)
th:replace页面片段包含(类似JSP中的include标签)
th:each元素遍历(类似JSP中的c:forEach标签)
th:if条件判断,如果为真
th:unless条件判断,如果为假
th:switch条件判断,进行选择性匹配
th:case条件判断,进行选择性匹配
th:object变量声明
th:with变量声明
th:attr通用属性修改
th:attrprepend通用属性修改,将计算结果追加前缀到现有属性值
th:attrappend通用属性修改,将计算结果追加后缀到现有属性值
th:value属性值修改,指定标签属性值
th:href用于设定链接地址
th:src用于设定链接地址
th:text用于指定标签显示的文本内容
th:utext用于指定标签显示的文本内容,对特殊标签不转义
th:fragment声明片段
th:remove移除片段

2.Thymeleaf标准表达式

说明表达式语法
变量表达式 (获取上下文中的变量值)${…}
选择变量表达式 (用于从被选定对象获取属性值)*{…}
消息表达式 (用于Thymeleaf模板页面国际化内容的动态替换和展示)#{…}
链接URL表达式 (用于页面跳转或者资源的引入)@{…}
片段表达式 (用来标记一个片段模板,并根据需要移动或传递给其他模板。)~{…}

举例


变量表达式

<p th:test=“${title}”>标题</p>

从上下文获取title字眼的变量,如果不存在即显示标题文本

选择变量表达式

<div th:object="${session.user}">
    <p>Name:<span th:text="${#object.name1}">baby</span></p>
    <p>Username<span th:text="${session.user.name2}">pipi</span></p>
    <p>password<span th:text="*{password}">susu</span></p>
</div>

上面的代码${#object.name1}变量表达式使用Thymeleaf模板提供的内置对象object获取当前上下文对象中的name属性值,${session.user.name2}变量表达式获取当前user对象的name2属性值,*{password}选择表达式获取当前指定user的password属性值

消息表达式

<input type="text" class="form-control"
           th:placeholder="#{login.username}" required="" autofocus="">

用于动态替换和展示

连接表达式

<a href="#" th:href="@{路径(参数名称=参数值)}">view</a>

链接表达式中@{路径(参数名称=参数值)}
路径可以写绝对链接路径,或绝对链接地址
参数值可以用变量表达式传递动态参数值

片段表达式

<div th:insert="~{thymeleafDemo::title}">

使用~{...}标记片段模板,并根据需要移动或传递给其他模板,
使用th:insertth:replace
就上述代码来说,使用th:insert属性将title片段引用到该 div标签中,thymeleafDemo为模板名称,Thymeleaf会自动查找"/resources/templates"目录下的thymeleafDemo模板

Thymeleaf为变量所在域提供了一些内置对象,如下:

•#ctx:上下文对象

•#vars:上下文变量

•#locale:上下文区域设置

•#request:(仅限Web Context)HttpServletRequest对象

•#response:(仅限Web Context)HttpServletResponse对象

•#session:(仅限Web Context)HttpSession对象

•#servletContext:(仅限Web Context)ServletContext对象

动态获取上下文关于locale的country

Thymeleaf基本使用

步骤一:引入依赖启动器

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

步骤二:全局配置文件设置

# 模板缓存:开启(开发阶段为关闭)
spring.thymeleaf.cache = false
#模板编码:utf-8
spring.thymeleaf.encoding =utf-8
#模板样式:HTML5
spring.thymeleaf.mode = HTML5
#指定模板页面存放路径(classpath=resources文件夹)
spring.thymeleaf.prefix = classpath:/templates/
#指定模板页面名称的后缀
spring.thymeleaf.suffix = .html
# 配置国际化文件基础名
spring.messages.basename=i18n.login

步骤三:创建控制类

@Controller
public class LoginController {
    @RequestMapping("/toLoginPage")
    public String login(Model model){
        //calendar启动日历对象,获取当前年份对象
        int i = Calendar.getInstance().get(Calendar.YEAR);
        model.addAttribute("currentYear",i);
        //model.addAttribute("currentYear", Calendar.getInstance().get(Calendar.YEAR));
        //因为全局配置文件有了存储路径,所以直接简写
        return "login";
    }
}

步骤四:创建对应的前端页面

在这里插入图片描述
login.html

<!DOCTYPE html>
<!--引入thymeleaf-->
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1,shrink-to-fit=no">
    <title>用户登录界面</title>
<!--    引入外联样式-->
    <link th:href="@{/login/css/bootstrap.min.css}" rel="stylesheet">
    <link th:href="@{/login/css/signin.css}" rel="stylesheet">
</head>
<body class="text-center">
<!--  用户登录form表单 -->
<form class="form-signin">
    <img class="mb-4" th:src="@{/login/img/login.jpg}" width="72" height="72">
    <h1 class="h3 mb-3 font-weight-normal" th:text="#{login.tip}">请登录</h1>
    <input type="text" class="form-control"
           th:placeholder="#{login.username}" required="" autofocus="">
    <input type="password" class="form-control"
           th:placeholder="#{login.password}" required="">
    <div class="checkbox mb-3">
        <label>
            <input type="checkbox" value="remember-me"> [[#{login.rememberme}]]
        </label>
    </div>
    <button class="btn btn-lg btn-primary btn-block" type="submit" th:text="#{login.button}">登录</button>
    <p class="mt-5 mb-3 text-muted">© <span th:text="${currentYear}">2019</span>-<span th:text="${currentYear}+1">2020</span></p>
    <a class="btn btn-sm" th:href="@{/toLoginPage(l='zh_CN')}">中文</a>
    <a class="btn btn-sm" th:href="@{/toLoginPage(l='en_US')}">English</a>
</form>
</body>
</html>



login_zh_CN.properties

login.tip=请登录
login.username=用户名
login.password=密码
login.rememberme=记住我
login.button=登录

login_en_US.properties

login.tip=Please sign in
login.username=Username
login.password=Password
login.rememberme=Remember me
login.button=Login

login.properties

login.tip=请登录
login.username=用户名
login.password=密码
login.rememberme=记住我
login.button=登录

静态包里就是bootstrap跟css样式以及壁纸
接下来启动启动类
输入端口号虚拟路径
在这里插入图片描述

实现国际化切换

引入上文所写的国际化切换属性

定制区域信息解析器

创建一个用于定制国际化功能区域信息解析器的自定义配置类MyLocalResovel,MyLocalResolver自定义区域解析器配置类实现了LocaleResolver接口,并重写了其中的resolveLocale()方法进行自定义语言解析,最后使用@Bean注解将当前配置类注册成Spring容器中的一个类型为LocaleResolver的Bean组件,这样就可以覆盖默认的LocaleResolver组件。

@Configuration
public class MylocalResovel implements LocaleResolver {
    // 自定义区域解析方式
    @Override
    public Locale resolveLocale(HttpServletRequest httpServletRequest) {
        // 获取页面手动切换传递的语言参数l
        String l = httpServletRequest.getParameter("l");
        // 获取请求头自动传递的语言参数Accept-Language
        String header = httpServletRequest.getHeader("Accept-Language");
        Locale locale=null;
        // 如果手动切换参数不为空,就根据手动参数进行语言切换,否则默认根据请求头信息切换
        if(!StringUtils.isEmpty(l)){
            String[] split = l.split("_");
            locale=new Locale(split[0],split[1]);
            //System.out.println(split);
        }else {
            // Accept-Language: en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7
            String[] splits = header.split(",");
            String[] split = splits[0].split("-");
            locale=new Locale(split[0],split[1]);
        }
        return locale;
    }
    @Override
    public void setLocale(HttpServletRequest httpServletRequest, @Nullable
            HttpServletResponse httpServletResponse, @Nullable Locale locale) {
    }
    // 将自定义的MyLocalResovel类重新注册为一个类型LocaleResolver的Bean组件
    @Bean
    public LocaleResolver localeResolver(){
        return new MylocalResovel();
    }
}

在这里插入图片描述
将编码格式设置为UTF-8避免出现乱码问题
因为如果是我们手写输入的,会受本地IDEA设置影响导致网页显示乱码

测试

在这里插入图片描述
在这里插入图片描述


总结

有兴趣的可以看我其他文章
初学Springboot(四)数据整合处理
初学Springboot(三)多环境配置
初学Springboot(二)热部署,全集配置文件
初学Springboot(一)环境搭建Springboot的优势

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值