栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringBoot学习2-基本使用

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringBoot学习2-基本使用

说明

日常使用中,API需要使用到JSON操作,JSON相关操作可以使用Gson,虽然阿里有FastJson,但是执行效率和底层实现上GSON具有明显优势,网站可能需要使用到模板引擎,模板引擎使用thymeleaf。

关于一些数据类操作,可以使用lombok来提高操作效率。


各个的pom依赖:


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



	org.projectlombok
	lombok
	true



	com.google.code.gson
	gson
	2.8.6


thymeleaf

thymeleaf使用,需要在模板中加入标签


控制器上,可以在具体的方法上加上Model,使用model.addAttribute("key",val);来对模板变量进行赋值,接着return一个模板文件路径即可。

引擎配置:

可以在resources/application.properties中写入全局配置信息:

# 模板路径
spring.thymeleaf.prefix=classpath:/templates/
# 模板扩展名
spring.thymeleaf.suffix=.html
# 其他
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html
# 是否缓存
spring.thymeleaf.cache=false
spring.thymeleaf.check-template-location=true

关于thymeleaf模板标签更多内容,点击这里


GSON
//实例化
Gson gson = new Gson();
//实例化
user u = user.builder().name("张三").id(1).age(25).build();
//序列化JSON(对象)
String json =  gson.toJson(u);
//反序列化到对象
u =  gson.fromJson(json,user.class);
//序列化JSON(数组)
List userList = new ArrayList<>();
userList.add(u);
json =  gson.toJson(userList);
//反序列化(数组)
Type type = new TypeToken>() {}.getType();
List lists = gson.fromJson(json,type);

lombok
package com.example.demo.model;

import lombok.Builder;
import lombok.Data;

@Data
@Builder
public class user {

    private String name;

    private int age;

    private int id;
}

可以在数据类上写上@Data注解,来实现自动处理,写@Builder注解,即可通过builder()快速实例化设置数据类。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/865306.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号