全民學後端快餐教程(1) - 隻不過是寫個Java程式
服務端程式本質上也隻是個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?