본문 바로가기

[JSP]

[JSP]11월 4일 EL표현식과 JSTL 제어문(taglib)

JSP_EL_JSTL 프로젝트를 생성하자.

자바 리소스 안에 controller 라는 패키지를 생성하고, MyServlet 클래스생성.

서블릿 만들기

1. HttpSErvlet을 상속

2. 요청처리 메소드를 오버라이드(doget, dopost)

3. 처리할 URL정의와 서블릿 등록(@WebServlet or web.xml에 <Servlet>)


*get방식과 post방식 각각 처리 메소드가 따로 있어서 불편하니까 doGet, doPost와 원형이 같은 메소드를 정의

해서 각각 doProc를 호출하게 만들었다.


@WebServlet("*.do")

public class MyServlet extends HttpServlet{

public void doProc(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

//서블릿 요청 처리 메소드

//1. 요청 URL 구분

//2. 적정한 로직 처리

//3-1. attribute에 필요한 데이터 담아서 forward

//3-2. 혹은 어떤 다른 요청으로 리다이렉트

String uri = req.getRequestURI();//요청 URI를 얻어와서

String contextPath = req.getContextPath();//이건 웹어플리켜이션 주소

if(uri.equals(contextPath + "/hello.do"))

{

//인사말 구해와서 attribute에 실어서 hello.jsp로 포워드

List<String> list = new ArrayList<String>();

list.add("안녕하세요");

list.add("hello");

list.add("你好");

list.add("こんにち");

list.add("봉주르");

req.setAttribute("helloList", list);

req.getRequestDispatcher("hello.jsp").forward(req, resp);

}

else if(uri.equals(contextPath + "/whatTime.do"))

{

//시간 구해와서 attribute에 실어서 whatTime.jsp로 포워드

Date date = new Date();

req.setAttribute("time", date);

req.getRequestDispatcher("whatTime.jsp").forward(req, resp);

}

else if(uri.equals(contextPath + "/elTest.do"))

{

Member member = new Member();

member.setId(1004);

member.setName("홍길동");

req.setAttribute("mem", member);

//hashmap도 모델클래스(케터 세터를 가진 구조체)와 유사하게 동작한다.

Map<String, String> hashMap = new HashMap<String, String>();

hashMap.put("father", "아빠");

hashMap.put("mother", "엄마");

hashMap.put("daughter", "딸");

hashMap.put("son", "아들");

req.setAttribute("family", hashMap);

req.getRequestDispatcher("elTest.jsp").forward(req, resp);

}

}

@Override

protected void doGet(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

// super.doGet(req, resp);

doProc(req, resp);

}


@Override

protected void doPost(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

// super.doPost(req, resp);

doProc(req, resp);

}

}


EL표현식을 사용하면 JSP페이지에서 attribute를 쉽게 써내다가 사용할 수 있다.

whatTime.do 요청이 들어왔을때

현재시간을 attribute 담아서 포워드 하면 whatTime.jsp에서 EL표현식을 이용해 시간을 출력해보자.


whatTime.jsp

<body>

현재시간은 ${time }

</body>

EL표현식을 이용해 attribute의 값을 출력.



그다음으로

만약 attribute의 값이 객체일때, 리스트일때, Map일때 는 어떻게 출력하는지 보자.

위에 

else if(uri.equals(contextPath + "/elTest.do"))

{

Member member = new Member();

member.setId(1004);

member.setName("홍길동");

req.setAttribute("mem", member);

//hashmap도 모델클래스(케터 세터를 가진 구조체)와 유사하게 동작한다.

Map<String, String> hashMap = new HashMap<String, String>();

hashMap.put("father", "아빠");

hashMap.put("mother", "엄마");

hashMap.put("daughter", "딸");

hashMap.put("son", "아들");

req.setAttribute("family", hashMap);

req.getRequestDispatcher("elTest.jsp").forward(req, resp);

}

이 요청에다가 모델클래스 하나랑 HashMap하나랑 attribute에 실어서 elTest.jsp에서 출력해보자.

모델클래스를 간단하게 하나 만들어준다 멤버를 private으로 감추고 getter/setter 생성.

저는 멤버로 id, name 두개 만들었습니다.


elTest.jsp

<body>

회원의 아이디 : ${ mem.id }<br>  

회원의 이  름 : ${ mem.name }<br>


mother는 한국말로 : ${family.mother }<br>

father는 한국말로 : ${family.father }<br>

daughter는 한국말로 : ${family.daughter }<br>

son은 한국말로 : ${family.son }

</body>

여기서 그냥 attribute이름.변수 하면된다. 단 getter가 있을때만 가능하다.



attribute가 list나 배열일때 꺼내는 방법을 보자.

hello.do에서는 attrubute에 각가지 나라의 인사말을 리스트 형태로 담아서 hello.jsp로 보내보자.

if(uri.equals(contextPath + "/hello.do"))

{

//인사말 구해와서 attribute에 실어서 hello.jsp로 포워드

List<String> list = new ArrayList<String>();

list.add("안녕하세요");

list.add("hello");

list.add("你好");

list.add("こんにち");

list.add("봉주르");

req.setAttribute("helloList", list);

req.getRequestDispatcher("hello.jsp").forward(req, resp);

}


hello.jsp 에서 EL표현식으로 꺼내보면

<body>

한국 : ${helloList[0] }<br>

영어 : ${helloList[1] }<br>

중국 : ${helloList[2] }<br>

일본 : ${helloList[3] }<br>

프랑스 : ${helloList[4] }<br>

</body>


확인해보실때 hello.do로 주소 입력해주셔야됩니다.

Servlet에서 hello.do로 요청왔을때 로직처리~ 해주셨으니까.

이런식으로 나온다~



EL 표현식은 각 종 자료형(list,map,객체)의 표현에만 집중하고, 제어구조에 대해서는 JSTL라이브러리를 활용하시면 됩니다.


JSTL 반복문을 보기 앞서 JSTL → Tag Library 를 다운받아서

WEB-INF → lib 안에 복사 붙혀놓기 해주셔야됩니다.


라이브러리를 추가해주시고~~

JSTL에서 제어문을 제공하는 태그는 c태그

jsp태그는 원래 사용할 수 있지만 그 외 태그라이브러리는 사용하고 싶으면 임포트 해야된다.



c태그

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

JSTL c태그를 이용한 반복문 <br>

<c:forEach var="i" begin="1" end="9" step="1">

2 * ${i } = ${i * 2 }<br>

</c:forEach>

var="반복계수" begin="반복계수 시작값" end="반복계수 끝값" step="반복계수 증가값"




산술증감에 의한 반복문은 이렇게 쓰시면 됩니다.


자료구조 탐색에는


JSTL c태그를 이용한 반복문(자료구조 담색 : list, set ,,,)<br>

<c:forEach var="hello" items="${helloList }">

 ${hello }<br>

</c:forEach>




if문은 whatTime.jsp 에서 해보겠습니다.

☆c태그 임포트 해주셔야되요!

<c:if test="${time.hours < 12 }">

오전이네요

</c:if>

딱 조건이 맞을때만 구분하는 단순 조건문은 c:if



<c:choose>

<c:when test="${time.hours < 12 }">

오전이네요

</c:when>

<c:when test="${time.hours == 12 }">

정오

</c:when>

<c:otherwise>

오후네요

</c:otherwise>

</c:choose>

if else는 choose

when - otherwise


if elseif elseif elseif else 이런식으로 계속 내려가는 else if는

choose

when when ... otherwise