ajax3
@GetMapping(value="/list.do", produces="application/json; charset=UTF-8")
public ResponseEntity<List<AjaxDto>> list() {
return new ResponseEntity<List<AjaxDto>>( // ResponseEntity는 @ResponseBody를 작성하지 않는다.
ajaxService.getDtoList() // 실제 응답 데이터
, HttpStatus.OK); // 응답 코드 (200)
}
ResponseEntity의 인수가 두개인 경우 첫번째 인수로는 응답 데이터를 넣어준다. 보낼 데이터 (여기선 ajaxService.getDtoList())
ResponseEntity의 두번째 인수로는 응답코드를 넣어준다. HttpStatus
상세보기 처리를 위해서 각 목록을 클릭했을 때 이름(name)을 넘겨주는 방법을
1. 목록을 구성하는 (클릭한) div 하위 태그로 span을 집어넣고 그 span안에 name을 넣은 후 찾을 때 find로 span을 찾고 그 내부 텍스트를 뜻하는 .text를 써서 이름을 넘겨준다

(어제한거)
$('#list').append('<div class="row">' + elem.name + ', ' + elem.age + '</div><input type="hidden" value="' + elem.name + '">');

3. 클릭한 div에 data 속성 data-name을 추가해서 이름을 넘겨준다.




json 데이터의 속성과 일치하는 이름을 필드로 가지고 있는 Dto로 받을 수 있다. (Dto가 가능하면 Map도 가능) - 잘 모르겠으면 map 선언하셈. json도 key value 형식이라
@PostMapping(value="/detail.do")
public ResponseEntity<AjaxDto> detail(@RequestBody AjaxDto ajaxDto) { // post 방식(@RequestBody)으로 전송된 JSON 데이터(AjaxDto ajaxDto)
// 응답 헤더 : Content-Type (produces="application/json; charset=UTF-8"을 대체한다.)
HttpHeaders header = new HttpHeaders();
header.add("Content-Type", "application/json; charset=UTF-8");
// 반환
return new ResponseEntity<AjaxDto>( // ResponseEntity는 @ResponseBody를 작성하지 않는다.
ajaxService.getDto(ajaxDto.getName()) // 실제 응답 데이터
, header // 응답 헤더
, HttpStatus.OK); // 응답 코드 (200)
}
}
<script>
$(function(){
fnImage();
})
function fnImage(){
$('#btn_image').click(function(){
var path = encodeURIComponent('C:\\GDJ69\\assets\\image');
var filename = $('#image').val();
$('#display').empty();
$('#display').append('<img src="${contextPath}/ajax4/display.do?path=' + path + '&filename=' + filename + '" width="192px">');
})
}
</script>
</head>
<body>
<%-- HDD에 저장된 이미지를 표시하기 --%>
<div>
<select id="image">
<c:forEach var="n" begin="1" end="10" step="1">
<option>animal${n}.jpg</option>
</c:forEach>
</select>
<button id="btn_image">이미지 가져오기</button>
</div>
<hr>
<div id="display"></div>
</body>
@Controller
public class AjaxController4 {
@GetMapping(value="/ajax4/display.do", produces="application/octet-stream") // "application/octet-stream" : 이진 데이터(0, 1) 자체를 의미한다.
public ResponseEntity<byte[]> display(@RequestParam("path") String path
, @RequestParam("filename") String filename) {
ResponseEntity<byte[]> responseEntity = null;
try {
// File 객체
File file = new File(path, filename);
// File 객체를 byte[]로 변환하는 Spring 클래스
byte[] b = FileCopyUtils.copyToByteArray(file);
// ResponseEntity 객체 생성
responseEntity = new ResponseEntity<byte[]>(b, HttpStatus.OK);
} catch (Exception e) {
e.printStackTrace();
}
return responseEntity;
}
}

원하는 이미지 선택 후 이미지 가져오기 버튼 누르면 이미지가 불러와짐
ajax4.jsp에서 $('#display').empty(); 해주기 전이라 가져온 이미지 계속 누적되는거
8장 만들기
맵반환
4교시 이어서
계속 이어서
주말 과제 안내