Spring Boot (2) Restful风格接口

时间:2023-01-03 10:11:34

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 (2) Restful风格接口

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);