SpringBoot视图层技术_springboot视图技术怎么做-程序员宅基地

技术标签: freemarker  Thymeleaf  spring-boot-jsp  springboot  

SpringBoot整合jsp

  • 创建spring-boot项目
  • 引入spring-boot-web启动器
<dependency>
  		<!-- spring-boot启动器 -->
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
</dependency>
  • 因为spring-boot并不推荐使用jsp,所以需要手动导入jsp引擎:
    	<!-- jstl -->
<dependency>
    	<groupId>javax.servlet</groupId>
    	<artifactId>jstl</artifactId>
</dependency>
    	<!-- jasper:jsp引擎 -->
<dependency>
    	<groupId>org.apache.tomcat.embed</groupId>
    	<artifactId>tomcat-embed-jasper</artifactId>
    	<scope>provided</scope>
</dependency>
    
<dependency>
		<groupId>org.eclipse.jdt.core.compiler</groupId>
		<artifactId>ecj</artifactId>
		<version>4.6.1</version>
		<scope>provided</scope>
</dependency>
  • 创建spring-boot的全局配置文件application.properties,在src/main/resources目录下
spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp
  • 创建controller
@Controller
public class UserController {
	
	@RequestMapping("/showUser")
	public String showUser(Model model) {
		List<User> list = new ArrayList<>();
		list.add(new User(1, "张三"));
		list.add(new User(2, "李四"));
		
		model.addAttribute("user", list);
		
		return "userList";
	}
}
public class User {
	private int id;
	private String username;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public User(int id, String username) {
		super();
		this.id = id;
		this.username = username;
	}
}
  • src/main/webapp/WEB-INF/jsp下新建jsp文件。
<body>
	<table border="1" align="center">
		<tr>
			<th>ID</th>
			<th>NAME</th>
		</tr>
		<c:forEach items="${user }" var="user">
			<tr>
				<td>${user.id }</td>
				<td>${user.username }</td>
			</tr>
		</c:forEach>
	</table>
</body>
  • 新建启动类
@SpringBootApplication
public class App {
	public static void main(String[] args) {
		SpringApplication.run(App.class, args);
	}
}


SpringBoot整合Freemarker

  • 创建项目
  • 修改pom文件,添加坐标
<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.4.RELEASE</version>
  </parent>
  <groupId>com.x</groupId>
  <artifactId>08-spring-boot-view-freemarker</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  
  <properties>
  	<java.version>1.8</java.version>
  </properties>
  
  <dependencies>
  		<!-- spring-boot启动器 -->
  	<dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
 		<!-- freemarker启动器 -->
 	<dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-freemarker</artifactId>
    </dependency>
    
  </dependencies>
</project>
  • 编写controller
@Controller
public class UserController {
	
	@RequestMapping("/showUser")
	public String showUser(Model model) {
		List<User> list = new ArrayList<>();
		list.add(new User(1, "张三"));
		list.add(new User(2, "李四"));
		
		model.addAttribute("user", list);
		
		return "userList";
	}
}
  • 编写application.properties
spring.freemarker.suffix=.ftl
spring.freemarker.template-loader-path=classpath:/templates/
  • 利用HBulider编写视图

①因为ecplise没有freemarker插件,所以编写比较麻烦;
②freemarker文件的后缀名为:.ftl
注意:spring-boot要求模板形式的视图层技术的文件,必须放置在src/main/resources/templates,且必须叫templates

<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>
			</tr>
			
			<#list user as u>
				<tr>
					<th>${u.id }</th>
					<th>${u.username }</th>
				</tr>
			</#list>
		</table>
	</body>
</html>
  • 编写启动器类


SpringBoot整合Thymeleaf

  • 创建项目
  • 修改pom文件
<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.1.12.RELEASE</version>
  </parent>
  <groupId>com.x</groupId>
  <artifactId>09-spring-boot-view-thymeleaf</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  
  <properties>
  	<java.version>1.8</java.version>
  	<spring-cloud.version>Greenwich.SR1</spring-cloud.version>
    <maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>
  </properties>
  
  <dependencies>
  		<!-- spring-boot启动器 -->
  	<dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    
    	<!-- thymeleaf启动器 -->
  	<dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    
</dependencies>
  • src/main/resources/templates,创建templates文件夹,用来存放视图文件
注意
templates:该目录是安全的,该目录下的文件是不允许外界直接访问的,意味着该目录下的文件只能通过java代码即controller等进行访问。
  • 编写controller
@Controller
public class DemoController {
	@RequestMapping("/show")
	public String getMes(Model model) {
		model.addAttribute("msg", "thymeleaf案例");
		return "index";
	}
}
  • 创建视图
    templates/index.html
<html>
<head>
<meta charset="UTF-8">
<title>Thymeleaf入门</title>
</head>
<body>
	<span th:text="${msg}"></span>
</body>
</html>
  • 编写启动器


Thymeleaf语法

  • Thymeleaf的基本使用

Thymeleaf特点:是通过其特定的语法,对html的标记做渲染。
Thymeleaf内置对象:使用#进行调用,大部分的内置对象都以s结尾,如:strings、numbers、dates等。th:text="${内置对象函数}"

  • 变量输出与字符串操作
