学习SpringBoot第一天(构建RESTful Web 服务)
第一步(构建springboot项目)


第二步(创建实体类)
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;
}
}
第三步(创建控制器)
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;
/**
* @RestController :相当于@ResponseBody + @Controller合在一起的作用;
* 如果只是使用@RestController注解Controller,则Controller中的方法无法返回jsp页面,
* 配置的视图解析器InternalResourceViewResolver不起作用,返回的内容就是Return 里的内容。
*
*/
@RestController
public class GreetingController {
// %s : 可以替换为请求的参数
private static final String template="Hello,%s";
// AtomicLong : 是对长整形进行原子操作
private final AtomicLong counter=new AtomicLong();
/**
* @GetMapping: 请求方式为get请求(http://localhost:8080/greeting)
* @RequestParam :将请求参数绑定到控制器;value : 参数值;defaultValue : 默认值
* incrementAndGet():每次默认加一
* @return : 返回类型为JSON,因为默认情况下web Starter 包含Jackson,Jackson库会自动将Greeting类转换为JSON;
*/
@GetMapping("/greeting")
public Greeting greeting(@RequestParam(value = "name",defaultValue = "World") String name){
return new Greeting(counter.incrementAndGet(),String.format(template,name));
}
}
第四步(测试)


浙公网安备 33010602011771号