ResponseEntity는 Spring Framework에서 클라이언트에게 HTTP 응답을 구성하여 반환할 때 사용하는 객체입니다. 일반적으로 응답 데이터, HTTP 상태 코드, 그리고 헤더 정보를 함께 전달할 수 있습니다.
* Controller 코드
@RequestMapping(value = "user/checkIn.do", method = RequestMethod.POST)
public ResponseEntity<String> checkIn(@RequestBody CheckInCheckOutVO checkInCheckOutVO) {
String latitude = checkInCheckOutVO.getLatitude();
String longitude = checkInCheckOutVO.getLongitude();
CheckInResult result = checkInCheckOutService.checkIn(checkInCheckOutVO, latitude, longitude);
switch (result) {
case SUCCESS:
return ResponseEntity.ok("출근 성공.");
case ALREADY_CHECKED_IN:
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
.body("이미 오늘 출근했습니다.");
case OUTSIDE_RANGE:
return ResponseEntity.status(HttpStatus.FORBIDDEN)
.body("회사 위치에서 벗어났습니다.");
default:
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body("시스템 오류가 발생했습니다.");
}
}
* jsp의 ajax 코드
<script>
function checkIn() {
if ("geolocation" in navigator) {
navigator.geolocation.getCurrentPosition(
(position) => {
const { latitude, longitude } = position.coords;
$.ajax({
url: "user/checkIn.do",
method: "POST",
contentType: "application/json",
data: JSON.stringify({
latitude: latitude,
longitude: longitude,
user_id: user_id // 세션의 사용자 ID
}),
success: function (data) {
// data 변수에는 서버에서 응답 본문에 담아 보낸 JSON 데이터가 들어옴
alert('출근 완료!');
},
error: function (xhr) {
if (xhr.status === 400) {
alert('이미 오늘 출근했습니다.');
} else if (xhr.status === 403) {
alert('회사 위치에서 벗어났습니다.');
} else {
alert('출근 처리 중 오류가 발생했습니다.');
}
}
});
},
(error) => {
alert(`위치 정보를 가져올 수 없습니다: ${error.message}`);
},
{
enableHighAccuracy: true,
timeout: 10000,
maximumAge: 0
}
);
} else {
alert("브라우저가 위치 서비스를 지원하지 않습니다.");
}
}
해당 코드를 통해서 결과에 따라 HTTP 상태 코드와 메시지를 클라이언트에게 반환할 수 있다는 것을 알 수있음. <br/>
- 성공 시: ResponseEntity.ok("출근 성공.") → 상태 코드 200 반환
- 이미 출근: HttpStatus.BAD_REQUEST → 상태 코드 400 반환
- 위치 벗어남: HttpStatus.FORBIDDEN → 상태 코드 403 반환
- 시스템 오류: HttpStatus.INTERNAL_SERVER_ERROR → 상태 코드 500 반환
'스프링' 카테고리의 다른 글
| [Spring] Spring MVC 프로젝트 생성 시 발생하는 오류 (0) | 2025.02.12 |
|---|---|
| [Spring] @RestController , @RequestBody, @ResponseBody (0) | 2025.02.06 |
| [Spring] Spring 세팅 오류 (0) | 2025.01.23 |
| [Spring] tomcat 연결 후 브라우저 설정 (0) | 2025.01.20 |
| sts와 이클립스 설치 관련, STS3 Legacy Project (0) | 2025.01.20 |