其他分享
首页 > 其他分享> > Building a RESTful Web Service

Building a RESTful Web Service

作者:互联网

官网页面:https://spring.io/guides/gs/rest-service/
先建立Greeting类

package com.example.demo;

import lombok.Data;

@Data//用了这个就不用写get和set函数了
public class Greeting {
    private final long id;
    private final String content;
    public Greeting(long id,String content)
    {
        this.id=id;
        this.content=content;
    }
}

再建立controller层GreetingController
import是导入相应的包
@RestController这里是将@Controller and @ResponseBody结合起来
AtomicLong是将多线程中对这个值的操作进行了同步
@GetMapping是指跳转对应的URL
@RequestParam则是设置默认值’

package com.example.demo;
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));//incrementAndGet()自动加一
    }
}

标签:Building,Web,String,Greeting,public,content,import,RESTful,id
来源: https://blog.csdn.net/stone_2027/article/details/117326788