본문 바로가기
JAVA

[Java&JSP] 달력 만드는 방법

by GoodDayDeveloper 2023. 2. 7.
반응형

 

웹 사이트의 달력 만드는 방법은 여러가지가 있습니다.

지난 포스팅에서는 자바스크립트를 이용한 달력 (FullCalendar) 을 생성해보았으며

이번에는 Java와 JSP 만으로 달력을 만드는 방법에 대해 알아보겠습니다.

아래는 구현 화면입니다.

 

 

 

 

 

JSP로 생성된 달력이 나타나며, 달력 위에 해당 표시되는 일정들이 나오는 것을 알 수 있습니다.

크게 아래와 같이 세가지로 나타나게 됩니다.

 

 

  • 현재월과 일정목록을 뽑는 작업
  • 공휴일을 출력하는 작업
  • JSP에서 달력을 그려주는 작업

 

 

생각보다 간단하니 천천히 알아보겠습니다.

 

 

 

https://chobopark.tistory.com/245

 

[JQuery] Fullcalendar 달력 구현 & 데이터 연동 (영상 有)

안녕하세요 오늘은 Fullcalendar란 라이브러리로 달력을 만들어보고 데이터도 연동해보겠습니다. 기능은 등록/수정/삭제/일정목록/다중 기간/기간 이동/ 등을 구현하였습니다. 아래는 영상입니다.

chobopark.tistory.com

 

 

 

 

 

 

 

