Spring基础:快速入门spring boot(3):创建Restful的Web服务

本篇文章将在上篇的基础之上,改善HelloWorld的例子, 使用参数绑定取得信息创建一个简单的Restful的web 服务。

这里写图片描述

创建一个用户类User

package com.example;

public class User {
  private final long id;
    private final String name;

    public User(long id, String name) {
        this.id = id;
        this.name = name;
    }

    public long getId() {
        return id;
    }

    public String getName() {
        return name;
    }
}

修改DemoApplication如下

package com.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.atomic.AtomicLong;

@RestController
@SpringBootApplication
public class DemoApplication {
    private static final String  templateStr = "Hello, %s ! Welcome to Spring Boot...";
    private final AtomicLong counter = new AtomicLong();

    @RequestMapping("/greeting")
    public User greeting(@RequestParam(value = "name",defaultValue = "World") String name){
        return new User(counter.incrementAndGet(),String.format(templateStr,name));
    }

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

说明:
@RequestParam(value = “name”,defaultValue = “World”): 绑定参数名称为name,缺省值为World
@RequestMapping(“/greeting”):与greeting函数建立Mapping
private final AtomicLong counter = new AtomicLong(); 用于设一一个自动计数器
public User greeting :注意greeting函数的返回值类型

执行输出

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.4.2.RELEASE)

2016-12-08 07:08:50.138  INFO 6484 --- [           main] com.example.DemoApplication              : Starting DemoApplication on vcc-PC with PID 6484 (C:\Users\Administrator\IdeaProjects\demo\target\classes started by Administrator in C:\Users\Administrator\IdeaProjects\demo)
2016-12-08 07:08:50.143  INFO 6484 --- [           main] com.example.DemoApplication              : No active profile set, falling back to default profiles: default
2016-12-08 07:08:50.283  INFO 6484 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@30ee2816: startup date [Thu Dec 08 07:08:50 CST 2016]; root of context hierarchy
2016-12-08 07:08:53.102  INFO 6484 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2016-12-08 07:08:53.135  INFO 6484 --- [           main] o.apache.catalina.core.StandardService   : Starting service Tomcat
2016-12-08 07:08:53.138  INFO 6484 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.6
2016-12-08 07:08:53.322  INFO 6484 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2016-12-08 07:08:53.322  INFO 6484 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 3044 ms
2016-12-08 07:08:53.547  INFO 6484 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: 'dispatcherServlet' to [/]
2016-12-08 07:08:53.556  INFO 6484 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2016-12-08 07:08:53.557  INFO 6484 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2016-12-08 07:08:53.557  INFO 6484 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2016-12-08 07:08:53.557  INFO 6484 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
2016-12-08 07:08:54.007  INFO 6484 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@30ee2816: startup date [Thu Dec 08 07:08:50 CST 2016]; root of context hierarchy
2016-12-08 07:08:54.118  INFO 6484 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/greeting]}" onto public com.example.User com.example.DemoApplication.greeting(java.lang.String)
2016-12-08 07:08:54.124  INFO 6484 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2016-12-08 07:08:54.125  INFO 6484 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2016-12-08 07:08:54.169  INFO 6484 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2016-12-08 07:08:54.170  INFO 6484 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2016-12-08 07:08:54.224  INFO 6484 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2016-12-08 07:08:54.475  INFO 6484 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2016-12-08 07:08:54.558  INFO 6484 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2016-12-08 07:08:54.565  INFO 6484 --- [           main] com.example.DemoApplication              : Started DemoApplication in 5.214 seconds (JVM running for 5.929)
2016-12-08 07:09:03.169  INFO 6484 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring FrameworkServlet 'dispatcherServlet'
2016-12-08 07:09:03.169  INFO 6484 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization started
2016-12-08 07:09:03.190  INFO 6484 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization completed in 21 ms

结果确认

不带参数的缺省访问: 显示Default的World,count信息提示为:1

这里写图片描述

刷新一次:count自动增长1后变成2

这里写图片描述

传入name参数值,确认参数绑定信息

这里写图片描述

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值