基础部分
成都创新互联 服务项目包括新余网站建设、新余网站制作 、新余网页制作以及新余网络营销策划等。多年来,我们专注于互联网行业,利用自身积累的技术优势、行业经验、深度合作伙伴关系等,向广大中小型企业、政府机构等提供互联网行业的解决方案,新余网站推广 取得了明显的社会效益与经济效益。目前,我们服务的客户以成都为中心已经辐射到新余省份的部分城市,未来相信会继续扩大服务区域并继续获得客户的支持与信任!
1. FastJson 简介
Fastjson是一个Java库,可用于将Java对象转换为JSON表示。它也可以被用来将一个JSON字符串转换成一个等效的Java对象。在转换速度上应该是最快的,几乎成为了项目的标配(在ajax请求和接口开发时一般都会用fastjson而不再使用jackson)。
GitHub: https://github.com/alibaba/fastjson (本地下载)
特性:
在服务器 端和android客户端提供最佳性能 提供简单toJSONString()和parseObject()方法的Java对象转换为JSON,反之亦然 允许存在的无法改变的对象转换为从JSON Java泛型的广泛支持 允许自定义表示对象 支持任意复杂的对象(深继承层次结构和广泛使用泛型类型) 主要特点:
快速FAST (比其它任何基于Java的解析器和生成器更快,包括jackson) 强大(支持普通JDK类包括任意Java Bean Class、Collection、Map、Date或enum) 零依赖(没有依赖其它任何类库除了JDK) 支持注解 2. fastjson api
Fastjson API入口类是com.alibaba.fastjson.JSON,常用的序列化操作都可以在JSON类上的静态方法直接完成。
// 把JSON文本parse为JSONObject或者JSONArray
public static final Object parse(String text);
// 把JSON文本parse成JSONObject
public static final JSONObject parseObject(String text);
// 把JSON文本parse为JavaBean
public static final T parseObject(String text, Class clazz);
// 把JSON文本parse成JSONArray
public static final JSONArray parseArray(String text);
// 把JSON文本parse成JavaBean集合
public static final List parseArray(String text, Class clazz);
// 将JavaBean序列化为JSON文本
public static final String toJSONString(Object object);
// 将JavaBean序列化为带格式的JSON文本
public static final String toJSONString(Object object, boolean prettyFormat);
// 将JavaBean转换为JSONObject或者JSONArray
public static final Object toJSON(Object javaObject); JSONArray:相当于List
JSONObject:相当于Map
SerializeConfig: 是对序列化过程中一些序列化过程的特殊配置, 如对一些字段进行格式处理(日期、枚举等)
SerializeWriter:相当于StringBuffer
SerializerFeature属性 :
QuoteFieldNames 输出key时是否使用双引号,默认为true UseSingleQuotes 使用单引号而不是双引号,默认为false WriteMapNullValue 是否输出值为null的字段,默认为false WriteEnumUsingToString Enum输出name()或者original,默认为false UseISO8601DateFormat Date使用ISO8601格式输出,默认为false WriteNullListAsEmpty List字段如果为null,输出为[],而非null WriteNullStringAsEmpty 字符类型字段如果为null,输出为”“,而非null WriteNullNumberAsZero 数值字段如果为null,输出为0,而非null WriteNullBooleanAsFalse Boolean字段如果为null,输出为false,而非null SkipTransientField 如果是true,类中的Get方法对应的Field是transient,序列化时将会被忽略。默认为true SortField 按字段名称排序后输出。默认为false WriteTabAsSpecial 把\t做转义输出,默认为false 不推荐 PrettyFormat 结果是否格式化,默认为false WriteClassName 序列化时写入类型信息,默认为false。反序列化是需用到 DisableCircularReferenceDetect 消除对同一对象循环引用的问题,默认为false WriteSlashAsSpecial 对斜杠'/'进行转义 BrowserCompatible 将中文都会序列化为\uXXXX格式,字节数会多一些,但是能兼容IE 6,默认为false WriteDateUseDateFormat 全局修改日期格式,默认为false。JSON.DEFFAULT_DATE_FORMAT = “yyyy-MM-dd”;JSON.toJSONString(obj, SerializerFeature.WriteDateUseDateFormat); DisableCheckSpecialChar 一个对象的字符串属性中如果有特殊字符如双引号,将会在转成json时带有反斜杠转移符。如果不需要转义,可以使用这个属性。默认为false NotWriteRootClassName 含义 BeanToArray 将对象转为array输出 WriteNonStringKeyAsString NotWriteDefaultValue BrowserSecure IgnoreNonFieldGetter WriteEnumUsingName 实战部分
1、pom.xml 中引入spring mvc、 fastjson 依赖
4.0.0
com.mengdee
platform-springmvc-webapp
war
0.0.1-SNAPSHOT
platform-springmvc-webapp Maven Webapp
http://maven.apache.org
UTF-8
3.8.1
2.5
1.2
4.2.3.RELEASE
1.2.32
junit
junit
3.8.1
test
javax.servlet
jstl
${jstl.version}
org.springframework
spring-webmvc
${spring.version}
org.springframework
spring-core
${spring.version}
org.springframework
spring-context
${spring.version}
org.springframework
spring-context-support
${spring.version}
org.springframework
spring-jdbc
${spring.version}
com.alibaba
fastjson
${fastjson.version}
aliyun
aliyun
http://maven.aliyun.com/nexus/content/groups/public
platform-springmvc-webapp
2、 配置web.xml
Archetype Created Web Application
contextConfigLocation
classpath:conf/spring/spring-*.xml
Spring监听器
org.springframework.web.context.ContextLoaderListener
spring-mvc
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
/WEB-INF/spring-servlet.xml
1
spring-mvc
/
characterEncodingFilter
org.springframework.web.filter.CharacterEncodingFilter
encoding
UTF-8
forceEncoding
true
characterEncodingFilter
/*
/index.jsp
404
/index.jsp
3、 配置spring-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
text/html;charset=UTF-8
application/json
QuoteFieldNames
WriteMapNullValue
4、Java
Education:学历(枚举类)
package com.mengdee.manage.entity;
import java.util.HashMap;
import java.util.Map;
/**
* 学历
* @author Administrator
*
*/
public enum Education {
KINDERGARTEN("幼儿园", 1),
ELEMENTARY("小学", 2),
JUNIOR_MIDDLE("初级中学", 3),
SENIOR_MIDDLE("高级中学", 4),
UNIVERSITY("大学", 5),
COLLEGE("学院", 6);
private static final Map EDUCATION_MAP = new HashMap();
static {
for (Education education : Education.values()) {
EDUCATION_MAP.put(education.getIndex(), education);
}
}
private String text;
private int index;
private Education(String text, int index) {
this.text = text;
this.index = index;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
public static Education getEnum(Integer index) {
return EDUCATION_MAP.get(index);
}
} Person:
package com.mengdee.manage.entity;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import com.alibaba.fastjson.annotation.JSONField;
public class Person {
private Long id;
private String name;
private byte gender; // 性别 1:男 2:女
private short age; // 年龄
private long salary; // 薪水
private double weight; // 体重
private char level; // 评级
private boolean adult; // 是否成年人
private Date birthday; // 生日
private Education education;// 学历
private String[] hobbies; // 爱好
private List dogs; // 宠物狗
private Map address; // 住址
// 使用注解控制是否要序列化
@JSONField(serialize = false)
private List obj = new ArrayList<>();
public Person() {
}
public Person(Long id, String name, byte gender, short age, long salary, double weight, char level, boolean adult,
Date birthday, String[] hobbies, List dogs, Map address) {
super();
this.id = id;
this.name = name;
this.gender = gender;
this.age = age;
this.salary = salary;
this.weight = weight;
this.level = level;
this.adult = adult;
this.birthday = birthday;
this.hobbies = hobbies;
this.dogs = dogs;
this.address = address;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public byte getGender() {
return gender;
}
public void setGender(byte gender) {
this.gender = gender;
}
public short getAge() {
return age;
}
public void setAge(short age) {
this.age = age;
}
public long getSalary() {
return salary;
}
public void setSalary(long salary) {
this.salary = salary;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
public char getLevel() {
return level;
}
public void setLevel(char level) {
this.level = level;
}
public boolean isAdult() {
return adult;
}
public void setAdult(boolean adult) {
this.adult = adult;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
// 处理序列化枚举类型,默认的值是序列化枚举值字符串,而不是枚举绑定的索引或者文本
@JSONField(name = "edu")
public int getEdu(){
return education.getIndex();
}
@JSONField(name = "edu")
public void setEdu(int index){
this.education = Education.getEnum(index);
}
@JSONField(serialize = false)
public Education getEducation() {
return education;
}
@JSONField(serialize = false)
public void setEducation(Education education) {
this.education = education;
}
public String[] getHobbies() {
return hobbies;
}
public void setHobbies(String[] hobbies) {
this.hobbies = hobbies;
}
public List getDogs() {
return dogs;
}
public void setDogs(List dogs) {
this.dogs = dogs;
}
public Map getAddress() {
return address;
}
public void setAddress(Map address) {
this.address = address;
}
}TestController
package com.mengdee.manage.controller;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.serializer.DoubleSerializer;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SimpleDateFormatSerializer;
import com.mengdee.manage.entity.Address;
import com.mengdee.manage.entity.Dog;
import com.mengdee.manage.entity.Education;
import com.mengdee.manage.entity.Person;
@Controller
public class TestController {
private static SerializeConfig serializeConfig = new SerializeConfig();
static {
serializeConfig.put(Date.class, new SimpleDateFormatSerializer("yyyy-MM-dd HH:mm:ss"));
serializeConfig.put(Double.class, new DoubleSerializer(new DecimalFormat("0.00")));
}
@RequestMapping("/index")
public String index(){
return "index";
}
// javabean to object
@RequestMapping("/json")
@ResponseBody
public Object json(){
Person person = new Person();
person.setId(1L);
person.setName("mengdee");
person.setAge((short) 18);
//
/*
{
"birthday": null,
"weight": 0,
"dogs": null,
"adult": false,
"hobbies": null,
"education": null,
"id": 1,
"level": "",
"address": null,
"age": 18,
"name": "mengdee",
"gender": 0,
"salary": 0
}
*/
Object personJson = JSON.toJSON(person);
return personJson;
}
// javabean to string
@RequestMapping("/json2")
@ResponseBody
public String json2(){
Person person = new Person();
person.setId(1L);
person.setName("mengdee");
person.setAge((short) 18);
// 使用该方式值为null的经测试不出来,已经配置了WriteMapNullValue
// "{"adult":false,"age":18,"gender":0,"id":1,"level":"","name":"mengdee","salary":0,"weight":0.0}"
String jsonString = JSON.toJSONString(person);
return jsonString;
}
@RequestMapping("/json3")
@ResponseBody
public Object json3(){
Person person = new Person();
person.setId(1L);
person.setName("mengdee");
person.setAge((short) 18);
person.setBirthday(new Date());
Object personJson = JSON.toJSON(person); // JSON.toJSON(person)默认是毫秒数"birthday":1495073314780,
// 使用serializeConfig序列号配置对日期格式化
// "{"birthday":"2017-05-18 10:19:55","weight":0.0,"adult":false,"id":1,"level":"","age":18,"name":"mengdee","gender":0,"salary":0}"
String jsonString = JSON.toJSONString(personJson, serializeConfig);
return jsonString;
}
@RequestMapping("/json4")
@ResponseBody
public Object json4(){
Person person = new Person();
person.setId(1L);
person.setName("mengdee");
person.setAge((short) 18);
person.setBirthday(new Date());
person.setEducation(Education.UNIVERSITY); // 枚举
String[] hobbies = {"读书", "旅游"};
person.setHobbies(hobbies);
Dog dog1 = new Dog(1L, "dog1", (short)1);
Dog dog2 = new Dog(2L, "dog2", (short)2);
List dogs = new ArrayList<>();
dogs.add(dog1);
dogs.add(dog2);
person.setDogs(dogs);
Address address1 = new Address(1l, "上海浦东新区");
Address address2 = new Address(2l, "上海宝山区");
Map addressMap = new HashMap<>();
addressMap.put(address1.getId() + "", address1);
addressMap.put(address2.getId() + "", address2);
person.setAddress(addressMap);
Object personJson = JSON.toJSON(person);
return personJson;
}
@RequestMapping("/json5")
@ResponseBody
public String json5(){
Dog dog1 = new Dog(1L, "dog1", (short)1);
Dog dog2 = new Dog(2L, "dog2", (short)2);
List dogs = new ArrayList<>();
dogs.add(dog1);
dogs.add(dog2);
// List -> JSON
String jsonString = JSON.toJSONString(dogs, false);
System.out.println(jsonString);
// JSON -> List
List parseArray = JSON.parseArray(jsonString, Dog.class);
for (Dog dog : parseArray) {
System.out.println(dog);
}
Map map = new HashMap();
map.put("dog1",new Dog(1L, "dog1", (short)1));
map.put("dog2",new Dog(2L, "dog2", (short)2));
map.put("dog3",new Dog(3L, "dog3", (short)3));
// Map -> JSON
String mapJsonString = JSON.toJSONString(map,true);
System.out.println(mapJsonString);
// JSON -> Map
@SuppressWarnings("unchecked")
Map map1 = (Map)JSON.parse(mapJsonString);
for (String key : map1.keySet()) {
System.out.println(key + ":" + map1.get(key));
}
// Array -> JSON
String[] hobbies = {"a","b","c"};
String hobbiesString = JSON.toJSONString(hobbies,true);
System.out.println(hobbies);
// JSON -> Array
JSONArray jsonArray = JSON.parseArray(hobbiesString);
for (Object o : jsonArray) {
System.out.println(o);
}
System.out.println(jsonArray);
return jsonString;
}
} Swagger集成
第一步:引入相关依赖
io.springfox
springfox-swagger2
2.6.1
compile
com.fasterxml.jackson.core
jackson-databind
2.6.6
第二步:Swagger信息配置
SwaggerConfig.java
@Configuration
@EnableWebMvc
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket customDocket() {
Docket docket = new Docket(DocumentationType.SWAGGER_2);
docket.apiInfo(apiInfo());
docket.select().apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class));
docket.select().paths(PathSelectors.regex("/api/.*")).build();
return docket;
}
private ApiInfo apiInfo() {
Contact contact = new Contact("小明", "http://www.baidu.com", "baidu@163.com");
return new ApiInfo("API接口", //大标题 title
"API接口", //小标题
"0.0.1", //版本
"www.baidu.com",//termsOfServiceUrl
contact,//作者
"API接口",//链接显示文字
"http://www.baidu.com"//网站链接
);
}
} 注意: 因SwaggerConfig这个类配置了注解,所以这个类必须被扫描到,即该类一定包含在context:component-scan中。
第三步:在类、方法、参数上使用注解
@Controller
@RequestMapping("/api/v1")
@Api(description = "API接口")
public class ApiController {
@ApiOperation(value = "用户登录", notes = "用户登录接口")
@ApiResponses({
@ApiResponse(code = 0, message = "success"),
@ApiResponse(code = 10001, message = "用户名错误", response = IllegalArgumentException.class),
@ApiResponse(code = 10002, message = "密码错误")
})
@RequestMapping(value = "/user/login", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8;"})
@ResponseBody
public String login(@ApiParam(name = "username", value = "用户名", required = true) @RequestParam String username,
@ApiParam(name = "password", value = "密码", required = true) @RequestParam String password){
return "{'username':'" + username + "', 'password':'" + password + "'}";
}
@ApiImplicitParams({
@ApiImplicitParam(paramType = "header", name = "phone", dataType = "String", required = true, value = "手机号"),
@ApiImplicitParam(paramType = "query", name = "nickname", dataType = "String", required = true, value = "nickname", defaultValue = "双击666"),
@ApiImplicitParam(paramType = "path", name = "platform", dataType = "String", required = true, value = "平台", defaultValue = "PC"),
@ApiImplicitParam(paramType = "body", name = "password", dataType = "String", required = true, value = "密码")
})
@RequestMapping(value = "/{platform}/user/regist", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8;"})
@ResponseBody
public String regist(@RequestHeader String phone, @RequestParam String nickname, @PathVariable String platform, @RequestBody String password){
return "{'username':'" + phone + "', 'nickname':'" + nickname + "', 'platform': '" + platform + "', 'password':'"+password+"'}";
}
@RequestMapping(value = "/user/list", method = RequestMethod.GET, produces = {"application/json;charset=UTF-8;"})
@ResponseBody
public String getUserList(Pager pager){
return "[{'id': "+pager.getPage()+", 'username': 'zhangsan"+pager.getSize()+"'}]";
}
@RequestMapping("/docs")
@ApiIgnore
public String test(){
return "api-docs";
}
} Pager
public class Pager {
@ApiModelProperty(value = "页码", required = true)
private int page;
@ApiModelProperty(value = "每页条数", required = true)
private int size;
public Pager() {
}
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
} 常用注解:
@Api(description = “接口类的描述”) @ApiOperation(value = “接口方法的名称”, notes = “备注说明”) @ApiParam(name = “参数名称”, value = “备注说明”, required = 是否必须):标注在方法的参数上 用于描述参数的名称、备注、是否必须等信息 @ApiImplicitParam(paramType = “query”, name = “password”, dataType = “String”, required = true, value = “密码”, defaultValue = “123456”)用于描述方法的参数,标注在方法上,和@ApiParam功能一样,只是标注的位置不同而已 .paramType:参数类型,即参数放在哪个地方 . header–>请求参数的获取:@RequestHeader,参数放在请求头 . query–>请求参数的获取:@RequestParam,参数追加在url后面 . path(用于restful接口)–>请求参数的获取:@PathVariable . body 使用@RequestBody接收数据 POST有效,参数放在请求体中 . form .name:参数名 .dataType:参数的数据类型 .required:参数是否必须传 .value:参数的描述 .defaultValue:参数的默认值 @ApiImplicitParams: 用于包含多个@ApiImplicitParam @ApiResponse(code = 0, message = “success”), .code:响应码,例如400 .message:信息,一般是对code的描述 .response:抛出异常的类 @ApiModel:描述一个Model的信息(这种一般用在post创建的时候,使用@RequestBody这样的场景,请求参数无法使用@ApiImplicitParam注解进行描述的时候) .@ApiModelProperty:描述一个model的属性 . position 允许在模型中显式地排序属性。 . value 参数名称 . required 是否必须 boolean . hidden 是否隐藏 boolean . allowableValues = “range[0, 1]” 一般用于指定参数的合法值 @ApiIgnore:用于或略该接口,不生成该接口的文档 第四步:访问/v2/api-docs
在浏览器上访问http://localhost:8080/工程名称/v2/api-docs 如果有json内容,证明正常
第五步:下载swagger-ui
从github上下载https://github.com/swagger-api/swagger-ui,注意这里要选择下载v2.2.10(https://github.com/swagger-api/swagger-ui/tree/v2.2.10 (本地下载)),大于这个版本的集成方式不一样。
集成方法:将v2.2.10下的dist目录下的所有文件放到自己工程中静态文件中,并使用下面代码覆盖掉index.html中的脚本部分
第六步:访问上面修改的那个index.html http://localhost:8080/工程名称/static/third-party/swagger-ui/index.html
注意: 因要访问静态资源,使用springmvc请确保静态资源能够被访问到,如果不能访问请做如下配置:
1、 在Spring的配置文件中增加默认的servlet处理器
2、 在web.xml中增加要过滤的静态文件
default
*.js
*.css
/assets/*"
/images/*
示例项目代码结构:
完整示例Demo下载地址: http://xiazai.jb51.net/201804/yuanma/platform-springmvc-webapp(jb51.net).rar
其他
关于spring-servlet.xml 和 applicationContext.xml
SpringMVC 提供了两种配置文件 spring-servlet.xml 、 applicationContext.xml spring-servlet.xml 是Controller级别的,作用范围是控制层,默认的名字是【servlet-name】-servlet.xml 默认是放在WEB-INF/目录下,SpringMVC会自动加载,也可以在web.xml中配置它的位置
spring-mvc
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
/WEB-INF/spring-servlet.xml
1
一般在spring-servlet.xml中配置一些和控制器相关的配置,如视图解析、静态资源文件的映射、返回结果的解析等
视图解析
org.springframework.web.servlet.view.UrlBasedViewResolver tiles3: org.springframework.web.servlet.view.tiles3.TilesConfigurer springMVC: org.springframework.web.servlet.view.InternalResourceViewResolver, shiro: org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor 上传 org.springframework.web.multipart.commons.CommonsMultipartResolver, 静态资源映射
org.springframework.context.support.ResourceBundleMessageSource
返回结果的解析
FastJson: com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter 3、applicationContext.xml 是系统级别的配置,作用范围是系统上下文,它的初始化需要放到 web.xml 中的context-param中配置
contextConfigLocation
classpath:conf/spring/spring-*.xml
4、 关于applicationContxt.xml,一般是按照功能拆成多个配置文件如:
- applicationContxt-base.xml // 基础 - applicationContxt-redis.xml // redis相关配置 - applicationContxt-shiro.xml // shiro 相关配置 - applicationContxt-dao.xml // 数据库相关配置 - applicationContxt-xxx.xml // xxx 总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对创新互联的支持。
本文标题:SpringMVC+FastJson+Swagger集成的完整实例教程
路径分享:http://shouzuofang.com/article/iigepo.html
免费获取网站建设与品牌策划方案报价
*主要业务范围包括:高端网站建设, 集团网站建设(网站建设网站制作)找网站建设公司就上四川攀枝花网站建设。