반응형

Insert까지 진행했엇다. 

이제는 리스트를 불러오도록 해보자!

 

 


Js 작업

 

       let str = '';
      let page = 1;
      getList(1, true);
 
 function getList(page, reset) {
         if(reset === true) {
            str = ''; //화면 리셋 여부가 true라면 str변수를 초기화.
         }
         
         $.getJSON(
            '<c:url value="/snsBoard/getList?pageNum=' + page + '" />',
            function(list) {
               console.log(list);
               
               for(let i=0; i<list.length; i++) {
                  str += "<div class='title-inner'>";
                        str += "<div class='profile'>";
                        str += "<img src='../resources/img/profile.png' >";    
                        str += "</div>";
                        str += "<div class='title'>";
                        str += "<p>"+ list[i].writer +"</p>";
                        str += "<small>"+ timeStamp(list[i].regdate) +"</small> &nbsp;&nbsp;";
                        
                        //파일다운로드
                        str += "<a href='download?fileLoca=" + list[i].fileloca +  "&fileName=" + list[i].filename + "'>이미지 다운로드</a>";
                        //파일다운로드끝
                        
                        str += "</div>";
                        str += "<div class='content-inner'>"
                        str += "<p>"+ (list[i].content === null ? '' : list[i].content) +"</p>";
                        str += "</div>";
                        /* 이미지 영역 */
                        str += "<div class='image-inner'>";
                        str += "<a href='" + list[i].bno + "'>"; ///////추가
                        str += "<img src='display?fileLoca=" + list[i].fileloca + "&fileName=" + list[i].filename +"'>";
                        str += "</a>" ////////추가
                        str += "</div>";
                        str += "<div class='like-inner'>";                   
                        str += "<img src='../resources/img/like.png'><span>522</span>";                  
                        str += "</div>";
                        str += "<div class='link-inner'>";                     
                        str += "<a href='##'><i class='glyphicon glyphicon-thumbs-up'></i>좋아요</a>";
                        str += "<a href='##'><i class='glyphicon glyphicon-comment'></i>댓글달기</a>";
                        str += "<a href='" + list[i].bno + "'><i class='glyphicon glyphicon-remove'></i>삭제하기</a>";
                        str += "</div>";
                        $('#contentDiv').html(str);
               }
               
            }
               
         ); //end getJSON
         
      } //end getList()

우선 변수 str과 page를 만들어준다. 

나는 무한스크롤을 진행을 하려고 페이지는 1로 두었다. 

 

함수를 만들어 reset을 변수로 둔다.

reset의 역활은 화면 여부가 리셋되는 것을 의미 한다. 

false가 오면 실패 true가 오면 성공이다. 

 

true값이 오면 

str을 초기화 해주는 역활을 한다. 

 

그다음 

 

(1) $.getJSON(url,callback)

1) 자바에서 static 메서드와 유사--> jQuery에서는 전역메서드라 불린다.

2) 첫번째 매개변수로 JSON 파일을 로드한다. 

3) 두번째 매개변수(콜백함수)에서 JSON 파일을 이용하여 로드된 데이터를 처리한다. 콜백함수는 로드된 데이터를 인자로 넘겨받는다.(JSON 데이터를 참조하기 위해 data 변수를 사용하고 있다.)

 

참고하자

을 활용 하여 

컨트롤러와 통신을 한다. url을 넣어주고

콜백으로 

for문을 돌려 str에 html을 add 시켜준다. 

그 후 컨트롤러와 통신을 하여 불러온 list의 값으로 

작성자 파일이름, 파일경로 등등을 불러와 준다.

그 후 str이 완료가 되었으면

 

J-Qurry 함수 html()로 전달을 해준다. 

 

그 후 reset 값이 true로 바뀌면 str의 값은 ''으로 초기화가 된다.

 

 

VO 제작

@Getter
@Setter
public class PageVO {
	
	//사용자가 선택한 페이지 정보를 담을 변수.
	private int pageNum;
	private int countPerPage;
	
	//검색에 필요한 데이터를 변수로 선언.
	private String keyword;
	private String condition;
	
	public PageVO() {
		this.pageNum = 1;
		this.countPerPage = 10;
	}

}

 

컨트롤러 제작

	@GetMapping("/getList")
	@ResponseBody
	public List<SnsBoardVO> getList(PageVO paging) {
		paging.setCountPerPage(3);
		return service.getList(paging);
	}

 

rest방식으로 통신을 진행한다. 

리스트타입으로 snsVO 타입으로 받고 

페이지의 정보를 리턴해야 하기 때문에 paging을 변수로 설정한다. 

 

 

 

서비스 제작

	@Override
	public List<SnsBoardVO> getList(PageVO paging) {
		return mapper.getList(paging);
	}

 

매퍼 제작

 

   <select id="getList" resultType="com.spring.myweb.command.SnsBoardVO">
          SELECT * FROM snsboard
            ORDER BY bno DESC
    
      
   </select>

