献给移动端的服务器搭建

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

前言:

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

1.基础框架搭建:

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

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

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

2.项目启动:

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

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

server.port: 8089
复制代码

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

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

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

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

在项目启动类 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文件目录单击右键

创建名为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的枚举类

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"; }

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




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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
1 硬件需求 1.1 基本配置 配件 数量 CPU 2核 内存 4G 硬盘 100G 1.2 最低配置 配件 数量 CPU 2核 内存 2G 硬盘 10G 2 软件需求 名称 分类 版本 Windows 操作系统 2003及以上 jdk Java虚拟机 1.5.x及以上 Tomcat Web服务器 5.x及以上 Easy do it (轻松互联网开发平台,简称轻开平台,原名WebEasy) 应用开发服务器 2014及以上 Access 数据库 97及以上 EditPlus 开发工具 2.x及以上 3 软件安装 4 发布 4.1 下载 Easy do it,轻松互联网开发平台(简称轻开平台,原名WebEasy)下载地址: CSDN下载频道:http://download.csdn.net/detail/tx18/8711175 百度云盘:http://pan.baidu.com/s/1eQElpom 官网:http://edoit.htok.net/ 最新更新的下载包:http://download.csdn.net/user/tx18 4.2 发布 复制webeasy目录到D:\下,然后进入%TOMCAT_HOME%\conf目录,用文本编辑器(如:EditPlus)打开server.xml文件,在“Host”标签下添加一“Context”标签: 保存退出并启动tomcat 5 编辑工具 轻开平台可以用任何网页或文本编辑器进行开发,我本人一直在使用EditPlus,以下推荐常用的编辑软件: • EditPlus EditPlus 是一款功能强大的文字处理软件。它可以充分的替换记事本,它也提供网页作家及程序设计师许多强悍的功能。支持 HTML、CSS、PHP、ASP、Perl、C/C++、Java、JavaScript、VBScript 等多种语法的着色显示。程序内嵌网页浏览器,其它功能还包含 FTP 功能、HTML 编辑、URL 突显、自动完成、剪贴文本、行列选择、强大的搜索与替换、多重撤销/重做、拼写检查、自定义快捷键,等等... EditPlus中文版包含在下载包中 6 开发 6.1 第一个json 新建一个扩展名json的文件,如one.json(下图) 然后录入如下内容 {"item":{ 土豆 1.24 KG T恤 68 件 可乐 2.20 瓶 书 51.24 本 @{item:name} @{item:price} @{item:unit} },"sort":@{int:@{item:getSuffix}+1} } 6.2 针对移动App(json格式)的规则及开发例子 除了基本开发标签语言及表达式(参见同一下载包中的开发手册)外,轻开平台特别针对移动App最常用的json文本格式开发的对应规则:  文件扩展名须为json(如:one.json)或用JspEasy扩展  文件内容须为闭合的json格式,静态内容则可直接书写json格式,如: {“item”: { … … },”other”:”other value” }  value属性参数表示输出不带引号的值,如: @{item:price} 输出:"pri
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值