SpringBoot Restful API 请求响应总结

Controller 映射注解分为两大类:url映射注解和参数绑定注解

url映射注解:

  • @Controller:修饰class,用来创建处理http请求的对象
  • @RestController:Spring4之后加入的注解,原来在@Controller中返回json需要@ResponseBody来配合,如果直接用@RestController替代@Controller就不需要再配置@ResponseBody,默认返回json格式。
  • @RequestMapping:配置url映射

参数绑定注解:

  • @PathVariable:路径参数绑定
  • @ModelAttribute:表单模型参数绑定(不支持json) 使用频率低
  • @RequestParam:单个表单参数绑定
  • @RequestBody:接收payload方式提交的json数据

Controller 实现Restful 请求简单实例:

package com.zzg.controller;

import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zzg.common.controller.AbstractController;
import com.zzg.entity.User;
import com.zzg.service.UserService;

@RestController
@RequestMapping("/api/user")
public class UserController extends AbstractController<User> {

	@Autowired
	private UserService userService;

	// 增
	@RequestMapping(value = "/insert", method = { RequestMethod.POST }, produces = "application/json;charset=UTF-8")
	public Object insert(@RequestBody User user) {
		return userService.save(user);
	}

	// 改
	@RequestMapping(value = "/update", method = { RequestMethod.POST }, produces = "application/json;charset=UTF-8")
	public Object update(@RequestBody User user) {
		return userService.updateById(user);
	}

	// 删
	@RequestMapping(value = "/delete/{id}", method = { RequestMethod.DELETE })
	public Object delete(@PathVariable("id") Integer id) {
		return userService.removeById(id);
	}

	// 查
	@RequestMapping(value = "/getUserByName", method = { RequestMethod.GET })
	public Object getUserByName(@RequestParam String userName) {
		QueryWrapper<User> query = new QueryWrapper<User>();
		query.like("username", userName);
		return userService.getOne(query);
	}

	// 查
	@RequestMapping(value = "/getId", method = { RequestMethod.GET })
	public Object getId(@RequestParam Integer id) {
		return userService.getById(id);
	}
	
	// 查
	@RequestMapping(value = "/getPage", method = { RequestMethod.POST })
	public Object getPage(@RequestBody Map<String, Object> parame) {
		Page<User> page = this.initPageBounds(parame);
		return userService.page(page);
	}
	

}

效果截图:

SpringBoot Restful API 请求响应总结

上一篇:【SpringMVC】RestFul


下一篇:三层交换机基础原理及配置