服务端程序本质上也只是个 Java 程序, 它接收客户端的输入, 然后将计算处理后的返回值返回给客户端. 下面我们就以这个思路开始 Java 后端之旅吧.
引用 Spring Boot 库
处理 HTTP 请求之类的事情, 我们需要库的帮助. 所以第一步我们就把 Spring Boot 引入进来.
不需要任何工具, 我们使用 maven 来管理库依赖, 这样我们只要写一个 pom.xml 就好了. 我们先写一个最简的 pom.xml. 主要是定义 groupId, 比如是我司, 还有 artifactId, 就是应用的具体名字:
- <?xml version="1.0" encoding="UTF-8"?>
- <project xmlns="http://maven.apache.org/POM/4.0.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <groupId>cn.alios.system.service.prefix</groupId>
- <artifactId>Prefix</artifactId>
- <version>1.0.0-SNAPSHOT</version>
- </project>
添加父引用
类似于类的继承, 我们不是从头开发, 而是继承 Spring Boot Starter 框架. 添加 parent 的内容如下:
- <parent>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-parent</artifactId>
- <version>2.1.2.RELEASE</version>
- </parent>
2.1.2 是本文写作时, Spring Boot 的最新版本.
增加依赖
为了自动下载库, 我们将需要的几个库添加到 pom.xml 中的依赖项中. 这样 maven 就可以帮我们从仓库中下载最新的库代码.
我们需要 AOP 和 web 两个包, 用全名是 spring-boot-starter-aop 和 spring-boot-starter-Web:
- <dependencies>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-aop</artifactId>
- </dependency>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-Web</artifactId>
- </dependency>
- </dependencies>
引用插件
Spring Boot 还提供了插件, 我们也将其引用进来:
- <build>
- <plugins>
- <plugin>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-maven-plugin</artifactId>
- </plugin>
- </plugins>
- </build>
主函数
库引用完了, 我们就写一个主程序吧. 按照惯例, 我们将其保存在 src/main/java 目录下:
- package cn.alios.system.service.prefix;
- import org.springframework.boot.SpringApplication;
- import org.springframework.boot.autoconfigure.SpringBootApplication;
- import org.springframework.Web.bind.annotation.RequestMapping;
- import org.springframework.Web.bind.annotation.ResponseBody;
- @SpringBootApplication
- @RequestMapping("/")
- public class Prefix {
- @RequestMapping("/")
- @ResponseBody
- public String home(){
- return "Hello, Java Web World!";
- }
- public static void main(String[] args) throws Exception{
- SpringApplication.run(Prefix.class,args);
- }
- }
编译
下面我们用 mvn package 命令来编译生成可运行的 jar 包:
mvn package
输出类似于下面这样:
- [INFO] Scanning for projects...
- [INFO]
- [INFO] ---------------<cn.alios.system.service.prefix:Prefix>----------------
- [INFO] Building Prefix 1.0.0-SNAPSHOT
- [INFO] --------------------------------[ jar ]---------------------------------
- [INFO]
- [INFO] --- maven-resources-plugin:3.1.0:resources (default-resources) @ Prefix ---
- [INFO] Using 'UTF-8' encoding to copy filtered resources.
- [INFO] Copying 0 resource
- [INFO] Copying 0 resource
- [INFO]
- [INFO] --- maven-compiler-plugin:3.8.0:compile (default-compile) @ Prefix ---
- [INFO] Changes detected - recompiling the module!
- [INFO] Compiling 1 source file to /Users/ziyingliuziying/working/GitLab/Prefix/target/classes
- [INFO]
- [INFO] --- maven-resources-plugin:3.1.0:testResources (default-testResources) @ Prefix ---
- [INFO] Using 'UTF-8' encoding to copy filtered resources.
- [INFO] skip non existing resourceDirectory /Users/ziyingliuziying/working/GitLab/Prefix/src/test/resources
- [INFO]
- [INFO] --- maven-compiler-plugin:3.8.0:testCompile (default-testCompile) @ Prefix ---
- [INFO] Nothing to compile - all classes are up to date
- [INFO]
- [INFO] --- maven-surefire-plugin:2.22.1:test (default-test) @ Prefix ---
- [INFO] No tests to run.
- [INFO]
- [INFO] --- maven-jar-plugin:3.1.1:jar (default-jar) @ Prefix ---
- [INFO] Building jar: /Users/ziyingliuziying/working/GitLab/Prefix/target/Prefix-1.0.0-SNAPSHOT.jar
- [INFO]
- [INFO] --- spring-boot-maven-plugin:2.1.2.RELEASE:repackage (repackage) @ Prefix ---
- [INFO] Replacing main artifact with repackaged archive
- [INFO] ------------------------------------------------------------------------
- [INFO] BUILD SUCCESS
- [INFO] ------------------------------------------------------------------------
- [INFO] Total time: 2.462 s
- [INFO] Finished at: 2019-01-31T16:53:48+08:00
- [INFO] ------------------------------------------------------------------------
最后生成的包是 target/Prefix-1.0.0-SNAPSHOT.jar.
运行
调用 java -jar target/Prefix-1.0.0-SNAPSHOT.jar 命令, 运行这个 Java 程序, 输出如下:
- . ____ _ __ _ _
- /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
- ( ( )\___ | '_ |'_| | '_ \/ _` | \ \ \ \
- \\/ ___)| |_)| | | | | || (_| | ) ) ) )
- ' |____| .__|_| |_|_| |_\__, | // //
- =========|_|==============|___/=/_/_/_/
- :: Spring Boot :: (v2.1.2.RELEASE)
- 2019-01-31 16:59:43.144 INFO 95879 --- [ main] cn.alios.system.service.prefix.Prefix : Starting Prefix v1.0.0-SNAPSHOT on ziyingliuziyingdeMacBook-Pro.local with PID 95879 (/Users/ziyingliuziying/working/GitLab/Prefix/target/Prefix-1.0.0-SNAPSHOT.jar started by ziyingliuziying in /Users/ziyingliuziying/working/GitLab/Prefix)
- 2019-01-31 16:59:43.148 INFO 95879 --- [ main] cn.alios.system.service.prefix.Prefix : No active profile set, falling back to default profiles: default
- 2019-01-31 16:59:44.289 INFO 95879 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
- 2019-01-31 16:59:44.325 INFO 95879 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
- 2019-01-31 16:59:44.325 INFO 95879 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.14]
- 2019-01-31 16:59:44.347 INFO 95879 --- [ main] o.a.catalina.core.AprLifecycleListener : The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [/Users/ziyingliuziying/Library/Java/Extensions:/Library/Java/Extensions:/Network/Library/Java/Extensions:/System/Library/Java/Extensions:/usr/lib/java:.]
- 2019-01-31 16:59:44.435 INFO 95879 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
- 2019-01-31 16:59:44.435 INFO 95879 --- [ main] o.s.Web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1234 ms
- 2019-01-31 16:59:44.665 INFO 95879 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
- 2019-01-31 16:59:44.886 INFO 95879 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
- 2019-01-31 16:59:44.889 INFO 95879 --- [ main] cn.alios.system.service.prefix.Prefix : Started Prefix in 2.161 seconds (JVM running for 2.561)
我们可以看到, 启动了一个 9.0.14 版本的 Apache Tomcat 服务器, 在 8080 端口上监听.
我们打开浏览器, 访问 http://127.0.0.1:8080/ , 可以看到『Hello, Java Web World!』这个字符串被显示出来.
再写一个 Controller
在主函数里面可以处理请求, 那么再其它类里面该如何做呢? 我们通过写 @Controller 注解, 加上 @RequestMapping 来指定路径, 就可以了.
我们来写个例子:
- package cn.alios.system.service.prefix.controller;
- import org.springframework.stereotype.Controller;
- import org.springframework.Web.bind.annotation.RequestMapping;
- import org.springframework.Web.bind.annotation.ResponseBody;
- @Controller
- @RequestMapping("/test")
- public class TestController {
- @RequestMapping("/")
- @ResponseBody
- public String test(){
- return "Test Controller!";
- }
- }
还是 mvn package, 然后 java -jar java -jar target/Prefix-1.0.0-SNAPSHOT.jar.
在浏览器里试下 http://127.0.0.1:8080/test/ , 显示:『Test Controller!』
大功告成! 现在整个从接收输入到显示输出的通道已经打通, 是不是很 easy?
来源: https://yq.aliyun.com/articles/689532