作為移動端開發(fā)者來說朴上,一般情況下,我們是不需要管理后臺接口懂鸵,只需要調(diào)用就可以了偏螺;但有時候,我們想要自己來實(shí)現(xiàn)接口匆光,就得需要搭建自己的后臺接口
當(dāng)然實(shí)現(xiàn)方式有很多套像,我對Java比較熟悉,這里就說下用Java等框架來實(shí)現(xiàn)Restful接口终息。大學(xué)的時候夺巩,我們學(xué)過利用較為原始的Servelet來實(shí)現(xiàn)贞让,當(dāng)然會顯得很臃腫,寫起來也很麻煩柳譬,所以這里就利用SpringBoot框架來實(shí)現(xiàn)喳张,大量的注解會讓我們實(shí)現(xiàn)起來很方便,也省去了很多配置
這里我使用Intellij Idea編譯器來創(chuàng)建工程美澳,這里的選項(xiàng)有很多销部,現(xiàn)在一步步來創(chuàng)建工程
如果沒有Spring Initializr這個選項(xiàng),就在插件配置中安裝即可制跟,這里就不再贅述
接下來就直接下一步舅桩,現(xiàn)在我們到項(xiàng)目中的結(jié)構(gòu)看一下
重點(diǎn)來看下TestController.java這個類
package com.helang.springboot.controller;
import com.helang.springboot.bean.ApiResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class DemoController {
/**
* http://localhost:8080/doGet
* 測試GET
* 默認(rèn)方法是GET,也可以不用寫(有參數(shù)一定要對應(yīng))
* @return
*/
@RequestMapping(value = "doGet",method = RequestMethod.GET)
private ApiResult testGet(String parm1){
ApiResult apiResult = new ApiResult();
apiResult.setCode(0);
apiResult.setData("I'm a restful api for get");
apiResult.setMessage("message is ok");
return apiResult;
}
/**
* http://localhost:8080/doPost
* 測試POST
* 客戶端傳的參數(shù)一定要和下面設(shè)定的參數(shù)一一對應(yīng)
* @return
*/
@RequestMapping(value = "doPost",method = RequestMethod.POST)
private ApiResult testPost(String parm1,String parm2){
ApiResult apiResult = new ApiResult();
apiResult.setCode(-1);
apiResult.setData("I'm a restful api for post");
apiResult.setMessage("message is not ok");
return apiResult;
}
}
代碼很簡單雨膨,省去了很多配置
運(yùn)行來看下效果:
本地訪問沒有問題擂涛,結(jié)果也是JSON數(shù)據(jù)。
如果要部署到自建的Tomcat容器中也很簡單哥放,將項(xiàng)目打成.jar或者.war即可歼指,需要訪問數(shù)據(jù)庫,利用現(xiàn)有的ORM框架甥雕,也只需要配置一下就可以了
以上就是很簡單的后臺接口開發(fā)踩身,如今很多項(xiàng)目已經(jīng)開發(fā)向微服務(wù)靠攏了(或者直接利用AWS等,開發(fā)者只管自己的業(yè)務(wù)社露,其他的都是現(xiàn)成的挟阻,工作量少了很多),或者是直接node.js實(shí)現(xiàn)后臺接口峭弟,所以技術(shù)的發(fā)展很快附鸽,但是只要掌握基本的原理,一門新技術(shù)也是手到擒來
補(bǔ)一個很簡單的demo瞒瘸,我會定時更新Springboot的各種用法
https://github.com/helang1991/springboot