상세 컨텐츠

본문 제목

JSTL문법 <c:forEach> c:tag를 이용한 리스트 출력

programing/JAVA&JSP&SERVLET&SPRING

by ZelKun 2018. 1. 1. 20:05

본문

반응형

사이트를 제작을 하게되면 DB연동과 함께 제일 먼저하는게 게시판을 구현하는 건데요

게시판 DB 페이지에 보여줘야 합니다 한마디로 DB 잘해서는 안되는 거죠

DB에서는 게시글 리스트를 불러와서 JSP페이지에 출력을 하게 되는데 JSP소스가 그대로 있으면

지저분 하고 유지보수할때도 번거롭게 됩니다. Bean이라던지.. request 사용이라던지..

각설하고 JSTL 문법을 사용하면 편합니다

 

리스트 출력은 이전에 샘플로 만들 소스가 있어서 재사용했습니다.

게시판은 보통 title, contents, count 정도 많이 사용하니 3개만 사용하는걸로

 

샘플 리스트 데이터

{contents=three, count=87, title=셋}, {contents=two, count=99, title=둘}, {contents=one, count=100, title=하나}

 

    • jsp 소스

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<%@ page import="java.util.Map"%>

<%@ page import="java.util.HashMap"%>

<%@ page import="java.util.List"%>

<%@ page import="java.util.ArrayList"%>

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

 

<% //DB 연동 대신 List 데이터

List<Map> allList = new ArrayList<Map>();

allList.clear();

 

HashMap<String, Object> hm = new HashMap<String, Object>();

hm.put("title", "셋");

hm.put("contents", "three");

hm.put("count", "87");

allList.add(hm);

 

hm = new HashMap<String, Object>();

hm.put("title", "둘");

hm.put("contents", "two");

hm.put("count", "99");

allList.add(hm);

 

hm = new HashMap<String, Object>();

hm.put("title", "하나");

hm.put("contents", "one");

hm.put("count", "100");

allList.add(hm);

 

request.setAttribute("allList", allList); //JSP 데이터 전달

out.print("list size:\t" + allList.size()); //List Size 출력

out.print("<br/>list :\t" + allList); //List 내용 출력

%>

 

<!DOCTYPE html>

<html lang="ko">

<head>

<meta charset="utf-8" />

<title>c:forEach test</title>

</head>

<body>

<table border="1">

<thead>

<tr>

<td>제목</td>

<td>조회수</td>

</tr>

</thead>

<tbody>

<c:forEach items="${allList }" var="item" varStatus="i">

<tr>

<td><c:out value="${item.title}"/></td>

<td><c:out value="${item.count}"/></td>

</tr>

</c:forEach>

</tbody>

</table>

</body>

</html>

 

  • 결과
리스트가 잘나오네요
제목에  엥커(<a />)를 달고 조회 화면을 만들고 추가해 나가면 됩니다


  • 참고


반응형

관련글 더보기

댓글 영역