ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 스케줄러 (Spring + MyBatis) - 일정 추가 구현
    취업용 Spring 프로젝트/기능 내역 2019. 7. 24. 00:27

    기능 - 'schedulePopup.jsp'페이지의  '확인' 버튼을 누르면 데이터베이스에 일정 저장

     

     

     

    schedule.jsp 파일에 fullcalendar 설정 변경

     

    마지막 설정에는 쉼표(,)가 없어야 동작하기 때문에 정적 데이터를 넣어준다.

        title : 'default',

       start : "2019-01-01",
       end : "2019-01-01"

     

    <script>
      document.addEventListener('DOMContentLoaded', function() {
    	 
        var calendarEl = document.getElementById('calendar');
    	
        var calendar = new FullCalendar.Calendar(calendarEl, {
          plugins: [ 'interaction', 'dayGrid', 'timeGrid', 'list' ],
          header: {
            left: 'prev,next today',
            center: 'title',
            right: 'dayGridMonth,timeGridWeek,timeGridDay,listMonth'
          },
          locale : "ko",
          navLinks: true, // can click day/week names to navigate views
          businessHours: true, // display business hours
          editable: true,
          events: [
    <% 
      	  for (int i = 0; i < list.size(); i++) {
      	  	ScheduleDTO dto = (ScheduleDTO)list.get(i);
    %>	
      	  {
      	   title : '<%= dto.getSubject() %>',
      	   start : '<%= dto.getStartDate() %>',
      	   end : '<%= dto.getEndDate() %>'
      	   },
    <%
    	}
    %>
    		{
    		   title : 'default',
    		   start : "2019-01-01",
    		   end : "2019-01-01"
    		  }
          ]
        });
    
        calendar.render();
    });
    </script>

     

    schedule.jsp 파일 상단에 스크립틀릿 태그 추가

    <%
    	List<ScheduleDTO> list = (ArrayList<ScheduleDTO>)request.getAttribute("showSchedule");
    %>

     

     

    Ajax로 Form의 입력값 서버로 전송하는 기능 추가 - schedule.js

     

    JSON타입의 여러 개 데이터를 Ajax로 보낼 때는 Jquery의 serializeObject() 함수를 구현해서 사용해야한다.

     

    *이전 글을 참고하세요.

    2019/07/22 - [취업용 Spring 프로젝트/오류 내역] - Ajax 전송 시 JSON타입 data 여러 개 넘길 때 오류

     

    Ajax 전송 시 JSON타입 data 여러 개 넘길 때 오류

    오류 내용 : Ajax에서 여러 개 데이터를 보내면 Controller에서 dto로 자동 매칭시켜 데이터를 옮기고 싶었지만 두 개 이상의 데이터를 서버로 보낼 때 JSON타입이 아닌 URL 인코딩이 적용되어 전송됨 - 400 에러..

    10study.tistory.com

     

    Ajax 요청이 성공하면 schdule.jsp 페이지를 새로고침하고 팝업창을 닫는다.

    $.fn.serializeObject = function(){
        var o = {};
        var a = this.serializeArray();
        $.each(a, function() {
        	var name = $.trim(this.name),
        		value = $.trim(this.value);
        	
            if (o[name]) {
                if (!o[name].push) {
                    o[name] = [o[name]];
                }
                o[name].push(value || '');
            } else {
                o[name] = value || '';
            }
        });
        return o;
    };
    function click_ok(){
    
    	var scheduleData = JSON.stringify($('form#scheduleData').serializeObject());
    	
    	$.ajax({
    		data : scheduleData,
    		url : "addSchedule",
    		type : "POST",
    		dataType : "json",
    		contentType : "application/json; charset=UTF-8",
    		success : function(data) {
    			opener.parent.location.reload();
    			window.close();
    		}
    	});
    };

     

     

     


     

     

    DTO

     

    public class ScheduleDTO {
    	private String subject;
    	private String startDate;
    	private String endDate;
    	private String memo;
    	
    	
    	public String getSubject() {
    		return subject;
    	}
    	public void setSubject(String subject) {
    		this.subject = subject;
    	}
    	public String getStartDate() {
    		return startDate;
    	}
    	public void setStartDate(String startDate) {
    		this.startDate = startDate;
    	}
    	public String getEndDate() {
    		return endDate;
    	}
    	public void setEndDate(String endDate) {
    		this.endDate = endDate;
    	}
    	public String getMemo() {
    		return memo;
    	}
    	public void setMemo(String memo) {
    		this.memo = memo;
    	}
    }

     

     

    Controller

     

     

    아무 값도 return하지 않아도 map을 return 시켜줘야 Ajax의 success가 동작한다. 

     

     

    * 캘린더에 일정이 추가되면 바로 업데이트 되어야하기 때문에 schedule() 메서드를 변경한다.

     

    @ResponseBody
    @RequestMapping(value = "/addSchedule", method = RequestMethod.POST)
    public Map<Object,Object> addSchedule(@RequestBody ScheduleDTO dto) throws Exception{
    	Map<Object,Object>map = new HashMap<Object,Object>();
    
    	service.addSchedule(dto);
    
    	return map;
    }
    
    @RequestMapping(value = "/schedule")
    public String schedule(Model model)throws Exception {
    
    	model.addAttribute("showSchedule" , service.showSchedule());
        
    	return "/schedule";
    }

     

     

    Service

     

    @Service
    public class ScheduleService {
    
    	@Inject
    	private ScheduleDAO dao;
    	
    	public List<ScheduleDTO> showSchedule() throws Exception {
    		return dao.showSchedule();
    	}
    	
    	public void addSchedule(ScheduleDTO dto) throws Exception{
    		dao.addSchedule(dto);
    	}
    }

     

     

    DAO

     

    @Repository
    public class ScheduleDAO {
    
    	@Inject
    	private SqlSession sqlSession;
    
    	private static final String namespace = "com.management.dao.ScheduleDAO";
    	
    	public List<ScheduleDTO> showSchedule() throws Exception {
    		return sqlSession.selectList(namespace + ".showSchedule");
    	}
    	
    	public void addSchedule(ScheduleDTO dto) throws Exception  {
    		sqlSession.insert(namespace + ".addSchedule", dto);
    	}
    }

     

     

    Mapper

     

        <mapper namespace = "com.management.dao.ScheduleDAO">
        	<select id="showSchedule" resultType = "ScheduleDTO">
        		SELECT
        			subject,startDate,endDate,memo
        		FROM
        			schedule
        		ORDER BY
        			num
        		DESC
        	</select>
        	<insert id="addSchedule" parameterType = "ScheduleDTO">
    	    	INSERT INTO
    	    		schedule(subject,startDate,endDate,memo)
    	    	VALUES
    	    		(#{subject},#{startDate},#{endDate},#{memo})
        	</insert>
        </mapper>

     

     

     


     

     

    동작

     

     

     

    일정 추가 전 화면

     

     

     

    일정 추가 

    일정 추가 팝업창(schedulePopup.jsp) 호출

     

     

    일정 추가 후 화면

    schedule.jsp 상단

     

    schedule.jsp 하단

Designed by Tistory.