Spring Boot文档阅读笔记-构建Restful风格的WebService
发布日期:2021-06-30 10:46:09 浏览次数:2 分类:技术文章

本文共 3044 字,大约阅读时间需要 10 分钟。

Maven代码如下:

4.0.0
org.springframework.boot
spring-boot-starter-parent
2.1.10.RELEASE
cn.it1995
demo
0.0.1-SNAPSHOT
demo
Demo project for Spring Boot
1.8
org.springframework.boot
spring-boot-starter-web
org.projectlombok
lombok
true
org.springframework.boot
spring-boot-starter-test
test
org.junit.vintage
junit-vintage-engine
org.springframework.boot
spring-boot-maven-plugin
org.projectlombok
lombok

服务端通过处理/greeting的get方法,接收name这个string参数,返回200的json状态。

body返回如下:

{    "id": 1,    "content": "Hello, World!"}

id这个域是greetting的主键,这个值是唯一的。content里面是问候语。

Greeting.java代码如下:

package cn.it1995.demo;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;    }}

程序通过适用JaksonJson库,将Greeting自动整理成json,Jackson默认被包含在web starter的jar包中,也就是这个jar包里面:

org.springframework.boot
spring-boot-starter-web

使用@RestController创建Rest风格的WebService,GreetingController.java监听了/greeting的GET方法,代码如下:

package cn.it1995.demo;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.RestController;import java.util.concurrent.atomic.AtomicLong;@RestControllerpublic 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));    }}

@GetMapping:代表适用HTTP的get方法,参数为/greeting代表http里面的url为/greeting,等同于@RequestMapping(method=GET)。

@RequestParam:为需要传入的参数,defaultValue为设置默认值。

@RestController:等同于@Controller加@ResponseBody

这里Greeting对象能够转换为json多亏了Jackson2。Spring的MappingJackson2HttpMessageConverter会将Greeting转换为JSON。

 

程序运行截图如下:

 

转载地址:https://it1995.blog.csdn.net/article/details/111308769 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:Spring Boot文档阅读笔记-构建Restful风格的WebService客户端
下一篇:Linux笔记-shell遍历数组并判断是否等于某个值

发表评论

最新留言

留言是一种美德,欢迎回访!
[***.207.175.100]2024年04月25日 17时41分36秒