JavaLib

演示一下JavaLib框架如何使用?我們從服務(wù)端說起

引入

目前JavaLib托管到JitPack。支持gradle、maven、sbtleiningen。我在寫Java項(xiàng)目時(shí),比較喜歡Maven,寫Android時(shí),會(huì)用Gradle,其他沒用過。下面就以Maven為例,演示一下如何添加依賴。

1、需要添加倉庫

<repositories>
    <repository>
        <id>jitpack.io</id>
        <url>https://jitpack.io</url>
    </repository>
</repositories>

2、添加依賴

<dependencies>
    <dependency>
        <groupId>com.github.fengwenyi</groupId>
        <artifactId>JavaLib</artifactId>
        <version>0.0.4</version>
    </dependency>
</dependencies>

如此,pom.xml文件結(jié)構(gòu)大致是這樣:

<?xml version="1.0" encoding="UTF-8"?>
<project ...>
    ...
    <dependencies>
        <dependency>
            <groupId>com.github.fengwenyi</groupId>
            <artifactId>JavaLib</artifactId>
            <version>0.0.4</version>
        </dependency>
        ...
    </dependencies>
    <repositories>
        <repository>
            <id>jitpack.io</id>
            <url>https://jitpack.io</url>
        </repository>
        ...
    </repositories>
    ...
</project>

注:... 表示,這里可能還有其他更多內(nèi)容。

Return

現(xiàn)在數(shù)據(jù)交換大多依賴接口的形式,而數(shù)據(jù)大多會(huì)Json格式。在JavaLib中默認(rèn)引入Gson(以后可能會(huì)默認(rèn)用Fastjson)。

新建一個(gè)枚舉類并實(shí)現(xiàn)IReturnCode:

public enum ReturnCode implements IReturnCode {
    ;
    private int code;
    private String msg;
    ReturnCode() {
    }
    ReturnCode(int code, String msg) {
        this.code = code;
        this.msg = msg;
    }
    @Override
    public int getCode() {
        return code;
    }
    @Override
    public String getMsg() {
        return msg;
    }
}

以登錄為例寫一個(gè)Contoller:

@RestController
@RequestMapping("/user")
public class UserController {
    // login
    @PostMapping("/login")
    public String login(@RequestParam("username") String username,
                        @RequestParam("password") String password) {
        Result result = new Result();
        if (StringUtil.isNullStr(username)
                || StringUtil.isNullStr(password)) {
            result.setResult(ReturnCode.ERROR_DATA_NULL);
        } else {
            if ("user".equals(username)) {
                if ("pwd".equals(password)) {
                    // 驗(yàn)證成功
                    /*
                    // 無數(shù)據(jù)返回
                    result.setResult(ReturnCode.SUCCESS);
                    */
                    // 要返回一些數(shù)據(jù)
                    Map<String, Long> map = new HashMap<>();
                    map.put("loginTime", System.currentTimeMillis());
                    result.setData(ReturnCode.SUCCESS, map);
                } else {
                    result.setResult(ReturnCode.ERROR_USER_PASSWORD_INCORRECT);
                }
            } else {
                result.setResult(ReturnCode.ERROR_USER_USERNAME_INCORRECT);
            }
        }
        return new Gson().toJson(result);
    }
}

一些返回碼:

// error
ERROR_DATA_NULL(1001, "數(shù)據(jù)不能為空"),
//----
ERROR_USER_USERNAME_INCORRECT(1101, "用戶名不正確"),
ERROR_USER_PASSWORD_INCORRECT(1102, "密碼不正確"),
// success
SUCCESS(0, "Sucess")
;

注:這里的代碼只是測試,實(shí)際開發(fā)的驗(yàn)證方式可能更復(fù)雜。

測試一下:

{
    "code":1101,
    "msg":"用戶名不正確"
}
{
    "code":0,
    "msg":"Sucess",
    "data":{
        "loginTime":1516166553865
    }
}

當(dāng)code=0時(shí),才會(huì)有數(shù)據(jù)返回。

Get/Post/Put/Delete

先來看web端的代碼:

// get
@GetMapping("/get")
public String get(@RequestParam("data") String data) {
    return data;
}
// post
@PostMapping("/post")
public String post(@RequestParam("data") String data) {
    return data;
}
@PostMapping("/post-json")
public String postJson(HttpServletRequest request) throws IOException {
    return RequestUtil.getPostData(request);
}
// put
@PutMapping("/put/{id}")
public String put(@PathVariable("id") int id) {
    return String.valueOf(id);
}
// delete
@DeleteMapping("/delete/{id}")
public String delete(@PathVariable("id") int id) {
    return String.valueOf(id);
}

在看些Get/Post/Put/Delete提交測試代碼:

// Get方式提交
private static void get() throws IOException {
    // 提交方式一
    String url = host + "/get";
    Map<String, String> map = new HashMap<>();
    map.put("data", "data-get-1");
    String rs = NetDataUtil.get(url, null, map);
    System.out.println("Get=>" + rs);
    /*
    // 提交方式二
    String url = host + "/get?data=data-get-2";
    String rs = NetDataUtil.get(url, null, null);
    System.out.println(rs);
    */
}
// Post方式提交(表單或json格式數(shù)據(jù))
private static void post() throws IOException {
    String url = host + "/post";
    Map<String, String> map = new HashMap<>();
    map.put("data", "data-表單格式數(shù)據(jù)");
    String rs = NetDataUtil.post(url, null, map);
    System.out.println("Post=>" + rs);
    // json
    String urlJson = host + "/post-json";
    Map<String, String> mapJson = new HashMap<>();
    mapJson.put("data", "data-Json-格式數(shù)據(jù)");
    Map<String, String> header = new HashMap<>();
    header.put("Content-Type", "application/json;charset=utf-8");
    header.put("Accept", "application/json;charset=utf-8");
    String rsJson = NetDataUtil.post(urlJson, header, mapJson);
    System.out.println("Post json =>" + rsJson);
}
// Put方式提交
private static void put() throws IOException {
    String url = host + "/put/1";
    String rs = NetDataUtil.put(url, null, null);
    System.out.println("Put=>" + rs);
}
// Delete方式提交
private static void delete() throws IOException {
    String url = host + "/delete/2";
    Map<String, String> header = new HashMap<>();
    header.put("Content-Type", "application/json;charset=utf-8");
    header.put("Accept", "application/json;charset=utf-8");
    String rs = NetDataUtil.delete(url, header, null);
    System.out.println("Delete=>" + rs);
}

測試代碼:

private static String host = "http://localhost:8080/user";

public static void main(String[] args) {
    try {
        get();
        post();
        put();
        delete();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

測試結(jié)果:


控制臺(tái)get-post-put-delete測試結(jié)果
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容