WEB/Spring
get,post,update,delete
hwahaha
2024. 3. 11. 02:22
1. get 메서드 구현
1-1 매개변수 없는 GET
@GetMapping(value="/")
public String getName(){
return "Name";
}
1-2 PathVariable GET
@GetMapping(value="/{id}")
public String getId(@PathVariable("id") Integer num){
return num;
}
1-3 RequestParm GET
@GetMapping(value="/")
public String getParam(@RequestParam String name){
return name;
}
//쿼리 파라미터에 어떤 값이 들어올지 모를때
@GetMapping(value="/")
public String getMap(@RequestParam Map<String,String){
StringBuilder sb=new StringBuilder;
param.entrySet().forEach(map ->{
sb.append(map.getKey()+" : " + mape.getValue()+"\n" })
return sb.toString();
}
//DTO 사용(MemberDTO class가 있다고 가정)
@GetMapping(value="/")
public String getDto(MemberDto dto){
return dto.toString();
}
2. post 메서드 구현
값을 body로 받아서 전송
@PostMapping(value="/")
public String postMap(@RequestBody Map<String,Object> post){
StringBuilder sb=new StringBuilder;
post.entrySet().forEach(map ->{
sb.append(map.getKey()+" : " + map.getValue()+"\n" })
return sb.toString();
}
//DTO 사용(MemberDTO class가 있다고 가정)
@PostMapping(value="/")
public String postDto(@RequestBody MemberDto dto){
return dto.toString();
}
3. update 메서드 구현
3-1
@PutMapping(value="/")
public String putMap(@RequestBody Map<String,Object> put){
StringBuilder sb=new StringBuilder;
put.entrySet().forEach(map ->{
sb.append(map.getKey()+" : " + map.getValue()+"\n" })
return sb.toString();
}
//DTO 사용(MemberDTO class가 있다고 가정)
@PuttMapping(value="/")
public String putDto1(@RequestoBody MemberDto dto){
return dto.toString();
}
@PuttMapping(value="/")
public MemberDto putDto2(@RequestoBody MemberDto dto){
return dto;
}
3-2 ResponseEntity 사용
@PuttMapping(value="/")
public ResponseEntity<MemberDto> putMemberDto(@RequestoBody MemberDto dto){
return ResponseEntity
.status(HttpStatus.ACCEPTED)
.body(dto);
}
4. delete 메서드 구현
4-1 pathVariable DELETE
@DeleteMapping(value="/{id}")
public String DeleteId(@PathVariable("id") Integer num){
return num;
}
4-2 RequestParm DELETE
@DeleteMapping(value="/")
public String deleteParm(@RequestParam String name){
return name;
}