1.REST简介
REST(Representational State Transfer) 表现形式状态转换,通俗理解为网络资源访问格式,按照这种格式对网络资源进行访问称为RESTful
传统风格资源描述形式:
http://localhost/user/getById?id=1
REST风格描述形式:
http://localhost/user/1
Spring MVC支持四种访问行为:GET、POST、PUT、DELETE
2.RESTful入门案例
步骤:
1.根据操作行为设定http请求的动作,根据method属性
2.设定请求参数(路径变量)“/users/{id}”,在形参前加注解@PathVariable表示接收的请求参数为路径变量
package com.itheima.controller;
import com.itheima.pojo.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
//定义controller
//使用@Controller来定义Bean
@Controller
public class UserController {
@RequestMapping(value = "/users",method = RequestMethod.POST)
@ResponseBody
public String save()
{
System.out.println("user save...");
return "save successfully";
}
@RequestMapping(value = "/users/{id}",method = RequestMethod.DELETE)
@ResponseBody
//@PathVariable表示请求数据来自于路径变量
public String delete(@PathVariable Integer id)
{
System.out.println("user delete..."+id);
return "delete successfully";
}
@RequestMapping(value = "users",method = RequestMethod.PUT)
@ResponseBody
public String update(@RequestBody User user)
{
System.out.println(user);
return "update successfully!";
}
@RequestMapping(value = "/users/{id}",method = RequestMethod.GET)
public String getById(@PathVariable Integer id)
{
System.out.println("getById"+id);
return "successfully!";
}
}
简化RESTful开发
package com.itheima.controller;
import com.itheima.pojo.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
//定义controller
//使用@Controller来定义Bean
@RestController
@RequestMapping("/users")
public class UserController {
@PostMapping
public String save()
{
System.out.println("user save...");
return "save successfully";
}
@DeleteMapping("/{id}")
//@PathVariable表示请求数据来自于路径变量
public String delete(@PathVariable Integer id)
{
System.out.println("user delete..."+id);
return "delete successfully";
}
@PutMapping
public String update(@RequestBody User user)
{
System.out.println(user);
return "update successfully!";
}
@GetMapping("/{id}")
public String getById(@PathVariable Integer id)
{
System.out.println("getById"+id);
return "successfully!";
}
}
基于Restful的分页查询controller层
总结