1. HTML 테이블을 만들어 볼 것이다.
2. forEach 태그를 사용하여 정보를 표시할 것이다.
3. 이클립스로 고고
1)
다이나믹 웹 프로젝트의 Java Resources/src에 새로운 패키지 생성
Student class 생성
package com.luv2code.jsp.tagdemo;
public class Student {
private String firstName;
private String lastName;
private boolean goldCustomer;
public Student(String firstName, String lastName, boolean goldCustomer) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.goldCustomer = goldCustomer;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public boolean isGoldCustomer() {
return goldCustomer;
}
public void setGoldCustomer(boolean goldCustomer) {
this.goldCustomer = goldCustomer;
}
}
학생들의 데이터를 받을 자바 클래스 생성, firstName, lastName, goldCustomer
생성자(String firstName, String lastName, boolean goldCustomer)
getter, setter 생성
2)
<%@page import="java.util.ArrayList"%>
<%@page import="com.luv2code.jsp.tagdemo.Student"%>
<%@page import="java.util.List"%>
<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%
List<Student> list = new ArrayList<>();
list.add(new Student("mohamad", "sala", true));
list.add(new Student("sadio", "mane", false));
list.add(new Student("diogo", "jose", false));
pageContext.setAttribute("students", list);
%>
<html>
<body>
<table border = "1">
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Gold Customer</th>
</tr>
<c:forEach var = "std" items = "${students }">
<tr>
<td>${std.firstName }</td>
<td>${std.lastName }</td>
<td>${std.goldCustomer }</td>
</tr>
</c:forEach>
</table>
</body>
</html>
<c:forEach var = "std" items = "${students}">
반복할 태그 안에 ${std.firstName~~} 인자들을 순서대로 받는다.
3) forEach 태그를 사용하지 않는다면?....
<table border = "1">
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Gold Customer</th>
</tr>
<%for(int i = 0; i<list.size(); i++) {%>
<tr>
<td><%=list.get(i).getFirstName() %></td>
<td><%=list.get(i).getLastName() %></td>
<td><%=list.get(i).isGoldCustomer() %></td>
</tr>
<%}%>
</table>
위에 코드에 이 부분을 넣어보면 된다. 똑같이 작동되지만, 딱 봐도 지저분하다.
<%=%><%%> 가 너무 많아 for문이 어디서 시작하는지 끝나는지 모를 정도이다.
list 안의 데이터를 접근할 때에도 getter를 이용하여 접근해야 하고 코드가 길어지는 것이 눈에 보인다.
jsp에서는 c:forEach 태그를 쓰는게 훨씬 나을 것이다.
'Udemy' 카테고리의 다른 글
JSTL Core Tag -<choose> (0) | 2021.08.07 |
---|---|
JSTL Core Tag - <if> (0) | 2021.08.07 |
JSTL Core Tag-<forEach> 반복문 (0) | 2021.08.07 |
JSTL 다운로드, 사용법 (0) | 2021.08.06 |
JSP: Cookie 사용하기 예제 (0) | 2021.08.06 |