Spring Boot (2) Restful风格接口
Rest接口
动态页面jsp早已过时,现在流行的是vuejs、angularjs、react等前端框架 调用 rest接口(json格式),如果是单台服务器,用动态还是静态页面可能没什么大区别,如果服务器用到了集群,负载均衡,CDN等技术,用动态页面还是静态页面差别非常大。
传统rest用法
用spring mvc可以很容易的实现json格式的rest接口,这是比较传统的用法,在spring boot中已经自动配置了jackson。
@Controller
public class HelloController { @Autowired
String hello; @RequestMapping(value = "/hello",method = RequestMethod.POST)
@ResponseBody
public String hello(User user){
return "hello world";
}
}
新的rest用法
在比较新的spring版本中,出了几个新的注解,简化了上面的用法,如下
/**
* RestController 等价于 @Controller 和 @ResponseBody
*/
@RestController
public class HelloController { @PostMapping("/postUserAPI")
public User postUserAPI(@RequestBody User user){ //@RequestBody json格式参数->自动转换为user
return user;
}
}
ajax调用Rest
<html>
<head>
<title>Title</title>
<script src="http://libs.baidu.com/jquery/1.7.2/jquery.min.js"></script>
<script>
$(function(){
var data = {
userId:1,
userName:'david'
};
$.ajax({
url:'/dev/postUserAPI',
type:"post",
data:JSON.stringify(data),
contentType:'application/json;charset=UTF-8',
dataType:"json",
success:function(data){
console.log(data)
}
});
});
</script>
</head>
<body>
index
</body>
</html>

