프로그래밍/전자정부프레임워크(eGov)

부트스트랩 테이블과 동적 JSTL 조지기 - (1)

Jay Tech 2017. 3. 5. 00:51
반응형

부트스트랩은 웹디자인을 쉽게 하기 위해서 미리 정의된 css,javascript를 모은 강력한 front-end 프레임워크이다.


부트스트랩 테이블을 이용하여 데이터베이스에서 값을 가지고와 jstl로 뿌려보자. 


제일 먼저 필요한건 당연히 테이블이 되겠다.





그냥 이런식이다. 이 테이블이 어떻게 만들어졌는지부터 보자.



          <div class="col-md-12">

                <div class="card">

                    <div class="header">

                        <h4 class="title">테이블 테스트</h4>

                        <p class="category">부트스트랩 테이블입니다~</p>

                    </div>

                    <div class="content table-responsive table-full-width">

                        <table class="table table-hover table-striped">

                            <thead>

                                <th>ID</th>

                            <th>Name</th>

                            <th>Salary</th>

                            <th>Country</th>

                            <th>City</th>

                            </thead>

                            <tbody>

                            <c:forEach items="${list}" var="list" varStatus="status">

                            <tr>

                              <td><c:out value="${list.id}"/></td>

                              <td><c:out value="${list.userName}"/></td>

                              <td><c:out value="${list.age}"/></td>

                              <td><c:out value="${list.country}"/></td>

                              <td><c:out value="${list.etc}"/></td>

                              </tr>

                            </c:forEach>

                            </tbody>

                        </table>

                   </div>

               </div>

           </div>  



이렇게 되어 있다.


먼저 <div class="col-md-12">가 의미하는 것은 부트스트랩의 그리드 시스템을 이용한다는 것이다. 이 시스템은 사용자크기에 따라 (즉 기기의 크기) 유동적으로 변하는 시스템이다.


모바일폰(매우 작은기기)    .col-xs-

태블릿(작은기기)    .col-sm-

데스크탑(중간기기)    .col-md-

더 큰 데스크탑(큰기기)    .col-lg-


문제의 col-md-12는 데스크탑크기에서 적용가능한 테이블로 12의 크기를 가지고 있는 것이다. 여기서 12란 나뉘어지는 비율을 말한다. 크기가 클수록 차지하는 비율이 보다시피 높아진다.


col-xs-12 .col-md-8
.col-xs-6 .col-md-4
.col-xs-6 .col-md-4
.col-xs-6 .col-md-4
.col-xs-6 .col-md-4
.col-xs-6
.col-xs-6









자 일단 저런 사이즈를 갖는 div를 생성했다.

두 번째, <div class="card">는 부트스트랩 카드를 만드는 것이다. 맨 위에 사진을 보면 회색 바탕의 흰색 표가 올라와 있는 것을 알 수 있다. 카드를 쓰지 않으면 그냥 회색 바탕에 경계가 없는 표가 만들어질 것이다.



<div class="header">는 말 그대로 헤더를 만드는 것이다. 지금 표 설명이 되어있는 부분에 강조가 들어갈 것이다. 다음 진짜 테이블에 관한 부분을 보자.


<div class="content table-responsive table-full-width"> 자 이쪽은 반응형 테이블을 만들고 너비를 꽉차게 만들겠다고 선언한다.

<table class="table table-hover table-striped"> 테이블의 속성을 정의하는데 hover는 테이블 칼럼에 마우스를 대면 색이 바뀌는 효과이고 striped는 격줄로 색이 칠해져 있는 테이블을 만들겠다는 것이다.


thead tbody등 테이블을 만드는 기본적인 것들은 생략하겠다.


그럼 이로써 테이블이 만들어 지게 된다. 저기 c:forEach는 나중에 설명할 것이다.



이제 테이블을 만들었으니 테이블에 값을 넣어야 한다. 그 값을 데이터베이스에서 가져와 보겠다. 그냥 가져오는것은 정적 테이블이고 사용자가 선택한 것만 보여지게 하려면 동적 테이블을 만들어야 한다.


동적 테이블을 만들기 위해 버튼을 달아 보겠다. 버튼은 이런식으로 테이블 위에 달것이다.




버튼을 단 코드를 보자.



<div class="col-md-12">

            <button class="btn btn-primary btn-fill btn-wd" id="primaryBtId">버튼</button>

            <p>체크박스 체크된 것들만 표에 보여지기</p>          

            <form id="frmReq2" method="get" action="welcomeWeb.do" class="form-horizontal">                        

       <label class="checkbox checkbox-inline">

           <input type="checkbox" name="myBtn" data-toggle="checkbox" value="아이디">아이디

       </label>

       <label class="checkbox checkbox-inline">

           <input type="checkbox" name="myBtn" data-toggle="checkbox" value="이름">이름

       </label>

       <label class="checkbox checkbox-inline">

           <input type="checkbox" name="myBtn" data-toggle="checkbox" value="나이">나이

       </label>

       

       <label class="checkbox checkbox-inline">

           <input type="checkbox" name="myBtn" data-toggle="checkbox" value="국가">국가

       </label>

       

       <label class="checkbox checkbox-inline">

           <input type="checkbox" name="myBtn" data-toggle="checkbox" value="기타">기타

       </label>

