阿里云云栖社区

“云栖社区”是阿里云官方开发者技术社区,聚焦于传播云计算、大数据等DT时代核心技术的内容与资源。...

全民学后端快餐教程(1) - 只不过是写个Java程序

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yunqiinsight/article/details/86735852

服务端程序本质上也只是个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?

 

原文链接
本文为云栖社区原创内容,未经允许不得转载。

没有更多推荐了,返回首页