spring boot 默认使用jackson 处理json,如果我们想要使用fast的json解析框架的话
1.我们需要在pom.xml中引入相应的依赖
<!--fastjson数据配置-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.29</version>
</dependency>
2.需要在SpringBootApplication启动类中配置一下,配置有两种方式:
1.继承WebMVCConfigurerAdapter并重写方法configureMessageConverters 添加我们自定义的json解析框架。
package com.spring.boot; import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import java.util.List; @SpringBootApplication
public class BootApplication extends WebMvcConfigurerAdapter { @Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
super.configureMessageConverters(converters); //1.定义一个convert转换消息对象
FastJsonHttpMessageConverter fastConverter=new FastJsonHttpMessageConverter(); //2.添加fastjson的配置信息,比如:是否要格式化返回json数据
FastJsonConfig fastJsonConfig=new FastJsonConfig();
fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
fastConverter.setFastJsonConfig(fastJsonConfig);
converters.add(fastConverter);
} public static void main(String[] args) {
SpringApplication.run(BootApplication.class, args);
}
}
2.使用@Bean注入第三方的json解析器。
package com.david; import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.web.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import java.util.List; @SpringBootApplication
public class DemoApplication{ @Bean//使用@Bean注入fastJsonHttpMessageConvert
public HttpMessageConverters fastJsonHttpMessageConverters(){
//1.需要定义一个Convert转换消息的对象
FastJsonHttpMessageConverter fastConverter=new FastJsonHttpMessageConverter(); //2.添加fastjson的配置信息,比如是否要格式化返回的json数据
FastJsonConfig fastJsonConfig=new FastJsonConfig();
fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat); //3.在convert中添加配置信息
fastConverter.setFastJsonConfig(fastJsonConfig); HttpMessageConverter<?> converter=fastConverter;
return new HttpMessageConverters(converter);
} public static void main(String[] args) {
SpringApplication.run(DemoApplication.class,args);
}
}
fastjson常用方法:
//bean转换json
//将对象转换成格式化的json
JSON.toJSONString(obj, true); //将对象转换成非格式化的json
JSON.toJSONString(obj, false); //obj设计对象
//对于复杂类型的转换,对于重复的引用在转成json串后在json串中出现引用的字符,比如 $ref":"$[0].books[1]
Student stu = new Student();
Set books = new HashSet();
Book book = new Book();
books.add(book);
stu.setBooks(books); List list = new ArrayList();
for (int i = 0; i < 5; i++)
list.add(stu); String json = JSON.toJSONString(list, true); //json转换bean
String json = "{\"id\":\"2\",\"name\":\"Json技术\"}";
Book book = JSON.parseObject(json, Book.class); //json转换复杂的bean,比如List,Map
String json = "[{\"id\":\"1\",\"name\":\"Json技术\"},{\"id\":\"2\",\"name\":\"java技术\"}]"; //将json转换成List
List list = JSON.parseObject(json, new TypeReference<ARRAYLIST>() {
}); //将json转换成Set
Set set = JSON.parseObject(json, new TypeReference<HASHSET>() {
}); //通过json对象直接操作json
//从json串中获取属性
String propertyName = 'id';
String propertyValue = "";
String json = "{\"id\":\"1\",\"name\":\"Json技术\"}";
JSONObject obj = JSON.parseObject(json);
propertyValue = obj.get(propertyName)); //除去json中的某个属性
String propertyName = 'id';
String propertyValue = "";
String json = "{\"id\":\"1\",\"name\":\"Json技术\"}";
JSONObject obj = JSON.parseObject(json);
Set set = obj.keySet();
propertyValue = set.remove(propertyName);
json = obj.toString(); //向json中添加属性
String propertyName = 'desc';
Object propertyValue = "json的玩意儿";
String json = "{\"id\":\"1\",\"name\":\"Json技术\"}";
JSONObject obj = JSON.parseObject(json);
obj.put(propertyName, JSON.toJSONString(propertyValue));
json = obj.toString(); //修改json中的属性
String propertyName = 'name';
Object propertyValue = "json的玩意儿";
String json = "{\"id\":\"1\",\"name\":\"Json技术\"}";
JSONObject obj = JSON.parseObject(json);
Set set = obj.keySet();
if (set.contains(propertyName))
obj.put(propertyName, JSON.toJSONString(propertyValue));
json = obj.toString(); //判断json中是否有属性
String propertyName = 'name';
boolean isContain = false;
String json = "{\"id\":\"1\",\"name\":\"Json技术\"}";
JSONObject obj = JSON.parseObject(json);
Set set = obj.keySet();
isContain = set.contains(propertyName); //json中日期格式的处理
Object obj = new Date();
String json = JSON.toJSONStringWithDateFormat(obj, "yyyy-MM-dd HH:mm:ss.SSS");
//使用JSON.toJSONStringWithDateFormat,该方法可以使用设置的日期格式对日期进行转换
jackson常用方法:
//bean转换json
//将类转换成Json,obj是普通的对象,不是List,Map的对象
String json = JSONObject.fromObject(obj).toString(); //将List,Map转换成Json
String json = JSONArray.fromObject(list).toString();
String json = JSONArray.fromObject(map).toString(); //json转换bean
String json = "{\"id\":\"1\",\"name\":\"Json技术\"}";
JSONObject jsonObj = JSONObject.fromObject(json);
Book book = (Book)JSONObject.toBean(jsonObj,Book.class); //json转换List,对于复杂类型的转换会出现问题
String json = "[{\"id\":\"1\",\"name\":\"Json技术\"},{\"id\":\"2\",\"name\":\"Java技术\"}]";
JSONArray jsonArray = JSONArray.fromObject(json);
JSONObject jsonObject;
T bean;
int size = jsonArray.size();
List list = new ArrayList(size);
for (int i = 0; i < size; i++) {
jsonObject = jsonArray.getJSONObject(i);
bean = (T) JSONObject.toBean(jsonObject, beanClass);
list.add(bean);
} //json转换Map
String jsonString = "{\"id\":\"1\",\"name\":\"Json技术\"}";
JSONObject jsonObject = JSONObject.fromObject(jsonString);
Iterator keyIter = jsonObject.keys();
String key;
Object value;
Map valueMap = new HashMap();
while (keyIter.hasNext()) {
key = (String) keyIter.next();
value = jsonObject.get(key).toString();
valueMap.put(key, value);
} //json对于日期的操作比较复杂,需要使用JsonConfig,比Gson和FastJson要麻烦多了
//创建转换的接口实现类,转换成指定格式的日期
class DateJsonValueProcessor implements JsonValueProcessor{
public static final String DEFAULT_DATE_PATTERN = "yyyy-MM-dd HH:mm:ss.SSS";
private DateFormat dateFormat;
public DateJsonValueProcessor(String datePattern) {
try {
dateFormat = new SimpleDateFormat(datePattern);
} catch (Exception ex) {
dateFormat = new SimpleDateFormat(DEFAULT_DATE_PATTERN);
}
}
public Object processArrayValue(Object value, JsonConfig jsonConfig) {
return process(value);
}
public Object processObjectValue(String key, Object value,
JsonConfig jsonConfig) {
return process(value);
}
private Object process(Object value) {
return dateFormat.format[1];
Map<STRING,DATE> birthDays = new HashMap<STRING,DATE>();
birthDays.put("WolfKing",new Date());
JSONObject jsonObject = JSONObject.fromObject(birthDays, jsonConfig);
String json = jsonObject.toString();
System.out.println(json);
}
}
//JsonObject 对于json的操作和处理 //从json串中获取属性
String jsonString = "{\"id\":\"1\",\"name\":\"Json技术\"}";
Object key = "name";
Object value = null;
JSONObject jsonObject = JSONObject.fromObject(jsonString);
value = jsonObject.get(key);
jsonString = jsonObject.toString(); //除去json中的某个属性
String jsonString = "{\"id\":\"1\",\"name\":\"Json技术\"}";
Object key = "name";
Object value = null;
JSONObject jsonObject = JSONObject.fromObject(jsonString);
value = jsonObject.remove(key);
jsonString = jsonObject.toString(); //向json中添加和修改属性,有则修改,无则添加
String jsonString = "{\"id\":\"1\",\"name\":\"Json技术\"}";
Object key = "desc";
Object value = "json的好东西";
JSONObject jsonObject = JSONObject.fromObject(jsonString);
jsonObject.put(key,value);
jsonString = jsonObject.toString(); //判断json中是否有属性
String jsonString = "{\"id\":\"1\",\"name\":\"Json技术\"}";
boolean containFlag = false;
Object key = "desc";
JSONObject jsonObject = JSONObject.fromObject(jsonString);
containFlag = jsonObject.containsKey(key);
Spring Boot (2) Restful风格接口的更多相关文章
- 使用Spring boot开发RestFul 风格项目PUT/DELETE方法不起作用
在使用Spring boot 开发restful 风格的项目,put.delete方法不起作用,解决办法. 实体类Student @Data public class Student { privat ...
- Spring Boot构建 RESTful 风格应用
Spring Boot构建 RESTful 风格应用 1.Spring Boot构建 RESTful 风格应用 1.1 实战 1.1.1 创建工程 1.1.2 构建实体类 1.1.4 查询定制 1.1 ...
- Spring Boot2 系列教程(三十一)Spring Boot 构建 RESTful 风格应用
RESTful ,到现在相信已经没人不知道这个东西了吧!关于 RESTful 的概念,我这里就不做过多介绍了,传统的 Struts 对 RESTful 支持不够友好 ,但是 SpringMVC 对于 ...
- spring boot(3)-Rest风格接口
Rest接口 虽然现在还有很多人在用jsp,但是其实这种动态页面早已过时,现在前端流行的是静态HTML+ rest接口(json格式).当然,如果是单台服务器,用动态还是静态页面可能没什么很大区别,但 ...
- Spring Boot 之restful风格
步骤一:restful风格是什么? 我们知道在做web开发的过程中,method常用的值是get和post.可事实上,method值还可以是put和delete等等其他值. 既然method值如此丰富 ...
- SpringBoot2.0基础案例(01):环境搭建和RestFul风格接口
一.SpringBoot 框架的特点 1.SpringBoot2.0 特点 1)SpringBoot继承了Spring优秀的基因,上手难度小 2)简化配置,提供各种默认配置来简化项目配置 3)内嵌式容 ...
- 使用SpringBoot编写Restful风格接口
一.简介 Restful是一种对url进行规范的编码风格,通常一个网址对应一个资源,访问形式类似http://xxx.com/xx/{id}/{id}. 举个栗子,当我们在某购物网站上买手机时会 ...
- Spring Boot开发RESTful接⼝服务及单元测试
Spring Boot开发RESTful接⼝服务及单元测试 常用注解解释说明: @Controller :修饰class,⽤来创建处理http请求的对象 @RestController :Spring ...
- Spring Boot - Building RESTful Web Services
Spring Boot Building RESTful Web Services https://www.tutorialspoint.com/spring_boot/spring_boot_bui ...
随机推荐
- 【剑指Offer】剑指offer题目汇总
本文为<剑指Offer>刷题笔记的总结篇,花了两个多月的时间,将牛客网上<剑指Offer>的66道题刷了一遍,以博客的形式整理了一遍,这66道题属于相对基础的算法题目,对于 ...
- ZOJ 3199 Longest Repeated Substring
Longest Repeated Substring Time Limit: 5000ms Memory Limit: 32768KB This problem will be judged on Z ...
- App的登陆注册接口安全设计
最近一APP产品,我担任的主要模块之一是后台登录注册模块的接口开发.基本完成,就说说并记录一下关于登录注册接口的一些东西,因为也涉及到接口的安全方面的问题. 1.先一般的app的登录注册接口安全设计上 ...
- nyoj_264_国王的魔镜_201311271800
国王的魔镜 时间限制:3000 ms | 内存限制:65535 KB 难度:1 描述 国王有一个魔镜,可以把任何接触镜面的东西变成原来的两倍——只是,因为是镜子嘛,增加的那部 ...
- 机器学习1k近邻
自己一直学习计算机视觉方面的东西,现在想学习一下数据挖掘跟搜索引擎,自己基础也有点薄弱,看朱明的那本数据挖掘,只能片面的了解这个数据挖掘.不过最近有一本书 机器学习实战,于是乎通过实战的形式了解一下基 ...
- Android中@+id和@id的差别
Android中的组件须要用一个int类型的值来表示.这个值也就是组件标签中的id属性值. id属性仅仅能接受资源类型的值,也就是必须以@开头的值,比如,@id/abc.@+id/xyz等. 假设在 ...
- Android自己定义Toast
一.引言 在开发的过程中你会发现Android自身的Toast提示有很多限制,比方我想自己定义Toast的动画.自己定义一个美观的View显示在Toast中.很多其它的是让Toast显示指定的时长等等 ...
- C++和C#的指针小解
昨天和赵崇说了一下工作的事情,说起了性能问题就讨论起了数据结果和指针对性能的影响.曾经一直没有想到这方面的事情,这几天专门抽时间回想一下这方面的知识,然后一点一点的总结一下,看看数据结构和指针在咱们代 ...
- Android开发之怎样监听让Service不被杀死
一.Service简单介绍 Service是在一段不定的时间执行在后台,不和用户交互应用组件. 每一个Service必须在manifest中 通过<service>来声明. 能够通过con ...
- UI设计--->全心全意为人民服务的宗旨---->注重客户体验--->软件持久的生命力
UI即User Interface(用户界面)的简称. UI设计是指对软件的人机交互.操作逻辑.界面美观的总体设计. 好的UI设计不仅是让软件变得有个性有品味,还要让软件的操作变得舒适简单.自由.充分 ...