SpringBoot学习笔记#1 创建一个RESTful Web服务
新建一个spring boot工程
新建一个POJO类
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; } }
新建一个controller
import java.util.concurrent.atomic.AtomicLong; import org.springframework.web.bind.annotation.RequestMapping; 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(); @RequestMapping("/greeting") public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) { return new Greeting(counter.incrementAndGet(), String.format(template, name)); } }
*@RestController注释标志这个类的所有方法都返回一个领域对象而不是视图,是@Controller和@ResponseBody结合的简写
*Spring自动使用MappingJackson2HttpMessageConverter将Greeting示例转为JSON
启动工程
修改项目根路径
application.properties
spring.mvc.servlet.path=/acme
访问