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风格接口的更多相关文章

  1. 使用Spring boot开发RestFul 风格项目PUT/DELETE方法不起作用

    在使用Spring boot 开发restful 风格的项目,put.delete方法不起作用,解决办法. 实体类Student @Data public class Student { privat ...

  2. Spring Boot构建 RESTful 风格应用

    Spring Boot构建 RESTful 风格应用 1.Spring Boot构建 RESTful 风格应用 1.1 实战 1.1.1 创建工程 1.1.2 构建实体类 1.1.4 查询定制 1.1 ...

  3. Spring Boot2 系列教程(三十一)Spring Boot 构建 RESTful 风格应用

    RESTful ,到现在相信已经没人不知道这个东西了吧!关于 RESTful 的概念,我这里就不做过多介绍了,传统的 Struts 对 RESTful 支持不够友好 ,但是 SpringMVC 对于 ...

  4. spring boot(3)-Rest风格接口

    Rest接口 虽然现在还有很多人在用jsp,但是其实这种动态页面早已过时,现在前端流行的是静态HTML+ rest接口(json格式).当然,如果是单台服务器,用动态还是静态页面可能没什么很大区别,但 ...

  5. Spring Boot 之restful风格

    步骤一:restful风格是什么? 我们知道在做web开发的过程中,method常用的值是get和post.可事实上,method值还可以是put和delete等等其他值. 既然method值如此丰富 ...

  6. SpringBoot2.0基础案例(01):环境搭建和RestFul风格接口

    一.SpringBoot 框架的特点 1.SpringBoot2.0 特点 1)SpringBoot继承了Spring优秀的基因,上手难度小 2)简化配置,提供各种默认配置来简化项目配置 3)内嵌式容 ...

  7. 使用SpringBoot编写Restful风格接口

    一.简介    Restful是一种对url进行规范的编码风格,通常一个网址对应一个资源,访问形式类似http://xxx.com/xx/{id}/{id}. 举个栗子,当我们在某购物网站上买手机时会 ...

  8. Spring Boot开发RESTful接⼝服务及单元测试

    Spring Boot开发RESTful接⼝服务及单元测试 常用注解解释说明: @Controller :修饰class,⽤来创建处理http请求的对象 @RestController :Spring ...

  9. Spring Boot - Building RESTful Web Services

    Spring Boot Building RESTful Web Services https://www.tutorialspoint.com/spring_boot/spring_boot_bui ...

随机推荐

  1. IDEA 创建一个普通的java项目

    IntelliJ IDEA 如何创建一个普通的java项目,及创建java文件并运行 首先,确保idea软件正确安装完成,java开发工具包jdk安装完成. IntelliJ IDEA下载地址:htt ...

  2. 【Android】登陆界面设计

    界面布局 布局其实很简单,用相对布局累起来就可以了,然后注册和记住密码这两个控件放在一个水平线性布局里 界面底部还设置了一个QQ一键登录的入口,可以直接用. 控件的ID命名有点乱 <?xml v ...

  3. Tensorflow人工智能入门(一)

    前言: 作为一个程序员,已经离开开发岗好多年,最近突然迷茫了,不知道自己何去何从.互联网技术发展的速度已快得难以想象,许久不码代码的手也越来越僵直,需求沟通中的套话和空话却越发的熟练,这和当年入行时的 ...

  4. H5音乐播放器

    前段时间无聊用JavaScript基于H5的audio写一个音乐播放器.误喷,技术有限,文笔不好之处希望各位大神海涵. 1.HTML代码: <div id="music" c ...

  5. jenkins简单持续构建

    一.安装jenkins 二.将需要持续构建的java project打包成jar文件 1.选择导出需要运行的main方法所在java类

  6. CF410div2 D. Mike and distribution

    /* CF410div2 D. Mike and distribution http://codeforces.com/contest/798/problem/D 构造 题意:给出两个数列a,b,求选 ...

  7. Void 参数

    在C程序中如果在声明函数的时候如果没有任何参数那么需要将参数定义为void以此来限定此函数不可传递任何参数,如果不进行限定让参数表默认为空其意义是可以传递任何参数,这个问题的由来实际上是由于要兼容早期 ...

  8. [poj2417]Discrete Logging_BSGS

    Discrete Logging poj-2417 题目大意:求$a^x\equiv b(mod\qquad c)$ 注释:O(分块可过) 想法:介绍一种算法BSGS(Baby-Step Giant- ...

  9. MySQL:解决MySQL无法启动的问题

    MySQL无法启动的原因有多种,这里是我遇到的一种情况和解决方法. 起因: 最近项目需要使用MySQL,于是想在MAC上安装一个本地的数据库,但是其实忘了已经安装过一个版本了,结果发现新的服务器怎么也 ...

  10. CSS3 网格布局(grid layout)基础知识 - 隐式网格自己主动布局(grid-auto-rows/grid-auto-columns/grid-auto-flow)

    网格模板(grid-template)属性及其普通写法(longhands)定义了一个固定数量的轨道.构成显式网格. 当网格项目定位在这些界限之外.网格容器通过添加隐式网格线生成隐式网格轨道. 这些隐 ...