ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [HTML/CSS] 캘린더 만들기 (+ 일정 추가기능)
    º Language º/JavaScript 2023. 6. 4. 23:35

    1. 캘린더의 기본적인 틀을 생성한다.

    <body>
    	<h1></h1>
    	<button id="btnPrev">이전달</button>
    	<button id="btnNext">다음달</button>
    	<table border="1" width="50%">
    		<thead>
    			<tr>
    				<th>일</th>
    				<th>월</th>
    				<th>화</th>
    				<th>수</th>
    				<th>목</th>
    				<th>금</th>
    				<th>토</th>
    			</tr>
    		</thead>
    		<tbody></tbody>
    	</table>	
    	<hr>
    	<div id="result"></div>
    	일정추가 : <input type="text" id="event_content">
    	<button id="btnAdd">추가</button>
    	<ul id="event_list"></ul>
    </body>

     

     

    2. 달력을 만들기 위한 코드를 JavaScript로 작성한다.

    	var thisYear;
    	var thisMonth;
    	
    	var calendar = function(year, month){
    		// 달력을 생성하는 함수
    		thisYear= year;
    		thisMonth = month;
    		
    		var start = new Date(year,month,1);
    		var day = start.getDay();
    		
    		var last = new Date(year, month+1, 0);
    		var lastDate = last.getDate();
    			
    		$("h1").html(year+"년 "+ (month+1)+"월");
    		
    		var str = "<tr>";
    		
    		for(j=1;j<=day;j++){
    			str += "<td></td>";
    		}
    		
    		for(i=1; i<=lastDate; i++){
    			str += "<td>"+i+"</td>";
    			if((i+day) % 7== 0){
    				str += "</tr><tr>";
    			}
    		}
    		str += "</tr>";
    		$("tbody").html(str);
    		
    		loadDateInMonth();
    	}
    	
    	var today = new Date();
    	var year = today.getFullYear();
    	var month = today.getMonth();
    	calendar(year, month);

     

     

     

    3. 일정 추가 기능을 위해 테이블 및 시퀀스를 생성한다. (Oracle)

    //테이블 생성
    create table schedule(
    no number primary key,
    event_date date,
    event_content varchar2(200)
    );
    
    //시퀀스 생성
    create sequence seq_schedule;
    
    // 추가 SQL 예시
    insert into schedule values(seq_schedule.nextval, to_date('2023/05/01','yyyy/mm/dd'),
    '새벽강변마라톤대회');
    
    // 조회 SQL 예시
    select to_char(event_date,'dd') from schedule where to_char(event_date,'yyyy/mm') ='2023/05';

     

    4. 일정 추가 기능을 위한 VO, DAO를 생성한다. (VO -> 맴버변수, 생성자, getter/setter 만들기) 

    public class ScheduleDAO {
    	
        // 해당 월의 날짜 목록을 가져오는 메서드
    	public ArrayList<String> listDate(String date){
    		String sql = "select distinct to_char(event_date, 'dd') "
    				+ "from schedule "
    				+ "where to_char(event_date, 'yyyy/mm') = ?";
    		ArrayList<String> list = new ArrayList<String>();
    		try {
    			Connection conn = ConnectionProvider.getConnection();
    			PreparedStatement pstmt = conn.prepareStatement(sql);
    			pstmt.setString(1, date);
    			ResultSet rs = pstmt.executeQuery();
    			while(rs.next()) {
    				list.add(rs.getString(1));
    			}
    			ConnectionProvider.close(conn, pstmt, rs);
    		}catch (Exception e) {
    			System.out.println("예외발생:"+e.getMessage());
    		}
    		return list;
    	}
    	
    	// 일정 삭제 메서드
    	public int deleteSchedule(int no) {
    		int re = -1;
    		String sql = "delete schedule where no=?";
    		try {
    			Connection conn = ConnectionProvider.getConnection();
    			PreparedStatement pstmt = conn.prepareStatement(sql);
    			pstmt.setInt(1, no);
    			re=pstmt.executeUpdate();
    			ConnectionProvider.close(conn, pstmt, null);
    		}catch (Exception e) {
    			System.out.println("예외발생:"+e.getMessage());
    		}
    		return re;
    	}
    	
        // 특정 날짜의 일정 목록을 가져오는 메서드 
    	public ArrayList<ScheduleVO> findByEventDate(String event_date){
    		ArrayList<ScheduleVO> list = new ArrayList<ScheduleVO>();
    		try {
    			String sql = "select * from schedule where event_date = ?";
    			Connection conn = ConnectionProvider.getConnection();
    			PreparedStatement pstmt = conn.prepareStatement(sql);
    			pstmt.setString(1, event_date);
    			ResultSet rs = pstmt.executeQuery();
    			while(rs.next()) {
    				list.add(new ScheduleVO(rs.getInt(1), rs.getString(2), rs.getString(3)));
    			}
    			ConnectionProvider.close(conn, pstmt, rs);
    		}catch (Exception e) {
    			System.out.println("예외발생:"+e.getMessage());
    		}
    		return list;
    	}
    	
    	// 일정 추가 메서드
    	public int insert(ScheduleVO s) {
    		int re = -1;
    		String sql = "insert into schedule values(seq_schedule.nextval,?,?)";
    		try {
    			Connection conn = ConnectionProvider.getConnection();
    			PreparedStatement pstmt = conn.prepareStatement(sql);
    			pstmt.setString(1, s.getEvent_date());
    			pstmt.setString(2, s.getEvent_content());
    			re = pstmt.executeUpdate();
    			ConnectionProvider.close(conn, pstmt, null);
    		}catch (Exception e) {
    			System.out.println("예외발생:"+e.getMessage());
    		}
    		return re;
    	}
    }

     

     

    5. JSP파일에 json형식으로 서버에 데이터를 요청하여  불러온다.

    (서로다른 컴퓨터끼리 데이터를 주고 받는 형식- json, xml)

     

    //listDate JSP (해당 월의 날짜 불러오기)
    <%
    	String date = request.getParameter("date");
    	System.out.println(date);
    	ScheduleDAO dao = new ScheduleDAO();
    	ArrayList<String> list = dao.listDate(date);
    	Gson gson = new Gson();
    	out.print(gson.toJson(list));
    %>
    
    //listSchedule JSP (특정 날짜의 일정 불러오기)
    <%
    	String event_date = request.getParameter("event_date");
    	event_date = event_date.substring(0, event_date.indexOf("<div"));
    	System.out.println(event_date);
    	ScheduleDAO dao = new ScheduleDAO();
    	ArrayList<ScheduleVO> list = dao.findByEventDate(event_date);
    	Gson gson = new Gson();
    	out.print(gson.toJson(list));
    %>
    
    //deleteSchedule JSP (특정 날짜의 일정 추가하기)
    <%
    	String event_date = request.getParameter("event_date");
    	String event_content = request.getParameter("event_content");
    	ScheduleVO sv = new ScheduleVO(0,event_date,event_content);
    	ScheduleDAO dao = new ScheduleDAO();
    	int re= dao.insert(sv);
    	out.print(re);
    %>
    
    //deleteSchedule JSP (특정 날짜의 일정 삭제하기)
    <%
    	String event_date = request.getParameter("event_date");
    	String event_content = request.getParameter("event_content");
    	ScheduleVO sv = new ScheduleVO(0,event_date,event_content);
    	ScheduleDAO dao = new ScheduleDAO();
    	int re= dao.insert(sv);
    	out.print(re);
    %>

     

    6. 각 버튼의 기능과 CSS를 추가하여 코드를 완성한다.

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <style type="text/css">
    /* 스타일을 지정하는 CSS 코드 */
    th {
    	background: yellow;
    }
    
    .mark{
    	color: red;
    	float:right;
    	margin-right: 10px;
    }
    
    .td:active{
    	background: pink;
    }
    
    .active{
    	background: orange;
    }
    
    </style>
    <title>Insert title here</title>
    <script type="text/javascript" src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
    <script type="text/javascript">
    	$(function(){
    javascript
    Copy code
    	var loadDateInMonth = function(){
    		// 월의 일정을 로드하는 함수
    		// thisMonth가 10보다 작으면 앞에 0을 붙이고 그렇지 않으면 그대로 사용
    		var str = "";
    		if(thisMonth < 10){
    			str += "0"+thisMonth;
    		}else{
    			str += thisMonth;
    		}
    		var data = {date:str};
    		$.ajax({
    			url:"listDate.jsp",
    			data: data,
    			success:function(arr){
    				
    				// 각 td 요소를 반복하면서 일정과 비교하여 표시
    				$("td").each(function () {
    					var a = eval($(this).html());
    					for(i=0;i<arr.length;i++){
    						var b = eval(arr[i]);
    						if(a==b){
    							// 일정이 있는 경우 해당 td에 빨간 별표(*) 추가
    							var div = $("<div></div>").html("*").addClass("mark");
    							$(this).append(div);
    						}
    					}
    				})
    			}
    		})
    	}
    	
    	$("#event_list").on("dblclick","li",function(){
    		// 일정 항목을 더블 클릭하면 삭제
    		var no = $(this).attr("no");
    		var data = {no:no};
    		
    		$.ajax({
    			url: "deleteSchedule.jsp",
    			data: data,
    			success: function(arr){
    				loadSchedule();
    			}
    		})
    	});
    	
    	var loadSchedule= function(){
    		// 일정을 로드하는 함수
    		$("#event_list").empty();
    		
    		var data = {event_date:event_date};
    		
    		$.ajax({
    			url:"listSchedule.jsp",
    			data:data,
    			success:function(arr){
    				$.each(arr, function(){
    					var li = $("<li></li>").html(this.event_content);
    					$(li).attr("no",this.no);
    					$("#event_list").append(li);
    					
    				});
    			}
    		});
    	}
    	
    	var event_date;
    	$(document).on("click", "td", function(){
    		// td 요소를 클릭하면 해당 일자의 일정을 표시
    		var thisDate = $(this).html();			
    		var str = thisYear+"/";
    		if(thisMonth < 10){
    			str += "0"+thisMonth+"/";
    		}else{
    			str += thisMonth+"/";
    		}
    		
    		if(thisDate < 10){
    			str += "0"+thisDate;
    		}else{
    			str += thisDate; 
    		}
    		event_date = str;
    		$("#result").html(str);
    		$(this).addClass("high_light");
    		loadSchedule();
    		
    	});
    	
    	var thisYear;
    	var thisMonth;
    	
    	var calendar = function(year, month){
    		// 달력을 생성하는 함수
    		thisYear= year;
    		thisMonth = month;
    		
    		var start = new Date(year,month,1);
    		var day = start.getDay();
    		
    		var last = new Date(year, month+1, 0);
    		var lastDate = last.getDate();
    			
    		$("h1").html(year+"년 "+ (month+1)+"월");
    		
    		var str = "<tr>";
    		
    		for(j=1;j<=day;j++){
    			str += "<td></td>";
    		}
    		
    		for(i=1; i<=lastDate; i++){
    			str += "<td>"+i+"</td>";
    			if((i+day) % 7== 0){
    				str += "</tr><tr>";
    			}
    		}
    		str += "</tr>";
    		$("tbody").html(str);
    		
    		loadDateInMonth();
    	}
    	
    	var today = new Date();
    	var year = today.getFullYear();
    	var month = today.getMonth();
    	calendar(year, month);
    	
    	$("#btnNext").click(function(){
    		// 다음달 버튼 클릭 시 다음달로 이동
    		thisMonth++;
    		if(thisMonth>11 ){
    			thisYear++;
    			thisMonth=0;				
    		}
    		calendar(thisYear, thisMonth);			
    	});
    	
    	$("#btnPrev").click(function(){
    		// 이전달 버튼 클릭 시 이전달로 이동
    		thisMonth--;
    		if(thisMonth < 0 ){
    			thisYear--;
    			thisMonth=11;				
    		}
    		calendar(thisYear, thisMonth);			
    	});
    	
    	$("#btnAdd").click(function(){
    		// 일정 추가 버튼 클릭 시 일정 추가
    		var data = 
    			{
    				event_date:event_date, 
    				event_content:$("#event_content").val()
    			};
    		
    		$.ajax({
    			url:"insertSchedule.jsp",
    			data:data,
    			success:function(re){
    				console.log(re);
    				loadSchedule();
    			}
    		})
    	});
    	
    })
    </script>
    </head>
    <body>
    	<h1></h1>
    	<button id="btnPrev">이전달</button>
    	<button id="btnNext">다음달</button>
    	<table border="1" width="50%">
    		<thead>
    			<tr>
    				<th>일</th>
    				<th>월</th>
    				<th>화</th>
    				<th>수</th>
    				<th>목</th>
    				<th>금</th>
    				<th>토</th>
    			</tr>
    		</thead>
    		<tbody></tbody>
    	</table>	
    	<hr>
    	<div id="result"></div>
    	일정추가 : <input type="text" id="event_content">
    	<button id="btnAdd">추가</button>
    	<ul id="event_list"></ul>
    </body>
    </html>
Coder yein