目标:
-
项目搭建
-
接口编写
-
跨域实现
-
服务打包
-
服务部署
选择创建一个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