본문 바로가기
Java/Spring

Spring) Ajax - ResponseEntity를 통해 응답

by 박채니 2022. 9. 6.
안녕하세요, 코린이의 코딩 학습기 채니 입니다.
개인 포스팅용으로 내용에 오류 및 잘못된 정보가 있을 수 있습니다.

 

Ajax

③ ResponseEntity를 통해 응답

- rest API에서 자주 쓰임

C : POST
R : GET
U : PUT/PATCH
D : DELETE

 

memberEnroll.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
<jsp:include page="/WEB-INF/views/common/header.jsp">
	<jsp:param value="회원등록" name="title"/>
</jsp:include>
<link rel="stylesheet" href="${ pageContext.request.contextPath }/resources/css/member.css" />

<div id="enroll-container" class="mx-auto text-center">
	<form name="memberEnrollFrm" action="" method="POST">
		<table class="mx-auto">
			<tr>
				<th>아이디</th>
				<td>
			        <div id="memberId-container">
			            <input type="text" class="form-control" placeholder="아이디(4글자이상)" name="memberId" id="memberId" required>
			            <span class="guide ok">이 아이디는 사용가능합니다.</span>
			            <span class="guide error">이 아이디는 사용할 수 없습니다.</span>
			            <input type="hidden" id="idValid" value="0"/> <!-- 사용불가한 아이디인 경우 0 | 사용가능한 아이디인 경우 1 -->
			        </div>
				</td>
			</tr>
			<tr>
				<th>패스워드</th>
				<td>
					<input type="password" class="form-control" name="password" id="password" required>
				</td>
			</tr>
			<tr>
				<th>패스워드확인</th>
				<td>	
					<input type="password" class="form-control" id="passwordCheck" required>
				</td>
			</tr>  
			<tr>
				<th>이름</th>
				<td>	
					<input type="text" class="form-control" name="name" id="name" required>
				</td>
			</tr>
			<tr>
				<th>생년월일</th>
				<td>	
					<input type="date" class="form-control" name="birthday" id="birthday"/>
				</td>
			</tr> 
			<tr>
				<th>이메일</th>
				<td>	
					<input type="email" class="form-control" placeholder="abc@xyz.com" name="email" id="email">
				</td>
			</tr>
			<tr>
				<th>휴대폰</th>
				<td>	
					<input type="tel" class="form-control" placeholder="(-없이)01012345678" name="phone" id="phone" maxlength="11" required>
				</td>
			</tr>
			<tr>
				<th>주소</th>
				<td>	
					<input type="text" class="form-control" placeholder="" name="address" id="address">
				</td>
			</tr>
			<tr>
				<th>성별 </th>
				<td>
					<div class="form-check form-check-inline">
						<input type="radio" class="form-check-input" name="gender" id="gender0" value="M">
						<label  class="form-check-label" for="gender0">남</label>&nbsp;
						<input type="radio" class="form-check-input" name="gender" id="gender1" value="F">
						<label  class="form-check-label" for="gender1">여</label>
					</div>
				</td>
			</tr>
			<tr>
				<th>취미 </th>
				<td>
					<div class="form-check form-check-inline">
						<input type="checkbox" class="form-check-input" name="hobby" id="hobby0" value="운동"><label class="form-check-label" for="hobby0">운동</label>&nbsp;
						<input type="checkbox" class="form-check-input" name="hobby" id="hobby1" value="등산"><label class="form-check-label" for="hobby1">등산</label>&nbsp;
						<input type="checkbox" class="form-check-input" name="hobby" id="hobby2" value="독서"><label class="form-check-label" for="hobby2">독서</label>&nbsp;
						<input type="checkbox" class="form-check-input" name="hobby" id="hobby3" value="게임"><label class="form-check-label" for="hobby3">게임</label>&nbsp;
						<input type="checkbox" class="form-check-input" name="hobby" id="hobby4" value="여행"><label class="form-check-label" for="hobby4">여행</label>&nbsp;
					 </div>
				</td>
			</tr>
		</table>
		<input type="submit" value="가입" >
		<input type="reset" value="취소">
	</form>
</div>
<script>
const ok = document.querySelector(".guide.ok");
const error = document.querySelector(".guide.error");
const idValid = document.querySelector("#idValid");

document.querySelector("#memberId").addEventListener('keyup', (e) => {
	const {value : memberId} = e.target;
	
	if(memberId.length < 4) {
		ok.style.display = "none";
		error.style.display = "none";
		idValid.value = "0";
		return;
	}
	
	$.ajax({
		url : "${pageContext.request.contextPath}/member/checkIdDuplicate.do",
		data : {memberId},
		success(response) {
			console.log(response);
			const {available} = response
			
			if(available) {
				ok.style.display = "inline";
				error.style.display = "none";
				idValid.value = "1";
			} else {
				ok.style.display = "none";
				error.style.display = "inline";
				idValid.value = "0";
			}
		},
		error(jqxhr, statusText, err) {
			console.log(jqxhr, statusText, err);
		}
	});
});

document.memberEnrollFrm.addEventListener('submit', (e) => {
	if(idValid.value == "0") {
		e.preventDefault();
		alert("유효한 아이디를 입력해주세요.");
		return;
	}
});
</script>
<jsp:include page="/WEB-INF/views/common/footer.jsp"/>

 

Controller

MemberController

 

ResponseEntity

- @ResponseBody 기능

- 핸들러에서 응답코드, 응답헤더, 메세지바디를 자유롭게 제어할 수 있도록 도와주는 객체

- 메세지바디에 작성할 자바객체는 messageConverter에 의해 json으로 처리

@GetMapping("/checkIdDuplicate.do")
public ResponseEntity<?> checkIdDuplicate3(@RequestParam String memberId, Model model) {
    Member member = memberService.selectOneMember(memberId);
    boolean available = member == null;

    Map<String, Object> map = new HashMap<>();
    map.put("memberId", memberId);
    map.put("available", available);

    return ResponseEntity.status(HttpStatus.OK).body(map);
}

HttpStatus.OK → 200 호출

 

pom.xml

#13. jackson messageConverter 빈 관련 의존

<!-- #13 jackson messageConverter빈 관련 의존 -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.13.3</version>
</dependency>

 

servlet-context.xml

#13.1 jackson message converter bean 등록

<!-- #13.1 jackson message converter bean 등록 -->
<beans:bean id="jacksonMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>

관련 설명은 아래 포스팅 참고

https://chanychu.tistory.com/408?category=991629 

 

Spring) Ajax - MessageConverter와 @ResponseBody를 통해 응답

안녕하세요, 코린이의 코딩 학습기 채니 입니다. 개인 포스팅용으로 내용에 오류 및 잘못된 정보가 있을 수 있습니다. Ajax ② MessageConverter와 @ResponseBody를 통해 응답 memberEnroll.jsp <%@ page language..

chanychu.tistory.com

 

아래와 같이 잘 처리되는 것을 확인할 수 있습니다.