일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
- jsp
- 로컬이미지삭제
- 로컬이미지불러오기
- 비전공자개발자
- 로컬이미지저장
- 개발자취업
- 게시물상세
- springboot
- 비전공개발자
- 게시물수정
- CRUD
- 개발자취업후기
- given when then
- I/OStream
- WebConfig
- 게시판
- 단위테스트코드
- jstl
- React+SpringBoot
- JPAHibernate
- mybatis
- React+JPA
- SpringBoot JPA
- React.js
- Self-invocation
- @Transactional
- 테스트코드작성
- jar빌드
- MySQL
- 게시판 CRUD
- Today
- Total
인텔리가 '되고 싶은' 인텔리재이
[JSP + MyBatis] 6. 게시물 리스트 + JSTL 본문
🕶 참고 포스팅
- [JSP + MyBatis] 1. 프로젝트 생성 및 실행해보기
- [JSP + MyBatis] 2. 프로젝트 세팅 및 화면 출력해보기
- [JSP + MyBatis] 3. MySQL DB 연동하기
- [JSP + MyBatis] 4. 화면에 부트스트랩(Bootstrap) 적용하기
- [JSP + MyBatis] 5. 게시글 작성하기 (insert)
🕶 참고 포스팅
작성한 여러개의 게시물을 한 화면에 리스트 형태로 출력하기 위해서는 반복문으로 내용을 불러와야겠죠! 🙄
그렇게 하기 위해 필요한 것이 바로 JSTL 입니다!
JSTL이 무엇인지 먼저 알아보도록 하겠습니다😊
JSTL?
자바서버 페이지 표준 태그 라이브러리은 Java EE 기반의 웹 애플리케이션 개발 플랫폼을 위한 컴포넌트 모음이다. JSTL은 XML 데이터 처리와 조건문, 반복문, 국제화와 지역화와 같은 일을 처리하기 위한 JSP 태그 라이브러리를 추가하여 JSP 사양을 확장했다. - 위키피디아
간단히 말하자면, 자바코드를 html 태그형식으로 간편하게 사용하기 위해 나온 라이브러리입니다.
JSP의 확장태그 라고도 하고, 흔히 C태그라고 부르기도 합니다.😏
JSTL 사용하기
JSTL을 사용하기 위한 환경세팅을 해보도록 하겠습니다.
1. 프로젝트의 pom.xml에 JSTL 라이브러리 dependency 추가
<!--JSTL : HTML에서 자바를 사용할 수 있게 도와주는 라이브러리-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
2. JSTL을 사용하고자하는 화면에 태그 추가
태그의 종류는 다양하지만, 그중에서도 저는 c태그와 날짜를 원하는 양식으로 출력하기 위한 fmt 태그를 추가했습니다.
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
화면 만들기
게시물 리스트를 조회할 수 있는 화면을 만들어보겠습니다.
저는 이전에 소개해드린 부트스트랩(Bootstrap)과 JSTL를 적용하였습니다.🙂
저는 src > main > webapp > WEB-INF > views > board 폴더를 생성하고,
폴더 안에 list.jsp 생성 후 화면을 만들었습니다.
list.jsp
- c:forEach 태그로 게시물 내용을 반복적으로 불러옵니다.
💡 기존 for문
for(초기값 ; 조건식 ; 증감식 ;) {
조건식이 true일 경우 수행할 코드
}
💡 forEach문 (=Enhanced For문)
for ( type 변수이름 : 반복을 돌릴 객체 ) {
수행할 코드
}
- fmt 태그로 날짜를 "yyyy-MM-dd" 형태로 출력합니다.
- 글쓰기 버튼 클릭 시, insert.jsp 화면을 호출합니다.
- 게시물 번호 영역 클릭 시, detail.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"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ include file="../include/style.jsp"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>List Page</title>
</head>
<body>
<jsp:include page="../include/header.jsp" />
<h2 style="text-align: center">게시물 리스트</h2>
<div class="list-container">
<div class="container">
<button class="btn btn-primary"
style="display: block; margin-bottom: 10px"
onclick="location.href='/insert'">글쓰기</button>
<table class="table table-hover">
<tr>
<th>No.</th>
<th>Subject</th>
<th>Writer</th>
<th>Date</th>
</tr>
<c:forEach var="i" items="${list}">
<tr onclick="location.href='/detail/${i.bno}'">
<td>${i.bno}</td>
<td>${i.subject}</td>
<td>${i.writer}</td>
<!--날짜 포맷팅 -->
<td>
<fmt:formatDate var="resultRegDt" value="${i.reg_date}"
pattern="yyyy-MM-dd" /> ${resultRegDt}
</td>
</tr>
</c:forEach>
</table>
</div>
</div>
<jsp:include page="../include/footer.jsp"></jsp:include>
</body>
</html>
연동해놓은 DB에 다음과 같은 SQL문을 추가합니다.
저는 미리 만들어놓은 board 테이블에 제목, 내용, 작성자명, 작성일자를 추가했습니다.
insert into board (subject, content, writer, reg_date) values ('제목1','내용1','소크라테스',now());
insert into board (subject, content, writer, reg_date) values ('제목2','내용2','테스형',now());
그리고 글쓰기 버튼을 클릭하여 글을 작성해보며 이전에 구현한 글쓰기 기능이 잘 구현되는지도 확인하였습니다.
기능 구현하기
본격적으로 DB에서 데이터를 불러오기 위해, controller, domain, mapper, service에 코드를 추가하도록 하겠습니다.
src > main > java > com.example.demo 해당 경로에
controller, domain, mapper, service 패키지가 생성되어있는지 확인 후, 코드를 작성합니다.
1. controller > BoardController.java
- controller는 화면으로부터 데이터를 받아 VO에 담고, 이를 service로 값을 전달해주는 역할을 담당합니다.
- 이를 위해 service와의 의존성을 주입해주었습니다.
- 게시물 리스트 화면을 호출하는 메소드를 작성합니다.
package com.example.demo.controller;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import com.example.demo.domain.BoardVO;
import com.example.demo.service.BoardService;
@Controller // 컨트롤러 빈으로 등록
public class BoardController {
@Resource(name = "com.example.demo.service.BoardService") // Service 의존성 주입
BoardService mBoardService;
@RequestMapping("/list") // 게시판 리스트 화면 호출
private String boardList(Model model) throws Exception {
model.addAttribute("list", mBoardService.boardListService());
return "board/list";
}
2. service > BoardService.java
- Service는 Controller로부터 데이터를 받고, 이를 Mapper로 전달해주는 역할을 담당합니다.
- 이를 위해 Mapper와의 의존성을 주입해주었습니다.
package com.example.demo.service;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.example.demo.domain.BoardVO;
import com.example.demo.mapper.BoardMapper;
@Service("com.example.demo.service.BoardService")
public class BoardService {
// Mapper 의존성 주입
@Resource(name = "com.example.demo.mapper.BoardMapper")
BoardMapper mBoardMapper;
// 게시판 리스트
public List<BoardVO> boardListService() throws Exception {
return mBoardMapper.boardList();
}
3. mapper > BoardMapper.java
- Mapper 인터페이스는 Service로부터 데이터를 받고, 직접 DB에 접근하여 데이터를 처리합니다.
- Mapper.xml 에 작성된 SQL 쿼리문을 자바 인터페이스를 통해 호출하여 처리합니다.
package com.example.demo.mapper;
import java.util.List;
import org.springframework.stereotype.Repository;
import com.example.demo.domain.BoardVO;
//DB에 접근하는 클래스
@Repository("com.example.demo.mapper.BoardMapper")
public interface BoardMapper {
// 게시글 리스트
public List<BoardVO> boardList() throws Exception;
}
4. mapper > BoardMapper.xml
- 이곳에 작성된 SQL 쿼리문을 자바 인터페이스를 통해 호출하여 DB에 반영합니다.
- id는 mapper에서 설정한 이름과 동일하게 작성합니다.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.example.demo.mapper.BoardMapper">
<select
id="boardList"
resultType="com.example.demo.domain.BoardVO"
>
SELECT
*
FROM BOARD
</select>
코드 작성 후, 기능이 잘 동작하는지 확인합니다.
이로써 다음과 같은 (간단한) 게시물 리스트가 완성되었습니다!😎
게시물 작성에 이어, 작성한 여러 게시물을 리스트 화면에 출력해보았습니다.😸
다음 포스팅에서는 작성한 게시물의 상세 페이지를 조회하는 기능을 살펴보도록 하겠습니다!
'✨LEVEL UP🎇 > PROJECT' 카테고리의 다른 글
[JSP + MyBatis] 8. 게시물 수정 (update), 삭제 (delete) 하기 (1) | 2023.03.29 |
---|---|
[JSP + MyBatis] 7. 게시물 상세페이지 조회하기 (0) | 2023.03.24 |
[JSP + MyBatis] 5. 게시글 작성하기 (insert) (1) | 2023.02.07 |
[JSP + MyBatis] 4. 화면에 부트스트랩(Bootstrap) 적용하기 (0) | 2023.01.27 |
[JSP + MyBatis] 3. MySQL DB 연동하기 (0) | 2023.01.25 |