美文网首页我爱编程Java 杂谈
SpringBoot——构建一个RESTful Web服务

SpringBoot——构建一个RESTful Web服务

作者: 打铁大师 | 来源:发表于2018-04-03 21:30 被阅读0次

    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配置,转化成参数接收对象或字段。

    @RequestBody和@RequestParam区别

    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!"}

    相关文章

      网友评论

        本文标题:SpringBoot——构建一个RESTful Web服务

        本文链接:https://www.haomeiwen.com/subject/nzochftx.html