发布Rest风格的WebService的SpringBoot极简例子
JDK:1.8.0_212
IDE:STS4(Spring Tool Suit4 Version: 4.3.2.RELEASE)
工程下载:https://files.cnblogs.com/files/xiandedanteng/SpringBootSample01_190927_2.rar
以下函数提供单个emp对象的服务
@RequestMapping(value="/emp/{empid}",produces=MediaType.APPLICATION_JSON_VALUE) public Emp findEmp(@PathVariable("empid") long id) { Emp e=new Emp(); e.setId(id); e.setAge(20); e.setName("Andy"); return e; }
在Browser里的地址是
http://localhost:8080/emp/12
输出是:
{"id":12,"name":"Andy","age":20}
以下函数提供多个Emp对象服务:
@RequestMapping(value="/emps",produces=MediaType.APPLICATION_JSON_VALUE) public List<Emp> findAllEmp() { List<Emp> ls=new ArrayList<Emp>(); for(int i=0;i<10;i++) { Emp e=new Emp(); e.setId(100+i); e.setAge(20+i); e.setName("Andy"+String.valueOf(i)); ls.add(e); } return ls; }
在Browser里地址为:
http://localhost:8080/emps
输出是:
[{"id":100,"name":"Andy0","age":20},{"id":101,"name":"Andy1","age":21},{"id":102,"name":"Andy2","age":22},{"id":103,"name":"Andy3","age":23},{"id":104,"name":"Andy4","age":24},{"id":105,"name":"Andy5","age":25},{"id":106,"name":"Andy6","age":26},{"id":107,"name":"Andy7","age":27},{"id":108,"name":"Andy8","age":28},{"id":109,"name":"Andy9","age":29}]
Emp类是一个简单实体类:
package com.example.demo; public class Emp { private long id; private String name; private int age; public Emp() { } public Emp(long id,String name,int age) { this.id=id; this.name=name; this.age=age; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
--END--2019年9月27日07:04:15