https://pabeba.tistory.com/162
JSTL 기본 문법 1 (param, getter&is 메서드 접근, if)
공용 index.jsp EL과 JSTL : View 영역에 해당되는 jsp 기술 jsp 내장객체 request : session : application (ServletContext) : EL Test1 EL Test2 EL Test3 JSTL if param (${param.~}) Test02Servlet @WebServlet("/Test02Servlet") public class Test02Se
pabeba.tistory.com
기본 문법 1 편을 보고 오면 조금 더 이해가 될 수 있습니다.
choose ~ when ~ otherwise
JAVA의 if ~ else if ~ else 구문과 같다고 보면 됩니다.
<body>
<div>
<%-- if ~ else if ~ else --%>
<c:choose>
<c:when test="${food.price>=20000}">
대단히 비쌈
</c:when>
<c:when test="${food.price>=15000}">
비쌈
</c:when>
<c:otherwise>
평범한 식사
</c:otherwise>
</c:choose>
</div>
</body>
food.price의 값을 변경해서 주면 그 조건에 맞는 값이 튀어나오게 됩니다. (food의 price는 servlet으로 보내주면 됩니다.)
forEach (${paramvalues.name})
@WebServlet("/Test07Servlet")
public class Test07Servlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String names[]= {"김민재","손흥민","이강인"};
request.setAttribute("nameArray", names);
ArrayList<String> list=new ArrayList<String>();
list.add("아이유"); list.add("송강호"); list.add("배두나");
request.setAttribute("starList", list);
request.getRequestDispatcher("step07-jstl-forEach-Array.jsp").forward(request, response);
}
}
servlet으로 다음과 같은 배열 2개를 보내줄 예정입니다.
첫 번째로는 축구선수 이름이 있는 배열,
두 번째로는 연예인 이름이 있는 배열입니다.
이 두 배열을 받아와서 for each 구문을 작성해보려고 합니다.
하나는 값을 나열하고, 하나는 input 박스 나열을 하려고 합니다.
<body>
<div>
${nameArray} <br><br>
<%--
jstl forEach : java for문에 해당
items : 배열 or 컬렉션
var : 요소를 담을 임시변수
--%>
<c:forEach items="${nameArray}" var="name">
${name}
</c:forEach>
<hr>
<form action="Test08Servlet">
<c:forEach items="${starList}" var="star">
<input type="checkbox" name="star" value="${star}">${star} <br>
</c:forEach>
<button type="submit" class="btn btn-primary">전송</button>
</form>
</div>
</body>
c:forEach 구문에서
items 는 servlet에서 보내주는 배열의 이름을 담는 곳이고
var 는 하나하나의 값을 어떻게 가져올 것인지를 담는 곳입니다.
<c:forEach items="${nameArray}" var="name">
${name}
</c:forEach>
그래서 저렇게 배열의 이름과 var의 name을 forEach 구문에 넣으면 축구 선수의 이름이 나오게 됩니다.
다음은 forEach 구문으로 input 박스를 만들어 보겠습니다.
<c:forEach items="${starList}" var="star">
<input type="checkbox" name="star" value="${star}">${star} <br>
</c:forEach>
이렇게 만들면 보내준 연예인들로 input 박스를 만들어옵니다.
그리고 연예인을 여러명 누르고 전송을 받으려면
<c:forEach items="${paramValues.star}" var="starName">
${starName}
</c:forEach>
${paramValues.star} 를 이용하여 배열을 받아올 수 있습니다.
또한 forEach 구문에서는 시작과 끝 번호를 정해서 그것만큼만 반복하게 할 수 있습니다.
JSP 파일에 다음과 같이 작성해보면
<c:forEach begin="1" end="5" var="page">
${page}
</c:forEach>
1 2 3 4 5 가 나타나는 것을 확인할 수 있습니다.
이렇게 시작과 끝 번호를 작성해서 자신이 나타내고 싶은 개수만큼 나타낼 수 있습니다.
소감
이것도 기본문법 1 번과 비슷한 소감입니다. java의 for 구문을 <%%>를 이용하여 복잡하게 사용하지 않아도 되는 것에 감사함을 느낍니다.
오늘은 여름이 왔다는 것을 느낀 날이였는데... 혹시 더위를 날릴만한 무언가가 있으시다면 추천해주시길 바랍니다.