献给移动端的服务器搭建

移动端进阶之选:移动端开发者也能轻松搭建的服务器

前言:

笔者最近收到了挺多客户端的留言,客户端在等待后台接口的时候遥遥无期,其实客户端只需要几步就能简单搭建一个后台,用于调试接口的,本期就简单搭建一个后台,用于客户端调试接口。相关代码已放于 github

1.基础框架搭建:

使用开发工具IDEA,新建一个spring-boot项目:

IDEA下载地址下载Ultimate版本
JDK下载地址 下载对应的JDK版本即可

image
image
image
image
image

点击finish后,一个sping-boot的基础项目已经创建好了。

image

2.项目启动:

TestApplication直接run就能启动项目了的

image

application.properties这个是项目的一些配置,举例一下默认是8080端口,我们如果想改下端口的话,就可以在配置增加

server.port: 8089

这样子启动的时候端口就更改了的

image

项目的请求地址为:http://本机IP:8089

3.一个简单的接口开发:

如图创建对应的目录以及创建对应的实体类:

image

在项目启动类 TestApplication设置HttpMessageConverters的JSON格式输出为fastjson:

package com.example.test;

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.http.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.http.MediaType;

import java.util.ArrayList;
import java.util.List;

@SpringBootApplication
public class TestApplication {

    /**
     * JSON格式输出使用fastjson
     * @return
     */
    @Bean
    public HttpMessageConverters fastJsonHttpMessageConverters() {
        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat,SerializerFeature.DisableCircularReferenceDetect,SerializerFeature.WriteNullStringAsEmpty);
        //时间格式化
        fastJsonConfig.setDateFormat("yyyyMMddHHmmss");
        fastConverter.setFastJsonConfig(fastJsonConfig);
        //由于新版本fastjson设置了MediaType为'/',所以需要手动加入所需的MediaType
        List<MediaType> supportedMediaTypes = new ArrayList<>();
        //增加JSON的MediaType
        supportedMediaTypes.add(MediaType.APPLICATION_JSON);
        supportedMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
        //下面的都是扩展的
        supportedMediaTypes.add(MediaType.APPLICATION_ATOM_XML);
        supportedMediaTypes.add(MediaType.APPLICATION_FORM_URLENCODED);
        supportedMediaTypes.add(MediaType.APPLICATION_OCTET_STREAM);
        supportedMediaTypes.add(MediaType.APPLICATION_PDF);
        supportedMediaTypes.add(MediaType.APPLICATION_RSS_XML);
        supportedMediaTypes.add(MediaType.APPLICATION_XHTML_XML);
        supportedMediaTypes.add(MediaType.APPLICATION_XML);
        supportedMediaTypes.add(MediaType.IMAGE_GIF);
        supportedMediaTypes.add(MediaType.IMAGE_JPEG);
        supportedMediaTypes.add(MediaType.IMAGE_PNG);
        supportedMediaTypes.add(MediaType.TEXT_EVENT_STREAM);
        supportedMediaTypes.add(MediaType.TEXT_HTML);
        supportedMediaTypes.add(MediaType.TEXT_MARKDOWN);
        supportedMediaTypes.add(MediaType.TEXT_PLAIN);
        supportedMediaTypes.add(MediaType.TEXT_XML);
        fastConverter.setSupportedMediaTypes(supportedMediaTypes);
        fastConverter.setFastJsonConfig(fastJsonConfig);
        //将fastjson添加到视图消息转换器列表内
        return new HttpMessageConverters(fastConverter);
    }

    public static void main(String[] args) {
        SpringApplication.run(TestApplication.class, args);
    }
}

pom.xml里面的dependencies增加如下配置:

<dependency>
   <groupId>com.alibaba</groupId>
   <artifactId>fastjson</artifactId>
   <version>1.2.47</version>
</dependency>

创建响应的基础DTO(entity目录):

在entity文件目录单击右键
image

创建名为ResponseDTO的实体类并且实现序列化(Serializable 可以使你将一个对象的状态写入一个Byte 流里(序列化),并且可以从其它地方把该Byte 流里的数据读出来(反序列化))

package com.example.test.entity;

import com.example.test.enums.ResponseEnum;

import java.io.Serializable;

/**
 * @author Dwyane.
 * @date 2018-11-12
 */
