目標:
-
項目搭建
-
接口編寫
-
跨域實現
-
服務打包
-
服務部署
選擇創建一個springboot項目:
此處若沒有Spring Initializr選項請參考:https://www.cnblogs.com/jtaosblog/p/13114601.html
輸入項目信息:
選擇spring web:
然后next->finish項目創建完成。
2. 接口編寫
項目結構:
編寫 TestController
package com.hlzf.webapi.controller; import org.springframework.web.bind.annotation.*; @RestController public class TestController { /** 無參數接口 */ @CrossOrigin @RequestMapping(value = "/hlzfwebapi/hello", method = RequestMethod.GET) public String hello() { return "hello Spring boot"; } /** 有參數接口 */ @CrossOrigin @RequestMapping(value = "/hlzfwebapi/gethello", method = RequestMethod.GET) public String getHello(@RequestParam(value = "hello") String hello) { System.out.println("getHello =" + hello); String path = System.getProperties().getProperty("server.path"); System.out.println("path =" + path); return "hello = " + hello; } /** 有參數有默認值接口 */ @CrossOrigin @RequestMapping(value = "/hlzfwebapi/gethellodefault", method = RequestMethod.GET) public String getHelloWorldDefault(@RequestParam(value = "hello", defaultValue = "my is defaultValue") String hello) { return "hello = " + hello; } }
啟動服務,在ResourceApplication類上右鍵啟動
服務啟動正常:
使用PostMan進行測試:
@CrossOrigin @RequestMapping(value = "/hlzfwebapi/hello", method = RequestMethod.GET) public String hello() { return "hello Spring boot"; }
對一系列接口配置,在類上加注解,對此類的所有接口有效
@CrossOrigin @RestController public class TestController { //... }
如果想添加全局配置,則需要添加一個配置類
@Configuration public class WebMvcConfig extends WebMvcConfigurerAdapter { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("*") .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE") .maxAge(3600) .allowCredentials(true); } }
<groupId>com.hlzf.webapi</groupId> <artifactId>hlzfWebApi</artifactId> <version>1.0.1</version> <name>hlzfWebApi</name> <packaging>jar</packaging> <description>hlzfWebApi</description>
-
-
artifactId:jar文件名
-
version:版本號
-
輸入打包命令:mvn clean install
5. 服務部署
使用命令行運行:
java -jar xxx.jar
傳參運行,可動態配置服務監聽端口:
java -jar xxx.jar 8083 D:\\apipath\\
此時需在服務中接收參數:
@SpringBootApplication public class WebapiApplication { public static void main(String[] args) { if(args.length ==2) { //端口 System.out.println("監聽端口:" + args[0]); //上傳的文件存儲路徑 System.out.println("文件存儲路徑:" + args[1]); System.getProperties().put("server.port", Integer.valueOf(args[0])); System.getProperties().put("server.path", args[1]); } //啟動服務 SpringApplication.run(WebapiApplication.class, args); } }
如果是Windows環境,使其在后台執行,新建一個bat文件,輸入:
@echo off start javaw -jar xxx.jar exit