Spring Boot 之 RESTfull API简单项目的快速搭建(一)

1.创建项目

2.创建 controller

IndexController.java

package com.roncoo.example.controller;

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

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.roncoo.example.bean.User;

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

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

	@RequestMapping(value = "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");

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

3.创建 bean -- 实体类 User

User.java

package com.roncoo.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;
	}

}

4.测试

SpringBootDemo21ApplicationTests.java

package com.roncoo.example;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.RequestBuilder;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;

import com.roncoo.example.controller.IndexController;

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootDemo21ApplicationTests {
	
	private MockMvc mvc;
	
	@Before
	public void befor() {
		this.mvc = MockMvcBuilders.standaloneSetup(new IndexController()).build();
	}

	@Test
	public void contextLoads() throws Exception {
		RequestBuilder req = get("/index");
		mvc.perform(req).andExpect(status().isOk()).andExpect(content().string("hello world"));
	}

}

5.项目目录

posted @ 2019-02-01 21:13  每天都要进步一点点  阅读(994)  评论(0编辑  收藏  举报