美文网首页
SpringBoot视图层技术

SpringBoot视图层技术

作者: Yanl__ | 来源:发表于2019-12-19 11:05 被阅读0次

1.整合jsp
2.整合freemarker
3.整合Thymeleaf

1.整合jsp

  1. 创建项目
  2. 修改pom文件,添加坐标
    springboot默认不推荐用jsp,就没有整合tomcat中对jsp处理的引擎jasper,需要额外配置jstl与jasper
  3. 创建SpringBoot的全局配置文件 application.properties
    设置jsp文件的前缀,后缀,这样就可以在控制器中直接返回字符串,然后拼接前缀后缀,跳转到对应的jsp页面
  4. 创建Controller
  5. 创建jsp
    jsp文件应该放在src/main/webapp/WEB-INF/jsp下
  6. 创建启动类
2. 修改pom文件,添加坐标
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <!-- 添加父项目-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.2.RELEASE</version>
    </parent>

    <groupId>com.steer</groupId>
    <artifactId>springboot03_jsp</artifactId>
    <version>1.0-SNAPSHOT</version>

    <!-- springBoot的启动器-->
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- jstl -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>
        <!-- jasper -->
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
            <scope>provided</scope>
        </dependency>
    </dependencies>

</project>

3.创建SpringBoot的全局配置文件 application.properties
#jsp文件的前缀,后缀,这样就可以在控制器中直接返回字符串,然后拼接前缀后缀,跳转到对应的jsp页面
spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp

4. 创建Controller
@Controller
public class ShowUser {
    /**
     * 处理请求
     * @return
     */
    @RequestMapping("showUser")
    public String showUser(Model model){
        // 添加展示数据
        ArrayList<User> list = new ArrayList<>();
        list.add(new User(1,"张三",20));
        list.add(new User(2,"李四",22));
        list.add(new User(3,"王五",24));
        // 需要一个Model对象
        model.addAttribute("list", list);
        return "userList";

    }
}
5. 创建jsp
  ······
6. 创建启动类
  ······

2.整合freemarker

  1. 创建maven项目,继承父项目,修改pom配置文件
  2. 编写视图

注意:springBoot 要求模板形式的视图层技术的文件必须要放到src/main/resources 目录下必须要一个名称为templates

  1. 编写Controller
  2. 编写启动类
1. pom配置文件
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <!-- 添加父项目-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.2.RELEASE</version>
    </parent>

    <groupId>com.steer</groupId>
    <artifactId>springboot_freemarker</artifactId>
    <version>1.0-SNAPSHOT</version>


    <!-- springBoot的启动器-->
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
        </dependency>
    </dependencies>
</project>

2. 编写视图
<html>
    <head>
        <title>展示用户数据</title>
        <meta charset="utf-8"></meta>
    </head>
    <body>
        <table border="1" align="center" width="50%">
            <tr>
                <th>ID</th>
                <th>Name</th>
                <th>Age</th>
            </tr>
        
            <#--    传过来的数据类型 传过来的名称 迭代后取的别名-->
            <#list list as user >
                <tr>
                    <td>${user.userid}</td>
                    <td>${user.name}</td>
                    <td>${user.age}</td>
                </tr>
            </#list>
        </table>
    </body>
</html>

3. 编写Controller
@Controller
public class ShowUser {
    /**
     * 处理请求
     * @return
     */
    @RequestMapping("/showUser")
    public String showUser(Model model){
        // 添加展示数据
        ArrayList<User> list = new ArrayList<>();
        list.add(new User(1,"张三",20));
        list.add(new User(2,"李四",22));
        list.add(new User(3,"王五",24));
        // 需要一个Model对象
        model.addAttribute("list", list);
        System.out.println("执行controller");
        return "userList";

    }
}

4. 编写启动类
@SpringBootApplication
public class App {
    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }

}

3.整合Thymeleaf

  • 视图目录位置:src/main/resources/templates (该目录是安全的,意味着该目录下的内容是不允许外界直接访问的)
  • Thymeleaf特点:通过特定语法对html的标记做渲染
1. 编写控制器
@Controller
public class ShowController {
    @RequestMapping("show")
    public String show(Model model){
        model.addAttribute("msg", "thymeleaf测试");
        return "index";
    }
}

2. 编写视图  index.html
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Thymeleaf入门</title>
</head>
<body>
    <span th:text="Hello"></span>
    <hr/>
    <span th:text="${msg}"></span>
</body>
</html>

Thymeleaf语法