CONTROLLER (Java)

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
@RequestMapping(value="/po/list.do",method = RequestMethod.GET)
public String  list(
        @ModelAttribute("searchVO")  ORDER_VO searchVO ,
        HttpServletRequest request,
        @RequestParam(required = false, value = "sYear"String sYear,
        @RequestParam(required = false, value = "sMonth"String sMonth,
        ModelMap model ) throws Exception {
 
 
    try{
 
        java.util.Calendar cal = java.util.Calendar.getInstance();
 
        //현재 년도, 월, 일
        int nYear = cal.get ( cal.YEAR );
        int nMonth = cal.get ( cal.MONTH ) + 1 ;
        int nDate = cal.get ( cal.DATE ) ;
 
        int iYear = nYear;
        int iMonth = nMonth;
 
        if(!StringUtils.isNullOrEmpty(sYear)) iYear = Integer.parseInt(sYear);
        if(!StringUtils.isNullOrEmpty(sMonth)) iMonth = Integer.parseInt(sMonth);
 
        //전월,다음월
        int preYear = iYear;
        int preMonth = iMonth - 1;
        int nextYear = iYear;
        int nextMonth = iMonth + 1;
        if(iMonth == 12){
            nextYear = iYear + 1;
            nextMonth = 1;
        }
 
        if(iMonth == 1){
            preYear = iYear - 1;
            preMonth = 12;
        }
 
        model.addAttribute("iYear",iYear);
        model.addAttribute("iMonth",iMonth);
        model.addAttribute("preYear",preYear);
        model.addAttribute("preMonth",preMonth);
        model.addAttribute("nextYear",nextYear);
        model.addAttribute("nextMonth",nextMonth);
 
 
 
        //공휴일 목록
        String iMonth2 = String.format("%02d", iMonth);
 
        Map<StringString> holidayList = getHolidayList(iYear + iMonth2);
 
        model.addAttribute("holidayList",holidayList);
 
 
        //출하일이 해당월인 일정목록
        searchVO.setPO_DATE(iYear + "-" + iMonth2);
        List<ORDER_VO> orderList = gnb01Lnb02Snb02Service.getOrderList(searchVO);
        model.addAttribute("orderList",orderList);
 
 
    }catch(Exception e){
        System.out.println("/po/list.do : " + e.toString());
    }
 
    return "tiles:bsite/po/list";
 
}
cs

 

 

 

달력을 넘길때 받아올 sYear와 sMonth를 파라미터 값으로 설정합니다.

여기서 중요한점은 초기 화면에서는 파라미터를 가져올 수 없기 때문에 required = false로 설정하여

Exception이 발생하지 않도록 합니다.

 

 

 

현재 년/월/일과 전월/다음월을 구한 다음,

공휴일 목록을 맵형태로 빼내줍니다. 

이때 JSP에서 사용하기 우해서 키값을 날짜값으로 설정하고, 

값을 지정 공휴일로 나타내어줍니다.

 

 

 

 

 

 

그리고 일정 목록을 리스트형태로 뽑아주기만 하면 됩니다.

 

 

 

 

 

 

 

SERVICEIMPL (Java)

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
public Map<StringString> getHolidayList(String yyyymm) throws Exception {
        // 검사년도
    int yyyy = Integer.parseInt(yyyymm.substring04 ));
 
    try {
        //공휴일 목록 갖고오기
        LoginVO user = (LoginVO)EgovUserDetailsHelper.getAuthenticatedUser();
        COM_CALENDAR_VO searchVO = new COM_CALENDAR_VO();
        searchVO.setFTR_CODE(user.getFtrCode());
        List<COM_CALENDAR_VO> list = gnb01Lnb02Snb02Service.getHolidayList(searchVO);
 
 
        String tmp01 = EgovDateUtil.toSolar(yyyy + "0101", StaticManager.getYun(yyyy + "01"));    //윤달여부
        String tmp02 = EgovDateUtil.toSolar(yyyy + "0815", StaticManager.getYun(yyyy + "08"));
 
        Map<StringString> holidayList = new HashMap<StringString>();
 
        holidayList.put(yyyy+StaticManager.preDays(tmp01), "설날");
        holidayList.put(tmp01, "설날");
        holidayList.put(yyyy+StaticManager.afterDays(tmp01), "설날");
        holidayList.put(yyyy+StaticManager.preDays(tmp02), "추석");
        holidayList.put(tmp02, "추석");
        holidayList.put(yyyy+StaticManager.afterDays(tmp02), "추석");
 
 
        for(COM_CALENDAR_VO vo : list){
 
            if("N".equals(vo.getCAL_TYPE())){
                //음력
                String tmpDate = EgovDateUtil.toSolar(yyyy + vo.getCAL_MONTH() + vo.getCAL_DAY() , StaticManager.getYun(yyyy + vo.getCAL_MONTH()));
                holidayList.put(tmpDate, vo.getCAL_TITLE());
 
            }else{
                //양력
                holidayList.put(yyyy + vo.getCAL_MONTH() + vo.getCAL_DAY(),  vo.getCAL_TITLE());
            }
        }
 
        return holidayList;
 
    } catch(Exception e) {
        e.printStackTrace();
        System.out.println("실패 getHolidayList : " + e.toString());
        throw e;
    }
}
cs

 

 

이곳은 공휴일을 출력해주는 메서드입니다.

우리나라는 양력과 음력이 존재하므로 조금의 계산법이 필요합니다.

우선 데이터 베이스에 아래와 같이 테이블을 만들어줍니다.

 

 

 

 

 

Y, N 값들은 음력 여부에 대한 기준값이며, 년도는 무시하시고 월/일만 입력하면 됩니다

 

 

공휴일의 목록을 가져와서 EgovDateUtil.toSolar로 음력날짜를 양력날짜로 변환시킵니다.

(위 코드는 전자정부프레임워크이지만 이 밖에 여러 라이브러리가 있기때문에 그것을 활용하시면 됩니다.)

 

 

설날/추석을 만들어 리스트 변수에 넣어주고,

반복문을 돌면서 음력을 나타내는 N값이라면 변환시켜줘서 리스트 변수에 담아줍니다.

 

 

 

 

 

 

반응형

 

 

 

 

JSP

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="ui" uri="http://egovframework.gov/ctl/ui"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%@ taglib prefix="tiles" uri="http://tiles.apache.org/tags-tiles"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ taglib prefix="validator" uri="http://www.springmodules.org/tags/commons-validator" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="aBtn" uri="/WEB-INF/authBtn.tld" %> 
<%@ page import="bsite.wsmes.vo.*" %>
<%@ page import="java.util.*" %>
<c:set var="pageUrl" value="${requestScope['javax.servlet.forward.request_uri']}" />
 
<%@page import="java.util.Calendar"%>
<%
    Calendar now = Calendar.getInstance();
    int year = now.get(Calendar.YEAR);
    int month = now.get(Calendar.MONTH)+1;
    
    String _year = request.getParameter("sYear");
    String _month = request.getParameter("sMonth");
    
    if(_year != null)
        year = Integer.parseInt(_year);
    
    if(_month != null)
        month = Integer.parseInt(_month);
    
    now.set(year, month-11);    //출력할 년도, 월로 설정
    
    year = now.get(Calendar.YEAR);    //변화된 년, 월
    month = now.get(Calendar.MONTH) + 1;
    
    int end = now.getActualMaximum(Calendar.DAY_OF_MONTH);    //해당월의 마지막 날짜
    int w = now.get(Calendar.DAY_OF_WEEK);    //1~7(일~토)
%>
 
<div class="pannel_body">
    <!-- 달력 -->
    <div class="table_cal_wrap">
        <div class="table_cal_title">
            <div class="prev_month">
                <a href="<c:out value="${pageUrl}" />?sYear=<c:out value="${preYear}" />&sMonth=<c:out value="${preMonth}" />"><span>&lt;&lt;</span> </a>
            </div>
        <div class="title">
            <%=year %>년 <%=month %>
        </div>
            <div class="next_month">
                <a href="<c:out value="${pageUrl}" />?sYear=<c:out value="${nextYear}" />&sMonth=<c:out value="${nextMonth}" />"><span>&gt;&gt;</span></a> 
            </div>
        </div>
        
        <table class="table_cal" width="100%" cellspacing="0" summary="">
            <caption>달력</caption>
            <colgroup>
                <col width="14.3%" />
                <col width="14.3%" />
                <col width="14.3%" />
                <col width="14.3%" />
                <col width="14.3%" />
                <col width="14.3%" />
                <col width="14.3%" />
            </colgroup>
            <thead>
                <tr>
                    <th class="first"><span class="txt_red">일(Sun)</span></th>
                    <th>월(Mon)</th>
                    <th>화(Tue)</th>
                    <th>수(Wed)</th>
                    <th>목(Thu)</th>
                    <th>금(Fri)</th>
                    <th class="last"><span class="txt_blue">토(Sat)</span></th>
                </tr>
            </thead>
            <tbody>
                <%
                    List<ORDER_VO> orderList = (ArrayList<ORDER_VO>)request.getAttribute("orderList");
                    
                
                    Map<StringString> holidayList = (Map<StringString>)request.getAttribute("holidayList");
                    String holidayName = "";
                    
                        int newLine = 0;
                        //1일이 어느 요일에서 시작하느냐에 따른 빈칸 삽입
                        out.println("<tr>");
                        for(int i=1; i<w; i++)
                        {
                            out.println("<td>&nbsp;</td>");
                            newLine++;
                        }
                        
                        String fc, bg;
                        for(int i=1; i<=end; i++)
                        {
                            holidayName = "";
                            fc = (newLine == 0)?"txt_red":(newLine==6?"txt_blue":"#000000");
    
                            String month2 = String.format("%02d", month);
                            String day2 = String.format("%02d", i);
                            String date2 = year + month2 + day2;
                            String date3 = year + "-" + month2 + "-" + day2;
                            
                            if(holidayList.get(date2) != null){
                                holidayName = holidayList.get(date2);
                                fc = "txt_red";
                            }
                            %>
                            
                            <td> 
                                <span class="<%=fc%>"> 
                                <a href="${pageContext.request.contextPath}/search/list.do?searchPodate=<%=date3 %>"><%=%></a>
                                <%=holidayName %>  </span> 
                           
                                <ul>
                                    <%
                                    for (int j = 0; j < orderList.size(); j++) {
                                        ORDER_VO vo = new ORDER_VO();
                                        vo = (ORDER_VO)orderList.get(j);
                                        if(date3.equals(vo.getPO_DATE())){
                                    %>
                                        <li class='order'><a href="${pageContext.request.contextPath}/search/list.do?searchPoIdx=<%=vo.getPO_IDX() %>">
                                        <%=vo.getCI_NAME()%> <%=vo.getPO_PROD_NM()%> <%=vo.getPO_TYPE_NM()%> <%=vo.getPO_STATE_NM()%> 
                                        </a></li>
                                    <%
                                        }
                                    }
                                    %>
                                </ul>
                                
                            </td>
                            <%
                            
                            newLine++;
                            if(newLine == 7 && i != end)
                            {
                                out.println("</tr>");
                                out.println("<tr>");
                                newLine = 0;
                            }
                        }
                        
                        while(newLine>0 && newLine<7)
                        {
                            out.println("<td bgcolor='ffffff'>&nbsp;</td>");
                            newLine++;    
                        }
                        out.println("</tr>");
                    %>
                
                
            </tbody>
        </table>
    </div>
    <!--// 달력 END -->
</div>    
cs

 

 

마지막으로 달력을 생성해주는 JSP입니다.

 

윗 부분에서 자바코드를 넣어줘서 출력할 년도,월을 설정해줍니다.

여기서 중요한 부분은 end와 w 변수로써

Calendar의 메서드를 이용하여 값을 넣어줍니다.

end는 해당월의 마지막 날짜이며, w는 달력에서 1일로 시작할 요일을 찾는 부분인거죠

 

 

tbody 부분부터 본격적으로 달력 생성에 들어갑니다.

일정 리스트와 공휴일 리스트를 만들어주고,

newLine 변수를 통해 1일이 어느 요일에 시작하는지 체크해준 다음,

그 이후부터 해당월의 마지막 일자를 기준으로 반복문을 돌면서

일정과 공휴일 값을 넣어줍니다.

 

 

반복문 마지막에 newLine 값이 7이면 다음 행으로 넘어갈 수 있도록

태그를 닫아주고 초기화 시켜줍니다.

 

 

반복문을 나와서 달력 마지막 부분을 빈칸으로 채워주면 끝입니다.

 

 

 

 

 

 

JSP 특성상 코드가 길어 간단한 설명으로 해깔릴 수 있겠지만

자세히 들여다보시면 충분히 이해하실 수 있으리라 생각합니다.

참고하시고 도움이 되셨으면 좋겠습니다~

 

 

 

 

 

 

 

 

https://chobopark.tistory.com/245

 

[JQuery] Fullcalendar 달력 구현 & 데이터 연동 (영상 有)

안녕하세요 오늘은 Fullcalendar란 라이브러리로 달력을 만들어보고 데이터도 연동해보겠습니다. 기능은 등록/수정/삭제/일정목록/다중 기간/기간 이동/ 등을 구현하였습니다. 아래는 영상입니다.

chobopark.tistory.com

 

 

 

반응형

댓글