springboot教程一:building RESTful Web Service

建立一个RESTful Web Service

本系列教程使用idea完成
idea安装springboot插件


image.png

需求:
jdk1.8及以上
maven3.2+

第一步
新建项目 jdk选择1.8 java选择8 点击下一步


image.png

第二步
选择web下面的spring web 点击完成


image.png

第三步
创建Greeting.java 代码如下
package com.example.restservice;

public class Greeting {

    private final long id;
    private final String content;

    public Greeting(long id, String content) {
        this.id = id;
        this.content = content;
    }

    public long getId() {
        return id;
    }

    public String getContent() {
        return content;
    }
}

第四步
创建一个资源控制器

package com.example.restservice;

import java.util.concurrent.atomic.AtomicLong;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class GreetingController {

    private static final String template = "Hello, %s!";
    private final AtomicLong counter = new AtomicLong();

    @GetMapping("/greeting")
    public Greeting greeting(@RequestParam(value = "name", defaultValue = "World") String name) {
        return new Greeting(counter.incrementAndGet(), String.format(template, name));
    }
}

最后启动应用,在浏览器访问http://localhost:8080/greeting
显示如下
{"id":1,"content":"Hello, World!"}
代一个参数访问
http://localhost:8080/greeting?name=User
显示如下
{"id":2,"content":"Hello, User!"}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容