</form>

                        </div>



위와 같이 col-md로 화면 분할을 하고 전송을 위한 부트스트랩 버튼을 단다.

<button class="btn btn-primary btn-fill btn-wd" id="primaryBtId">버튼</button> 이렇게 버튼을 달고 제일 중요한 폼 태그를 만든다.


<form id="frmReq2" method="get" action="welcomeWeb.do" class="form-horizontal"> 

form의 아이디는 frmReq2이고 get으로 보내고 url맵핑은 welcomeWeb.do로 한다. 자 이제 폼태그 밑의 버튼들을 위와 같이 달아준다면 컨트롤러에서 RequestMapping에 welcomeWeb.do로 받아 처리해주면 된다. 


중요한점은 컨트롤러에서 jsp쪽에서 넘긴 버튼을 가져오려면 jsp input태그의 name이 필요하다. 즉 여기서는 myBtn으로 name을 통일 시켰다. 이로써 컨트롤러에서 myBtn으로 값을 가져올 수 있다는 것이다. 컨트롤러 코드를 보자.




@RequestMapping(value="welcomeWeb.do")

public String initWelcomeWeb(HttpServletRequest request, ModelMap model) throws Exception {

Map<String, Object> paramMap = new HashMap<String, Object>();


// 버튼

//String[] btns = request.getParameterValues("myBtn");

System.out.println(request.getParameterNames());

Enumeration<String> attr = request.getParameterNames(); // <-- 열거형 인터페이스

while(attr.hasMoreElements()) { 

String attrName = attr.nextElement(); // 화면에서 보낸 name이 찍힌다.

if(attrName.equals("myBtn")) {

String[] arr = request.getParameterValues("myBtn"); // 이거는 버튼의 이름

//파일업로드할때 쓰임

for(int i=0; i<arr.length; i++) {

System.out.println(arr[i]);

}

model.addAttribute("clickButtons", arr);

System.out.println(arr);

}

}


return "welcomeWeb/welcomeWeb.tiles";

}




Enumeration<String> attr = request.getParameterNames(); 부분을 보자.


여기서 Enumeration을 보고 가야 한다. Enumeration은 인터페이스인데 객체들을 하나씩 처리할 수 있는 메소드를 제공하는 Collection 이다. 어떤 타입이든 다 때려박아도 흡수한다.


public interface Enumeration<E>

An object that implements the Enumeration interface generates a series of elements, one at a time.
Successive calls to the nextElement method return successive elements of the series.

For example, to print all elements of a Vector<E> v:

   for (Enumeration<E> e = v.elements(); e.hasMoreElements();)
       System.out.println(e.nextElement());

Methods are provided to enumerate through the elements of a vector, the keys of a hashtable, and the values in a hashtable.

Enumerations are also used to specify the input streams to a SequenceInputStream.

NOTE: The functionality of this interface is duplicated by the Iterator interface. In addition, Iterator adds an optional remove operation, and has shorter method names.

New implementations should consider using Iterator in preference to Enumeration.

Since:
JDK1.0

메소드 종류를 보자.


  • hasMoreElements

    boolean hasMoreElements()
    Tests if this enumeration contains more elements.
    Returns:
    true if and only if this enumeration object contains at least one more element to provide; false otherwise.

  • nextElement

    E nextElement()
    Returns the next element of this enumeration if this enumeration object has at least one more element to provide.
    Returns:
    the next element of this enumeration.
    Throws:
    NoSuchElementException - if no more elements exist.

여기서 둘 다 쓰인다.



getParameterNames를 보자. 스트링 객체의 열거형을 반환한다고 되어 있다. 그러므로 당연히 열거형으로 받았다.


getParameterNames

java.util.Enumeration<java.lang.String> getParameterNames()
Returns an Enumeration of String objects containing the names of the parameters contained in this request. If the request has no parameters, the method returns an empty Enumeration.

Returns:
an Enumeration of String objects, each String containing the name of a request parameter; or an empty Enumeration if the request has no parameters




String attrName = attr.nextElement(); 부분을 보면 attr의 nextElement가 존재하면 attrName에 넣는다. 무엇을? 화면에서 보낸 name을 넣는다. 즉, jsp에서 버튼 name을 myBtn이라고 지었다. 그러므로 myBtn이 들어가게 된다.


String attrName = attr.nextElement(); 다음 열거형을 받는다.


if(attrName.equals("myBtn")) {

String[] arr = request.getParameterValues("myBtn");  이 부분은 다음열거형을 받은 것의 이름이 myBtn이라면 getParameterValues를 실행한다.


getParameterValues는 String배열을 리턴한다. 즉, 체크된 버튼의 배열이 들어오게 된다. 하나라면 하나만 들어오겠다.


마지막에 model.addAttribute("clickButtons", arr); 를 해주며 뷰로 던져버린다. 뷰(jsp)에서는 이 키값 ("clickButtons")을 이용해서 화면에 뿌릴수 있게 된다. 이것은 다음 포스팅때 해보자.

반응형