public class ResponseDTO<T> implements Serializable {
    private static final long serialVersionUID = -4109110629830724000L;
    /**
     * 响应code
     */
    private String responseCode;
    /**
     * 响应描述
     */
    private String responseDesc;
    /**
     * 响应的内容
     */
    private T data;

    private ResponseDTO() {
    }

    public ResponseDTO(ResponseEnum responseEnum) {
        this(responseEnum, null);

    }

    public ResponseDTO(String responseCode, String responseDesc) {
        this.responseCode = responseCode;
        this.responseDesc = responseDesc;
    }

    public ResponseDTO(T data, ResponseEnum responseEnum) {
        this(responseEnum);
        this.data = data;
    }

    public ResponseDTO(T data, String responseCode, String responseDesc) {
        this.responseCode = responseCode;
        this.responseDesc = responseDesc;
        this.data = data;
    }

    public ResponseDTO(ResponseEnum responseEnum, String extend) {
        if (responseEnum != null) {
            this.responseCode = responseEnum.getResponseCode();
            this.responseDesc = responseEnum.getResponseDesc() + (extend == null ? "" : "(" + extend + ")");
        }
    }

    public static <T> ResponseDTO<T> buildSuccess(T data) {
        return new ResponseDTO<>(data, ResponseEnum.SUCCESS);
    }

    public static <T> ResponseDTO<T> buildSuccess() {
        return new ResponseDTO<>(ResponseEnum.SUCCESS);
    }

    public static <T> ResponseDTO<T> buildFail() {
        return new ResponseDTO<>(ResponseEnum.FAIL);
    }

    public static <T> ResponseDTO<T> buildError() {
        return new ResponseDTO<>(ResponseEnum.ERROR);
    }

    public static <T> ResponseDTO<T> buildEnum(T data, ResponseEnum responseEnum) {
        return new ResponseDTO<>(data, responseEnum);
    }

    public static <T> ResponseDTO<T> buildEnum(ResponseEnum responseEnum) {
        return new ResponseDTO<>(responseEnum);
    }

    public String getResponseCode() {
        return this.responseCode;
    }

    public void setResponseCode(String responseCode) {
        this.responseCode = responseCode;
    }

    public String getResponseDesc() {
        return this.responseDesc;
    }

    public void setResponseDesc(String responseDesc) {
        this.responseDesc = responseDesc;
    }

    public T getData() {
        return this.data;
    }

    public void setData(T date) {
        this.data = date;
    }
}

创建响应的基础枚举(enums目录):

在enums文件目录单击右键创建class时选择Enum的枚举类

image
package com.example.test.enums;

/**
 * @author Dwyane.
 * @date 2018-11-12
 */
public enum ResponseEnum {

    SUCCESS("0000","成功"),
    ERROR("9999","服务器异常"),
    FAIL("9998","失败"),

    ;
    /**
     * 返回代码
     */
    public String responseCode;
    /**
     * 返回描述
     */
    public String responseDesc;

    ResponseEnum(String responseCode, String responseDesc) {
        this.responseCode = responseCode;
        this.responseDesc = responseDesc;
    }

    /**
     * 获取  返回代码
     *
     * @return 返回代码
     */
    public String getResponseCode() {
        return this.responseCode;
    }

    /**
     * 获取  返回描述
     *
     * @return 返回描述
     */
    public String getResponseDesc() {
        return this.responseDesc;
    }

}

创建请求的实体类和响应的实体类(entity目录下的member目录):

package com.example.test.entity.member;

import javax.validation.constraints.NotNull;

/**
 * @author Dwyane.
 * @date 2018-11-9
 */
public class LoginRequestDTO {

    @NotNull
    private String mobile;

    @NotNull
    private String pwd;

    public String getMobile() {
        return mobile;
    }

    public void setMobile(String mobile) {
        this.mobile = mobile;
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }
}
package com.example.test.entity.member;

/**
 * @author Dwyane.
 * @date 2018-11-9
 */
public class LoginResponseDTO {

    private String mobile;

    private String name;

    public String getMobile() {
        return mobile;
    }

