안녕하세요, 코린이의 코딩 학습기 채니 입니다.
개인 포스팅용으로 내용에 오류 및 잘못된 정보가 있을 수 있습니다.
Ajax
② MessageConverter와 @ResponseBody를 통해 응답
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>
<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>
<input type="checkbox" class="form-check-input" name="hobby" id="hobby1" value="등산"><label class="form-check-label" for="hobby1">등산</label>
<input type="checkbox" class="form-check-input" name="hobby" id="hobby2" value="독서"><label class="form-check-label" for="hobby2">독서</label>
<input type="checkbox" class="form-check-input" name="hobby" id="hobby3" value="게임"><label class="form-check-label" for="hobby3">게임</label>
<input type="checkbox" class="form-check-input" name="hobby" id="hobby4" value="여행"><label class="form-check-label" for="hobby4">여행</label>
</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
MessageConverter(jackson)
- 리턴 객체를 json으로 변환
@ResponseBody
- 핸들러의 리턴 객체를 응답메세지 body에 작성
@GetMapping("/checkIdDuplicate.do")
@ResponseBody
public Map<String, Object> checkIdDuplicate2(@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 map;
}
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 등록
- 핸들러의 리턴 값이 viewName이 아닌 자바 객체가 리턴 되었을 때 json으로 변환해줌
<!-- #13.1 jackson message converter bean 등록 -->
<beans:bean id="jacksonMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
핸들러의 리턴 값이 viewName이 아닌 자바 객체가 리턴 된다면 해당 MessageConverter가 실행되어 json으로 변환해준 후 @ResponseBody에 의해 응답메세지 바디에 작성됩니다.
따라서 아래와 같이 처리해줄 수 있는 것이죠.
'Java > Spring' 카테고리의 다른 글
Spring) Rest API - 개요, GET (java.time 패키지 처리 관련 의존 설정) (0) | 2022.09.06 |
---|---|
Spring) Ajax - ResponseEntity를 통해 응답 (0) | 2022.09.06 |
Spring) Ajax - jsonView빈을 통해 응답 (0) | 2022.09.05 |
Spring) 파일 다운로드 (0) | 2022.09.04 |
Spring) 2개 이상 테이블 조회(JOIN) - association, collection (0) | 2022.09.02 |