关键字 功能介绍 案例
th:id 替换id <input th:id="'xxx' + ${collect.id}"/>
th:text 文本替换 <p th:text="${collect.description}">description</p>
th:utext 支持html的文本替换 <p th:utext="${htmlcontent}">conten</p>
th:object 替换对象 <div th:object="${session.user}">
th:value 属性赋值 <input th:value="${user.name}" />
th:with 变量赋值运算 <div th:with="isEven=${prodStat.count}%2==0"></div>
th:style 设置样式 th:style="'display:' + @{(${sitrue} ? 'none' : 'inline-block')} + ''"
th:onclick 点击事件 th:onclick="'getCollect()'"
th:each 属性赋值 <tr th:each="user,userStat:${users}">
th:if 判断条件 <a th:if="${userId == collect.userId}" >
th:unless 和th:if判断相反 <a th:href="@{/login}" th:unless=${session.user != null}>Login</a>
th:href 链接地址 <a th:href="@{/login}" th:unless=${session.user != null}>Login</a> />
th:switch 多路选择 配合th:case 使用 <div th:switch="${user.role}">
th:case th:switch的一个分支 <p th:case="'admin'">User is an administrator</p>
th:fragment 布局标签,定义一个代码片段,方便其它地方引用 <div th:fragment="alert">
th:include 布局标签,替换内容到引入的文件 <head th:include="layout :: htmlhead" th:with="title='xx'"></head> />
th:replace 布局标签,替换整个标签到引入的文件 <div th:replace="fragments/header :: title"></div>
th:selected selected选择框 选中 th:selected="({xxx.id} =={configObj.dd})"
th:src 图片类地址引入 <img class="img-responsive" alt="App Logo" th:src="@{/img/logo.png}" />
th:inline 定义js脚本可以使用变量 <script type="text/javascript" th:inline="javascript">
th:action 表单提交的地址 <form action="subscribe.html" th:action="@{/subscribe}">
th:remove 删除某个属性 <tr th:remove="all">
1.all:删除包含标签和所有的孩子。
2.body:不包含标记删除,但删除其所有的孩子。
3.tag:包含标记的删除,但不删除它的孩子。
4.all-but-first:删除所有包含标签的孩子,除了第一个。
5.none:什么也不做。这个值是有用的动态评估。
th:attr 设置标签属性,多个属性可以用逗号分隔 比如th:attr="src=@{/image/aa.jpg},title=#{logo}",此标签不太优雅,一般用的比较少。
  1. 变量输出与字符串操作
  2. 日期格式化处理
  3. 条件判断
  • th:if
  • th:switch
<span th:if="${sex} == '男'">
性别:男
</span>
<span th:if="${sex} == '女'">
性别:女
</span>
  1. 迭代遍历
  • th:each
  • th:each 状态变量
  • th:each 迭代Map
状态变量
<table border="1">
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
<th>Index</th>
<th>Count</th>
<th>Size</th>
<th>Even</th>
<th>Odd</th>
<th>First</th>
<th>lase</th>
</tr>
<tr th:each="u,var : ${list}">
<td th:text="${u.userid}"></td>
<td th:text="${u.username}"></td>
<td th:text="${u.userage}"></td>
<td th:text="${var.index}"></td>
<td th:text="${var.count}"></td>
<td th:text="${var.size}"></td>
<td th:text="${var.even}"></td>
<td th:text="${var.odd}"></td>
<td th:text="${var.first}"></td>
<td th:text="${var.last}"></td>
</tr>
</table>

状态变量属性
1,index:当前迭代器的索引从0 开始
2,count:当前迭代对象的计数从1 开始
3,size:被迭代对象的长度
4,even/odd:布尔值,当前循环是否是偶数/奇数从0 开始
5,first:布尔值,当前循环的是否是第一条,如果是返回true 否则返回false
6,last:布尔值,当前循环的是否是最后一条,如果是则返回true 否则返回false

迭代map
<table border="1">
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
</tr>
<tr th:each="maps : ${map}">
<td th:text="${maps}"></td>
</tr>
</table>
<th/>
<table border="1">
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
</tr>
// 传过来一个map, 取名maps,每个迭代的maps就是传过来的map的一个键值对。所以需要在td中再迭代一次
<tr th:each="maps : ${map}">
<td th:each="entry:${maps}"
th:text="${entry.value.userid}" ></td>
<td th:each="entry:${maps}"
th:text="${entry.value.username}"></td>
<td th:each="entry:${maps}"
th:text="${entry.value.userage}"></td>
</tr>
</table>
  1. 域对象操作
  • HttpServletRequest
  • HttpSession
  • ServletContext
参数:HttpServletRequest request
1. 
request.setAttribute("req", "HttpServletRequest");

Request:<span th:text="${#httpServletRequest.getAttribute('req')}"></span><br/>

2.
request.getSession().setAttribute("sess", "HttpSession");

Session:<span th:text="${session.sess}"></span><br/>

3.
request.getSession().getServletContext().setAttribute("app", "Application");

Application:<span th:text="${application.app}"></span>
  1. URL表达式
  • 基本语法: @{}
  • URL类型:1.绝对路径 2.相对路径
1. 绝对路径
<a th:href="@{http://www.baidu.com}">绝对路径</a><br/>
<a href="http://www.baidu.com">绝对路径</a><br/>

两个表达式含义一致

2.相对路径
<a th:href="@{/show}">相对于服务器的根</a>  // 直接看项目控制器中拦截show的控制器,跳转到对应页面
<a th:href="@{~/project2/resourcename}">相对于服务器的根</a>  // 相对与服务器路径的根
  • 在url 中实现参数传递
可以传递一个或者多个
<a th:href="@{/show(id=1,name=zhagnsan)}">相对路径-传参</a> 

在url 中通过restful 风格进行参数传递
<a th:href="@{/path/{id}/show(id=1,name=zhagnsan)}"> 相对路径- 传参-restful</a>

相关文章

网友评论

      本文标题:SpringBoot视图层技术

      本文链接:https://www.haomeiwen.com/subject/pvsunctx.html