    public void setMobile(String mobile) {
        this.mobile = mobile;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

创建一个controller(controller目录):

package com.example.test.controller;

import com.example.test.entity.ResponseDTO;
import com.example.test.entity.member.LoginRequestDTO;
import com.example.test.entity.member.LoginResponseDTO;
import com.example.test.enums.ResponseEnum;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

/**
 * @author Dwyane.
 * @date 2018-11-12
 */
@RestController
@RequestMapping("/member")
public class MemberController {

    @PostMapping("/login")
    public ResponseDTO<LoginResponseDTO> login(@Valid @RequestBody LoginRequestDTO requestDTO) throws Exception{
        //todo 校验账号密码

        //校验好了,返回用户信息给到客户端
        LoginResponseDTO response = new LoginResponseDTO();
        response.setMobile(requestDTO.getMobile());
        response.setName("test");
        return new ResponseDTO<>(response, ResponseEnum.SUCCESS);
    }

}

4.test接口调试:

在test目录下创建一个简单的调试类:

package com.example.test;

import com.example.test.entity.member.LoginRequestDTO;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class TestApplicationTests {

    @Autowired
    protected TestRestTemplate restTemplate;

    /**
     * 登录单元测试
     *
     * @throws Exception
     */
    @Test
    public void login() throws Exception {
        LoginRequestDTO requestDTO = new LoginRequestDTO();
        requestDTO.setMobile("12345678910");
        requestDTO.setPwd("123");
        HttpEntity<LoginRequestDTO> formEntity = new HttpEntity<>(requestDTO, new HttpHeaders());
        ResponseEntity<String> exchange = restTemplate.exchange("/member/login",
                HttpMethod.POST, formEntity, String.class);
        System.err.println(exchange.getBody());
    }

}

直接单击右键测试类run即可:

{"responseDesc":"成功","data":{"mobile":"12345678910","name":"test"},"responseCode":"0000"}

这样一个简单的接口调用项目已经完成了。

iOS 开发者也可以用以下 swift 代码请求接口(安卓请求也简单,在此不予列出)

// 输入自己电脑连接的ip , 我的是以下ip ,其中 8089 是端口号
var urlStr = "http://192.168.1.113:8089/member/login"
var url:NSURL! = NSURL(string: urlStr)
let request:NSMutableURLRequest = NSMutableURLRequest(url: url as URL)

//设置为POST请求
request.httpMethod = "POST"
request.setValue("text/html", forHTTPHeaderField: "Content-Type")

//设置参数
var params = "{'mobile':122, 'pwd':112}"
let data = params.data(using: .utf8)
request.httpBody = data

//默认session配置
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
//发起请求
let dataTask = session.dataTask(with: request as URLRequest) { (data, response, error) in
    // let str:String! = String(data: data!, encoding: NSUTF8StringEncoding)
    // print("str:/(str)")
    //转Json
    let jsonData:NSDictionary = try! JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! NSDictionary
    print(jsonData)
}

//请求开始
dataTask.resume()

得出如下结果:

{
data = {
mobile = 122;
name = test;
};
responseCode = 0000;
responseDesc = "\U6210\U529f";
}

至此,一个完整的、简单的后台搭建完成,客户端的朋友们,是不是觉得很简单? 如有疑问,欢迎留言,笔者第一时间回复,谢谢关注!




欢迎关注公众号「程序员大咖秀」

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 157,298评论 4 360
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,701评论 1 290
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 107,078评论 0 237
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,687评论 0 202
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,018评论 3 286
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,410评论 1 211
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,729评论 2 310
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,412评论 0 194
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,124评论 1 239
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,379评论 2 242
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,903评论 1 257
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,268评论 2 251
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,894评论 3 233
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,014评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,770评论 0 192
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,435评论 2 269
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,312评论 2 260

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 170,544评论 25 707
  • 1、通过CocoaPods安装项目名称项目信息 AFNetworking网络请求组件 FMDB本地数据库组件 SD...
    X先生_未知数的X阅读 15,934评论 3 118
  • 用两张图告诉你,为什么你的 App 会卡顿? - Android - 掘金 Cover 有什么料? 从这篇文章中你...
    hw1212阅读 12,461评论 2 59
  • 文/脏辫姑娘 来到印尼已经好几个星期了,思绪万千吧,有时候觉得自己是穿越时空来到这里的。 我把这十个月当成是上天赐...
    脏辫姑娘阅读 367评论 0 3
  • 文/蓝籽 图/网络 诗歌作为一种文学体裁,也是一种表达情感与美感、体现想象与现实的艺术形式。在这里,笔者将从《诗经...
    蓝籽阅读 940评论 0 2