REDTful风格设计接口
1.创建实体类
package com.offcn.po;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
private Long id;
private String name;
private Integer age;
}
2. 创建Controller UserController
package com.offcn.controllerold;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.offcn.po.User;
@RestController
@RequestMapping("/users-test")
public class UserController {
//这里加同步锁是为了访问安全
private List<User> listUser=Collections.synchronizedList(new ArrayList<User>());
/***
* 获取全部用户信息
* @return
*/
@GetMapping("/")
public List<User> getUserList(){
return listUser;
}
/***
* 新增用户
* @param user
* @return
*/
@PostMapping("/")
public String createUser(User user) {
listUser.add(user);
return "success";
}
/***
* 获取指定id用户信息
* @param id
* @return
*/
@GetMapping("/{id}")
public User getUser(@PathVariable("id")Long id) {
for (User user : listUser) {
if(user.getId()==id) {
return user;
}
}
return null;
}
/**
* 更新指定id用户信息
* @param id
* @param user
* @return
*/
@PutMapping("/{id}")
public String updateUser(@PathVariable("id") Long id,User user) {
for (User user2 : listUser) {
if(user2.getId()==id) {
user2.setName(user.getName());
user2.setAge(user.getAge());
}
}
return "success";
}
/***
* 删除指定id用户
* @param id
* @return
*/
@DeleteMapping("/{id}")
public String deleteUser(@PathVariable("id") Long id) {
listUser.remove(getUser(id));
return "success";
}
}