js 추가 작성

 

 $.ajax({
            url: '<c:url value="/snsBoard/upload" />',
            type: 'post',
            data: formData, //폼데이터 객체를 넘깁니다.
            contentType: false, //ajax 방식에서 파일을 넘길때는 반드시 false로 처리 -> "multipart/form-data"로 선언됨.
            processData: false, //폼 데이터를 &변수=값&변수=값... 형식으로 변경되는 것을 막는 요소.
            success: function(result) {
               if(result === 'success') {
                  $('#file').val(''); //파일선택지 비우기
                  $('#content').val(''); //글 영역 비우기
                  $('.fileDiv').css('display', 'none'); //미리보기 감추기
                  getList(1, true); //글 목록을 호출
               } else {
                  alert('업로드에 실패했습니다. 관리자에게 문의해 주세요.');
               }
            },
            error: function(request, status, error) {
               console.log('code: ' + request + '\n' + 'message: ' + request.responseText + '\n' + 'error: ' + error);
               alert('업로드에 실패했습니다. 관리자에게 문의해 주세요.');
            }
            
         }); //end ajax

저번에 insert 에서 만들어 두었는데 

마지막 부분에 getList()를 추가해주어

등록하기 버튼을 눌렀을 때 getList가 작동될 수 있게 해준다.

 

그 후 

 

  for(let i=0; i<list.length; i++) {
                  str += "<div class='title-inner'>";
                        str += "<div class='profile'>";
                        str += "<img src='../resources/img/profile.png' >";    
                        str += "</div>";
                        str += "<div class='title'>";
                        str += "<p>"+ list[i].writer +"</p>";
                        str += "<small>"+ timeStamp(list[i].regdate) +"</small> &nbsp;&nbsp;";
                        
                        //파일다운로드
                        str += "<a href='download?fileLoca=" + list[i].fileloca +  "&fileName=" + list[i].filename + "'>이미지 다운로드</a>";
                        //파일다운로드끝
                        
                        str += "</div>";
                        str += "<div class='content-inner'>"
                        str += "<p>"+ (list[i].content === null ? '' : list[i].content) +"</p>";
                        str += "</div>";
                        /* 이미지 영역 */
                        str += "<div class='image-inner'>";
                        str += "<a href='" + list[i].bno + "'>"; ///////추가
                        str += "<img src='display?fileLoca=" + list[i].fileloca + "&fileName=" + list[i].filename +"'>";
                        str += "</a>" ////////추가
                        str += "</div>";
                        str += "<div class='like-inner'>";                   
                        str += "<img src='../resources/img/like.png'><span>522</span>";                  
                        str += "</div>";
                        str += "<div class='link-inner'>";                     
                        str += "<a href='##'><i class='glyphicon glyphicon-thumbs-up'></i>좋아요</a>";
                        str += "<a href='##'><i class='glyphicon glyphicon-comment'></i>댓글달기</a>";
                        str += "<a href='" + list[i].bno + "'><i class='glyphicon glyphicon-remove'></i>삭제하기</a>";
                        str += "</div>";
                        $('#contentDiv').html(str);
               }

 

그 후 snsList에서 등록된  이미지를 저장 후 불러 와줄 컨트롤러를 작성한다.

 

str += "<img src='display?fileLoca=" + list[i].fileloca + "&fileName=" + list[i].filename +"'>";

이부분에서 컨트롤러를 부른다. 

 

fileLoca = 파일경로

fileName = 파일이름 

	//게시글의 이미지 파일 전송 요청
	//ResponseEntity: 응답으로 변환될 정보를 모두 담은 요소들을 객체로 만들어서 반환해 줍니다.
	@GetMapping("/display")
	public ResponseEntity<byte[]> getFile(String fileLoca, String fileName) {
		
		System.out.println("fileName: " + fileName);
		System.out.println("fileLoca: " + fileLoca);
		
		File file = new File("C:\\Users\\mls00\\OneDrive\\바탕 화면\\upload\\" + fileLoca + "\\" + fileName);
		System.out.println(file);
		
		ResponseEntity<byte[]> result = null;
		
		try {
			
			HttpHeaders headers = new HttpHeaders();
			//probeContentType: 파라미터로 전달받은 파일의 타입을 문자열로 변환해 주는 메서드.
			//사용자에게 보여주고자 하는 데이터가 어떤 파일인지를 검사해서 응답 상태 코드를 다르게 리턴할 수도 있습니다.
			headers.add("Content-Type", Files.probeContentType(file.toPath()));
//			headers.add("merong", "hello");
			
			//ResponseEntity<>(응답 객체에 담을 내용, 헤더에 담을 내용, 상태 메세지);
			//FileCopyUtils: 파일 및 스트림 데이터 복사를 위한 간단한 유틸리티 메서드의 집합체.
			//file객체 안에 있는 내용을 복사해서 byte배열로 변환해서 바디에 담아 화면에 전달.
			result = new ResponseEntity<>(FileCopyUtils.copyToByteArray(file), headers, HttpStatus.OK);

		} catch (IOException e) {
			e.printStackTrace();
		}
		
		
		return result;
		
	}

이부분은 좀더 공부가 필요해 보인다 . 

 

3편에서 계속...

반응형

+ Recent posts