본문 바로가기
개발 공부 Today I Learned

[국비 65일차 TIL] 갤러리 글 상세보기

by 개발자신입 2024. 2. 26.
반응형

갤러리 상세보기


gallery.jsp

포토카드 형식으로 갤러리 화면 만들기 (부트스트랩 card 사용)

-> 정사각형 이미지 틀 안에 직사각형 이미지가 들어갈 경우, 정사각형 이미지 틀에 맞춰서 확대되도록.
<img src="./resources/upfile/${row.gfile}" class="card-img-top img-fluid" style="height: 100%; object-fit: cover;">

 

	<!-- 갤러리 업로드 -->
	<section class="page-section" id="gallery" style="margin-top: 30px;">
		<div class="container">
			<div class="row">
				<c:forEach items="${list}" var="row">
					<div class="col-lg-3 col-md-4 col-sm-6 mb-4">
						<div class="card h-100">
							<img src="./resources/upfile/${row.gfile}" class="card-img-top img-fluid" style="height: 100%; object-fit: cover;">
							<div class="card-body">
								<h5 class="card-title">${row.gtitle}</h5>
								<p class="card-text">${row.gcontent}</p>
							</div>
							<div class="card-footer d-flex justify-content-between align-items-center">
								<small class="text-muted">${row.gdate}</small> 
								<span class="badge rounded-pill bg-primary">${row.glike}</span>
							</div>
						</div>
					</div>
				</c:forEach>
			</div>
			<div class="d-flex justify-content-end">
				<button type="submit" class="btn btn-primary btn-lg" onclick="location.href='./galleryInsert'">글쓰기</button>
			</div>
		</div>
	</section>

 

 

 

gallery-mapper.xml

날짜 보기 편하게 변경 및 최신글이 앞으로 오도록 ORDER BY

 

	<select id="galleryList" resultType="galleryDTO">
		SELECT gno, gtitle, gfile, 
		if(date_format(now(), '%Y-%m-%d') = date_format(gdate, '%Y-%m-%d'), 
		date_format(gdate, '%h:%i'),
		date_format(gdate, '%Y-%m-%d')
		) as gdate, glike
		FROM gallery
		WHERE gdel=1
		ORDER BY gno DESC
	</select>

 

galleryDetail.jsp

이미지를 클릭하면 상세페이지로 넘어가기 <onclick="galleryDetail(${row.gno})">

<img src="./resources/upfile/${row.gfile}" class="card-img-top img-fluid" style="height: 100%; object-fit: cover;" onclick="galleryDetail(${row.gno})">

// 주소 /를 @로 변경
function galleryDetail(no){
	location.href = './galleryDetail@'+no;
}

 

 

GalleryController.java

선생님은 String으로 intCheck를 사용했지만 그냥 Integer로 적용시킴. 

Service, DAO에서도 String이 아닌 Integer로 해야함.

	// 2024-02-26 gallerDetail 요구사항 확인
	   @GetMapping("/galleryDetail@{no}")
	   public String galleryDetail(@PathVariable("no") Integer no, Model model) {
	      System.out.println("경로" + no);
	      
	      GalleryDTO detail = galleryService.detail(no);
	      model.addAttribute("detail", detail);
	      
	      return "galleryDetail";
	   }
}

 

-> detail 생성하기 (GalleryService, DAO)

 

GalleryService.java

	public GalleryDTO detail(Integer no) {
		return galleryDAO.detail(no);
	}

 

GalleryDAO.java

	public GalleryDTO detail(Integer no) {
		return sqlSession.selectOne("gallery.galleryDetail", no); // "mapper의 namespace.메소드명" 
	}

 

gallery-mapper.xml

	<select id="galleryDetail" parameterType="Integer" resultType="galleryDTO">
      SELECT g.gno, g.glike, g.gtitle, g.gcontent, g.gfile,
      g.gdate, m.mname, m.mid FROM gallery g JOIN member m ON g.mno=m.mno
      WHERE g.gno=#{no} AND g.gdel='1'
	</select>

 