操作符 作用
th:field 进行数据回显。<input type="text" name="username" th:field="${user.username}">可以进行数据修改。但是注意传递数据需要使用model.addAttribute(),页面取不到该数据。public String show(HttpServletRequest req, Model model)
th:text 将某值在页面输出。<span th:text="${}"></span>
th:value 将某值放入到input标签的value中。<input type="text" name="n" th:value="${}"/>
${#strings.isEmpty(key)} 判断字符串是否为空,返回true;否则返回false;<span th:text="${#strings.isEmpty(Attribute的key)}"></span>
${#strings.contains(key,‘s1’)} 判断字符串是否包含某个字符,包含返回true;不包含返回false。区分大小写。
${#strings.startsWith(key,‘s1’)} 判断字符串是否以某个字符开头,是返回true,否则返回false。
${#strings.endsWith(key,‘s1’)} 判断字符串是否以某个字符结尾,是返回true,否则返回false。
${#strings.length(key)} 返回字符串的长度。
${#strings.indexof(key,‘s1’)} 返回子串的索引位置,没找到返回-1。
${#strings.substring(key, index)} 截取字符串,参数为1个、2个、3个。与jdk方法相同
${#strings.toUpperCase(key)}、${#strings.toLowerCase(key)} 字符串转换大小写
  • 日期格式化处理

model.addAttribute(“key”,new Date());

操作符 作用
${#dates.format(key)} 根据浏览器默认语言进行格式化。
${#dates.format(key,‘yyy/MM/dd’)} 根据自定义格式进行格式化。
${#dates.year(key)} 取年
${#dates.month(key)} 取月
${#dates.day(key)} 取日
  • 条件判断

model.addAttribute(“sex”,“男”);
model.addAttribute(“id”,“2”);

操作符 作用
th:if <span th:if="${sex} == '男' ">性别:男</span>
th:switch 多分支判断。例如下:
<div th:switch="${id}">
	<span th:case="1">ID为1</span>
	<span th:case="2">ID为2</span>
</div>
  • 迭代遍历
操作符 作用
th:each 迭代遍历,类似java中的for(Obj : obj)。th:each="u : ${list}",例1:
th:each="u,var : ${list}" var为状态变量,可取:index(迭代器索引,从0开始)、count(迭代对象的技术,从1开始)、size(被迭代对象的长度)、even(迭代次数是偶数,布尔值)、odd(迭代次数是基数)、first(是否是第一条)、last(是否是最后一条)
th:each=“maps : ${map}” 迭代map; 方法有:.value.key
例1:
<tr th:each="u : ${list}">
	<td th:text="${u.id}"></td>
</tr>
  • 域对象操作

request.setAttribute(“req”,“HttpServletRequest”);
request.getSession().setAttribute(“session”,“HttpSession”);
request.getSession().getServletContext().setAttribute(“app”,“application”);

操作符 作用
th:text="${#httpServletRequest.getAttribute(‘req’)}" 从request中取值。
th:text="${session.session}" 从session中取值。
th:text="${application.app}" 从application中取值。
  • URL表达式

URL表达式语法
基本语法:@{}
URL类型
绝对路径:
相对路径:

@Controller
public class DemoController {
	@RequestMapping("/{page}")
	public String getMes(@PathVariable String page) {
		return page;
	}
}
操作符 作用
th:href <a th:href="@{http://www.baidu.com}">绝对路径</a>等同于 <a href="http://www.baidu.com">绝对路径1</a>
th:href <a th:href="@{/show}">相对路径</a>,从当前项目的根目录进行查找相应的controller。
th:href <a th:href="@{~/project2/resources-name}">相对路径1</a>,从当前服务器的根目录进行查找相应的项目下的资源。
th:href <a th:href="@{/show(key=value)}">相对路径2</a>,url参数传递。
th:href <a th:href="@{/path/{id}/show(key=value)}">相对路径3</a>,url中通过restful风格进行参数传递。
th:src
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq_42197800/article/details/104427423

智能推荐

使用 gitee+sphinx+readthedocs 搭建个人博客_添加readthedocs项目-程序员宅基地

文章浏览阅读1.1k次,点赞21次,收藏25次。gitee,是国内免费的代码托管平台,相比github在国内,有更快的访问速度,全中文界面,对国人,更友好。sphinx,是一个功能强大的文档生成器,具有许多用于编写技术文档的强大功能。readthedocs,是一个免费在线文档托管范围平台,可以使用二级域名显示个人博客。_添加readthedocs项目

详解Google Authenticator工作原理_authenticator 二维码 算法-程序员宅基地

文章浏览阅读5.5k次。详解Google Authenticator工作原理发表于2014-09-23 08:28| 10060次阅读| 来源CSDN| 16 条评论| 作者伍昆Google二维码Google Authenticator算法 摘要:Google Authenticator是谷歌推出的一款动态口令工具,旨在解决大家Google账户遭到恶意攻击的问题。那么,Authen_authenticator 二维码 算法

普通函数和箭头函数之间的区别_箭头函数和普通函数之间如何转换-程序员宅基地

文章浏览阅读1k次。I.普通函数和ES6的箭头函数除了this指向不同之外还有什么不同?A.箭头函数作为匿名函数,不能作为构造函数,不能使用new关键字B.箭头函数不绑定arguments,用rest参数...解决C.箭头函数会捕获其上下文的this值,作为自己的this值D.箭头函数当方法使用,没有定义this的绑定E.使用call()和apply()调用,传入参数时,参数一的改变对this没有..._箭头函数和普通函数之间如何转换

如果结束进程拒绝访问,可以尝试以下-程序员宅基地

文章浏览阅读2.3k次。如果taskkill /f /pid 123 出现拒绝访问时,可使用以下方式删除进程:wmic process where name=‘qq.exe’ delete11如果这样还杀不死,恐怕就要进[安全模式]删除了。杀了进程,想删除文件,可以这样删除cmd下运行:DEL /F /A /Q 文件名抄自-吉吉教主...

Visual Studio-IIS Express 支持局域网访问配置-程序员宅基地

文章浏览阅读201次。转自:http://www.itnose.net/detail/6132793.html使用Visual Studio开发Web网页的时候有这样的情况:想要在调试模式下让局域网的其他设备进行访问,以便进行测试。虽然可以部署到服务器中,但是却无法进行调试,就算是注入进程进行调试也是无法达到自己的需求;所以只能在Visual Studio-IIS Express 中进行调试。而于此将..._visual studio iis express debug localhost

Oracle 数据库层级遍历查询_oracle遍历查询结果集-程序员宅基地

文章浏览阅读1.5k次。首先创建一张用于测试的表,表明为 TREE,表中有3个字段,分别是,ID,NANE,UP_ID。UP_ID 是 ID 的上层,主要实现树形结构的存储。1.1 初始化测试数据1.1.1 写入数据1.1.2 树形结构如下图root(8)一(1)二(2)三(3)五(5)root(6)四(4)2. 树形结构遍历查询2.1 从父节点遍历查询结果如下:2.2 从子节点开始遍历查询结果是:2.3 start with 条件 connect by prior_oracle遍历查询结果集

随便推点

解卷积的维度计算_转置卷积pad多少是整数倍-程序员宅基地

文章浏览阅读4.5k次。解卷积(deconvolution)或者反卷积,类似于卷积的逆运算;如果按照严格的数学公式来叫,应该叫做“转置卷积(transpose convolution)”。解卷积最直观的作用是扩大feature map的分辨率,在语义分割任务中被广泛使用。解卷积的维度计算公式如下: w_new = stride*w - 2*pad + (kernel-stride) 从上面的公式可以看到:与卷积相..._转置卷积pad多少是整数倍

linux 块设备子系统,Linux块设备IO子系统(二) _页高速缓存-程序员宅基地

文章浏览阅读143次。磁盘驱动就是实现磁盘空间和内存空间数据上的交互,在上一篇中我们讨论了内存端的Page Segment Block Sector相关的概念,本文以3.14内核为例,讨论这部分内存是如何被组织管理的。我们知道,为了解决CPU和内存的速度不匹配,计算机系统引入了Cache缓存机制,这种硬件Cache的速度接近CPU内部寄存器的速度,可以提高系统效率,同样的思路也适用于解决内存和磁盘的速度不匹配问题,此外..._linux块设备io子系统(二)

狂神说SpringBoot07:整合JDBC-程序员宅基地

文章浏览阅读4.9k次,点赞12次,收藏48次。狂神说SpringBoot系列连载课程,通俗易懂,基于SpringBoot2.2.5版本,欢迎各位狂粉转发关注学习。未经作者授权,禁止转载SpringData简介对于数据访问层,无论是 ...

flash_镁光mt25qu01的擦除时序要求-程序员宅基地

文章浏览阅读377次。记录flash 调试过程中的问题_镁光mt25qu01的擦除时序要求

竹云+巨杉丨互信认证 安全可靠_竹云iam 操作手册-程序员宅基地

文章浏览阅读2.3k次。近日,竹云IAM统一身份安全管理平台与巨杉数据库完成技术兼容和认证工作,经双方共同严格测试,巨杉数据库V3.4与竹云身份管理与访问控制平台软件V6.0,竹云安全内控管理平台软件V6.0在兼容性、可靠性和性能等方面均能满足用户的关键性应用需求,双方将共同打造基于分布式数据库的微服务架构身份管理与访问控制系统联合解决方案。随着国家对重点行业“安全可控信息技术”的要求不断深化,也越来越强调基于国产生态环境下信息系统的自主可控。作为拥有完全自主可控国产化技术的高新科技企业,竹云与巨杉的紧密合作将为用户提供更高效、_竹云iam 操作手册

c++中string和char*的类型转换,并求string的长度_c_str() 长度-程序员宅基地

文章浏览阅读1.5k次。一、char*(char)转string(直接赋值)#include<iostream>#include<string>#include <typeinfo>using namespace std;int main(){ string str; const char* p = "ch"; //char p[] = "ch"; str = p; cout << str << endl; _c_str() 长度