데이터 입력
controller
@PostMapping("/api/v1/main")
public ResponseDTO<Object> postMainData(@RequestBody ReqInsertMainDTO ReqInsertMainDTO) {
mainService.postMainData(ReqInsertMainDTO);
}
ReqInsertMainDTO.java
package com.example.hr1.domain.main.dto;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.ToString;
@NoArgsConstructor
@AllArgsConstructor
@Getter
@ToString
public class ReqInsertMainDTO {
private String regionsName;
}
mainService
public void postMainData(ReqInsertMainDTO reqInsertMainDTO){
long count = regionsRepository.count();
RegionsEntity regionsEntity = RegionsEntity.builder()
.regionId((int)count + 1)
.regionName(reqInsertMainDTO.getRegionsName())
.build();
regionsRepository.save(regionsEntity);
}
+ json 형식으로 리턴
ResponseDTO.java
package com.example.hr1.common.dto;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Getter
public class ResponseDTO<T> {
private Integer code;
private String message;
private T data;
}
controller
@PostMapping("/api/v1/main")
public ResponseDTO<Object> postMainData(@RequestBody ReqInsertMainDTO ReqInsertMainDTO) {
mainService.postMainData(ReqInsertMainDTO);
return ResponseDTO
.builder()
.code(0)
.message("region 등록에 성공했습니다")
.build();
}
추가 버튼 구현
html
<div>
<input id="newRegion" type="text" placeholder="새 지역" />
<button id="addButton">추가</button>
</div>
script
document.querySelector("#addButton").addEventListener("click", () => {
const reqInsertMainDTO = {
regionsName: document.querySelector("#newRegion").value
};
fetch("/api/v1/main", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(reqInsertMainDTO),
})
.then((response) => response.json())
.then((data) => {
alert(data.message);
if(data.code === 0){
location.reload();
}
console.log(data);
})
.catch((error) => {
console.error("Error:", error);
});
});
정말 잘 읽었습니다, 고맙습니다!