前言
本文引导读者通过spring boot创建一个restful服务器,笔者使用开发环境如下:
项目 | 说明 |
---|---|
jdk | 1.8 |
idea | 2017-03 |
操作步骤
- 创建spring boot项目,参考idea 新建spring boot项目;
- 创建领域类
Greeting
,(需要创建对应的包,这里就不再具体说明)
package com.nick.demo.domain;
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.nick.demo.controller;/*
* @Author : Nick
* @Description :
* @Date : Create in 21:45 2018/4/25
**/
import com.nick.demo.domain.Greeting;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.concurrent.atomic.AtomicLong;
@RestController
public class GreetingController {
private static final String template = "Hello, %s!";
private final AtomicLong counter = new AtomicLong();
@RequestMapping("/greeting")
public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) {
return new Greeting(counter.incrementAndGet(),
String.format(template, name));
}
}
- 执行查看效果
总结
- 控制类上面使用
@RestController
注解; - 方法映射地址使用
@RequestMapping
注解