Hello

파일첨부_파일첨부 완료 후 게시글 조회시 이미지 출력

by 볼빵빵오춘기

Board2DTO

  • Service에서 가져온 Entity값을 DTO로 변환해서 View으로 넘겨줘야한다.
  • 이 때 fileAttached 값이 1 이면 이미지가 있고 0이면 이미지가 없는것이다
  • fileAttached 값이 1이면 파일의 originalFileName과 storedFileName 도 DTO에 담아 넘겨준다.
  • 파일이 있을 경우 원본파일이름과 저장파일이름을 가져와야한다.
더보기

But Board2Entity를 매개변수로 받았는데 어떻게 가져올까?
board_table 과 board_file_table은 연결되어있다.

일반 쿼리로 쓴다면 아래와 같다.

select * from board_table b, board_file_table bf where b.id=bf.board_id and where b.id=?

 

위의 쿼리를 스프링 JPA가 아래 코드와 같이 쓸 수 있게 도와준다.

board2DTO.setOriginalFileName(board2Entity.getBoardFileEntityList().get(0).getOriginalFileName());
  • 어떻게 알고 도와주냐면 board_table 과 board_file_table 연결할 때 위의 같은 연결코드를 작성하였다.
  • 연결코드를 써줌으로써 board2Entity에서 boardFileEntityList에 접근할 수 있도록 해준다.
    ⇒ 즉, 자기 자식 데이터에 접근이 가능하다.
    ⇒ board2Entity.getBoardFileEntityList() 는 어디서 가져온 데이터냐면 board_file_table에서 가져온 데이터이다.
  • get(0) 은 List의 첫번째 인덱스 0번을 의미한다.
    (아직 단일 파일첨부이기때문에 0번으로 직접적으로 가져왔지만 파일이 여러개이면 for문 같이 반복문을 이용해 가져와야한다.)
public static Board2DTO toBoard2DTO(Board2Entity board2Entity){
        Board2DTO board2DTO = new Board2DTO();

        board2DTO.setId(board2Entity.getId());
        board2DTO.setBoardWriter(board2Entity.getBoardWriter());
        board2DTO.setBoardPass(board2Entity.getBoardPass());
        board2DTO.setBoardTitle(board2Entity.getBoardTitle());
        board2DTO.setBoardContents(board2Entity.getBoardContents());
        board2DTO.setBoardHits(board2Entity.getBoardHits());
        board2DTO.setBoardCreatedTime(board2Entity.getCreatedTime());
        board2DTO.setBoardUpdatedTime(board2Entity.getUpdatedTime());

        if(board2Entity.getFileAttached()==0){
            board2DTO.setFileAttached(board2Entity.getFileAttached());
        }else{
            board2DTO.setFileAttached(board2Entity.getFileAttached());
            // 파일 이름을 가져가야 함.
            // originalFileName, storedFileName : board_file_table(=BoardFileEntity)
            // join
            // select * from board_table b, board_file_table bf where b.id=bf.board_id
            // and where b.id=?
            board2DTO.setOriginalFileName(board2Entity.getBoardFileEntityList().get(0).getOriginalFileName());
            board2DTO.setStoredFileName(board2Entity.getBoardFileEntityList().get(0).getStoredFileName());

        }

        return board2DTO;
    }

 

참고 - @Transactional

  • JPA쿼리가 아닌 직접적으로 쿼리를 작성하여 가져올 때 Service에 직접적인 쿼리를 사용하는 메소드 위에 @Transactional 을 붙여준 적이 있다.
  • 부모Entity에서 자식Entity에 접근할 때는 그 접근하는 메서드를 하는 곳에도 @Transactional을 붙여준다.

board2detail.html

  • Thymeleaf if문을 써서 파일첨부여부가 1이면 이미지를 보여준다.
  • Thymeleaf 이미지를 넣는다.
    (이미지태그에 src "@{|/upload/${board.storedFileName}|}" 실제 경로가 아닌 |/upload/ 라 적었는데 뒤에 경로설정을 한다.)
<tr th:if="${board.fileAttached == 1}">
    <th>image</th>
    <td><img th:src="@{|/upload/${board.storedFileName}|}" alt=""></td>
</tr>

 

WebConfig

  • Config 패키지 생성, WebConfig 클래스 생성
  • board2detail.html에서 이미지태그에 src속성을 적을 때 ( "@{|/upload/${board.storedFileName}|}" ) 경로에 upload를 넣었다. 하지만 우리는 파일을 저장할 때 upload에 파일에 넣지 않았다.
  • @Configuration 어노테이션을 이용해서 설정클래스로 지정을한다. 코드를 넣음으로써 리소스의 경로를 설정할 수 있다.
    스프링프레임워크는 서블릿컨테스트에서 설정해주는 부분이 있지만 스프링부트는 xml로 설정을 할 수도 있지만 클래스로도 설정이 가능하다.
package com.example.member2.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {
    private String resourcePath = "/upload/**"; // view 에서 접근할 경로

//    private String savePath = "file:///C:/springboot_img/"; // 실제 파일 저장 경로(window)
    private String savePath = System.getProperty("user.dir")+"/src/main/resources/static/files/"; // 실제 파일 저장 경로(mac)

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler(resourcePath)
                .addResourceLocations(savePath);
    }
}

블로그의 정보

Hello 춘기's world

볼빵빵오춘기

활동하기