- SpringBoot2.0学习第一篇之构建RESTful Web
- Java Maven+Idea 构建SpringBoot项目(光
- SpringBoot——构建一个RESTful Web服务
- (转:目录)使用Django 2.0构建Python Restf
- SpringBoot指南|第二篇:构建一个RESTful Web
- [原创]1.创建一个 RESTful web服务
- [Spring Guides] Restful Web 服务
- SpringBoot——使用RESTful Web服务
- SAP 如何提供 RESTful Web 服务(3) - Res
- SAP 如何提供 RESTful Web 服务(2) - ABA
1. 使用@RestController注解
@RestController 相当于 @ResponseBody + @Controller的结合
2. 使用@RequestMapping注解
这个注解会将 HTTP 请求映射到 MVC 和 REST 控制器的处理方法上。
3.使用@RequestParam注解
用来处理Content-Type: 为 application/x-www-form-urlencoded编码的内容。(Http协议中,如果不指定Content-Type,则默认传递的参数就是application/x-www-form-urlencoded类型)
RequestParam可以接受简单类型的属性,也可以接受对象类型。
实质是将Request.getParameter() 中的Key-Value参数Map利用Spring的转化机制ConversionService配置,转化成参数接收对象或字段。
4.使用@SpringBootApplication注解
@SpringBootApplication是一个组合注解,包括@EnableAutoConfiguration, @Configuration 和@ComponentScan。
下面是demo:
Greeting.java
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;
}
}
GreetingController.java
@RestController
public class GreetingController {
private static final String template = "Hello, %s";
private final AtomicLong couter = new AtomicLong();
@RequestMapping("/greeting")
public Greeting greeting(@RequestParam(value = "name", defaultValue = "World") String name) {
return new Greeting(couter.incrementAndGet(),String.format(template,name));
}
}
Application.java
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
启动main方法,访问http://localhost:8080/greeting
结果:{"id":1,"content":"Hello, World!"}
网友评论