날짜 데이터를 년/월/일로 표현하기.

	<select id="galleryDetail" parameterType="Integer" resultType="galleryDTO">
      SELECT g.gno, g.glike, g.gtitle, g.gcontent, g.gfile, 
      date_format(g.gdate, '%Y년 %m월 %d일') as gdate, m.mname, m.mid 
      FROM gallery g JOIN member m ON g.mno=m.mno 
      WHERE g.gno=#{no} AND g.gdel='1'
	</select>

중복 부분 상속받기


DAO에 같은 부분( SqlSession )이 존재하므로 부모 형태 하나를 만들어서 받아오도록 하기 

 

AbstractDAO.java

import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;

// 2024-02-26 부모형태로 존재하도록

public class AbstractDAO {
	@Autowired
	Protected SqlSession sqlSession;
}

 

-> SqlSession이 있는 다른 DAO 파일에서 @Autowired를 삭제한 후,  extends AbstractDAO 상속받도록 하기.
@Autowired를 삭제하면 어차피 빨간줄 오류 뜸. 
-> AbstractDAO에서 접근제한자를 protected로 변경.

 

Service에도 동일하게 상속 적용하기 (Util)

 

AbstractService.java

import org.green.util.Util;
import org.springframework.beans.factory.annotation.Autowired;

public class AbstractService {
	@Autowired
	Util util;
}

 

@Resource 추가하기 위해 어노테이션 코드를 pom.xml에 추가하기

<!-- https://mvnrepository.com/artifact/javax.annotation/javax.annotation-api -->
<dependency>
    <groupId>javax.annotation</groupId>
    <artifactId>javax.annotation-api</artifactId>
    <version>1.3.2</version>
</dependency>

 

GalleryController.java

기존의 @Autowired를 삭제하고 @Resource로 변경하기 (@Resource(name="galleryService"))

 

@Controller
public class GalleryController {
	
	@Resource(name="galleryService")
	private GalleryService galleryService;

 

GalleryService.java

컨트롤러에서 바꾼 리소스의 name을 @Service 어노테이션 뒤에 입력해줌.
GalleryService를 GalleryServiceImpl로 변경

@Service("galleryService")
public class GalleryServiceImpl extends AbstractService {

 

=> * 중요 : 컨트롤러 @Resource(name="여기 이름")과 서비스 @Service("여기 이름") : 같아야 함.

 

GalleryService (interface)

인터페이스 : 객체 생성 불가, 상속 목적 (강제성)
GalleryController.java의 에러를 없애주기 위해

public interface GalleryService {
	
	public int galleryInsert(GalleryDTO dto); 
	
	public List<GalleryDTO> galleryList();
	
	public GalleryDTO detail(Integer no); 
}

 

인터페이스 생성하여 서비스(GalleryServiceImpl)에 implements 해줘야 함.

@Service("galleryService")
public class GalleryServiceImpl extends AbstractService implements GalleryService {

공지사항 만들기


공지사항 게시판 notice

  • NoticeController
  • NoticeService
  • NoticeServiceImpl
  • NoticeDAO
  • NoticeDTO
  • notice-mapper.xml

제작 순서

NoticeDTO - DB - NoticeService

 

NoticeDTO

import lombok.Data;

@Data
public class NoticeDTO {
	private int nno, ndel, nread, nlike;
	private String ntitle, ncontent, ndate;
}

 

Database

테이블명 : notice
column : 

nno(int, auto, PK), ndel(int 1), nread(int, 기본값 1), nlike(int, 기본값 1), 

ntitle(varchar, 50), ncontent(varchar, 500), ndate(datetype, current timestamp)

 

CREATE TABLE notice (
	nno INT AUTO_INCREMENT PRIMARY KEY,
	ndel INT,
	nread INT,
	nlike INT,
	ntitle VARCHAR(255),
	ncontent VARCHAR(500),
	ndate TIMESTAMP
);

 

NoticeService 인터페이스

public List<NoticeDTO> noticeList();
public NoticeDTO detail(int no);
public int noticeWrite(NoticeDTO);
public int noticeDel(int no);
public int noticeUpdate(NoticeDTO);

import java.util.List;

import org.green.dto.NoticeDTO;

public interface NoticeService {

    public List<NoticeDTO> noticeList();
    public NoticeDTO detail(int no);
    public int noticeWrite(NoticeDTO noticeDTO);
    public int noticeDel(int no);
    public int noticeUpdate(NoticeDTO noticeDTO); 
}

 

반응형

댓글