Spring Boott基础教程二:RESTfull API简单项目的快速搭建

目录

1、spring-boot-starter-web的引入,其依赖包的学习

2、spring-boot-devtools的引入,其依赖包的学习

3、代码的实现

4、运行项目

5、打包


搭建一个简单的RESTfull API接口项目

1、spring-boot-starter-web的引入,其依赖包的学习

2、spring-boot-devtools的引入,其依赖包的学习

3、代码的实现

package com.gs.example.bean;

import java.util.Date;

public class User {
	
	private int id;
	private String name;
	private Date date;
	
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Date getDate() {
		return date;
	}
	public void setDate(Date date) {
		this.date = date;
	}
}
package com.gs.example.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.gs.example.bean.User;

@RestController
@RequestMapping("/index")
public class IndexController {

	@RequestMapping
	public String index() {
		return "hello world";
	}

	/**
	 * http://localhost:8080/index/get?name=guansong
	 * 
	 * {"name":"guansong","value":"hello spring boot"}
	 */
	@RequestMapping("get")
	public Map<String, String> get(@RequestParam String name) {
		Map<String, String> map = new HashMap<String, String>();
		map.put("name", name);
		map.put("value", "hello world");
		map.put("secret", secret);
		map.put("number", number + "");
		map.put("desc", desc); 
		return map;
	}

	@RequestMapping("find/{id}/{name}")
	public User get(@PathVariable int id, @PathVariable String name) {
		User user = new User();
		user.setId(id);
		user.setName(name);
		user.setDate(new Date());
		return user;
	}

}

4、运行项目

直接运行main方法或者使用maven命令: spring-boot:run

测试: http://localhost:8080/index

带参数:http://localhost:8080/index/get?name=wujing

带参数有中文:http://localhost:8080/index/get?name=无境

url测试:http://localhost:8080/index/get/1/wujing

url测试:http://localhost:8080/index/get/1/无境

5、打包

命令: clean package

发布了632 篇原创文章 · 获赞 758 · 访问量 51万+

猜你喜欢

转载自blog.csdn.net/songzi1228/article/details/104002795