Spring学习【1】Build a Restful Web Service


这篇文章将完成使用Spring创建“Hello,World” restfulweb服务的过程。

使用IDEA作为开发工具,使用Maven进行项目管理。


Starting with Spring Initialize

首先从Spring Initializr快速创建项目restservice,这里只需要添加Spring Web依赖。

spring initializr相关设置
点击Generate将项目下载到本地。


Create a Resource Representation Class

在src/main/java/com/example/restservice/目录下新建Greeting.java文件。

package com.example.restservice;

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;
	}
}

Create a Resource Controller

在目录src/main/java/com/example/restservice/下创建GreetingController.java文件。

package com.example.restservice;

import java.util.concurrent.atomic.AtomicLong;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class GreetingController {

	private static final String template = "Hello, %s!";
	private final AtomicLong counter = new AtomicLong();

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

Test the Service

到这里就可以测试service了,运行main函数。在浏览器打开http://localhost:8080/greeting,可以看到如下结果。在这里插入图片描述
同时我们可以提供name参数,在地址栏输入http://localhost:8080/greeting?name=FZQ,可以看到“Hello,World"变成了"Hello,FZQ"。
在这里插入图片描述


Summary

在这里主要对过程中用到的注解进行总结

@RestController
一个很方便的注解,自身包含了 @Controller@ResponseBody
带有这个注解的类型被视为控制器,其中 @RequestMapping 方法默认使用 @ResponseBody 的语义。

@GetMapping
@GetMapping 确保对 /greeting 的 HTTP GET 请求被映射到greeting()方法。
其他HTTP动作也有相应的注解,如POST请求有 @PostMapping 注解。 他们都是从 @RequestMapping 派生而来的,有着相同的作用,如 @RequestMapping(method=GET)

@RequestParam
@RequestParamquery string parameter name 的值绑定到greeting()方法的name参数中。如果请求中缺少name参数,则会使用默认的参数“World”。

@SpringBootApplication
@SpringBootApplication 是一个很方便的注解,包含了以下所有注解:
@Configuration:将该类标记为bean定义的源。
@EnableAutoConfiguration:告诉Spring Boot基于类的路径设置、其他bean和各种属性设置添加bean。例如,如果spring-webmvc 在类的路径上,这个注解就会将这个应用程序标记为web应用程序,并激活关键行为,例如建立一个DispatcherServlet。
@ComponentScan:告诉Spring在com/example包中查找其他组件、配置和服务,让它找到控制器。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值