dhtmlxscheduler使用

  最近项目中需要一个日程管理的功能,找啊找,先是用的fullcalendar,不知道是人品还是版本问题,events接受后台JSON参数总是出错,试了许多方法,也没有试出什么结果来。所以果断换到了dhtmlxscheduler,这个插件网上搜索结果较少,我也是自己从官方网站的文档自己慢慢摸索,做了一个不算日程表的日程表。主要是样式这些还没搞懂,对于英文实在缺乏的我感到很吃力。现在已经萌生了重拾英语的想法。闲话不多说,留此文已做记录,免得下次用到无从下手。

技术分享

  结果是这样的,样式基本没有改动,但功能齐全。springMVC+mysql。

dhtmlscheduler下载地址:http://docs.dhtmlx.com/scheduler/index.html

dhtmlscheduler文档地址:http://docs.dhtmlx.com/scheduler/api__refs__scheduler.html

可以删除一些不必要的,只留需要的就可以了。

技术分享技术分享

技术分享

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>日程管理</title>
   
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
	<!-- jquery -->
	<script type="text/javascript" src='<%=basePath %>static/js/jquery/jquery-1.11.0.min.js'></script>	
	<script src="${res}/static/js/artDialog/jquery.artDialog.js?skin=default" type="text/javascript"></script>
	<link rel="stylesheet" type="txt/css" href="${res}/static/css/yz.css" />
	<!-- dhtmlscheduler -->
	<script src="<%=basePath %>static/js/dhtmlxscheduler/codebase/dhtmlxscheduler.js" type="text/javascript" charset="utf-8"></script>
    <link rel="stylesheet" href="<%=basePath %>static/js/dhtmlxscheduler/codebase/dhtmlxscheduler.css" type="text/css" media="screen" title="no title" charset="utf-8">
	<script src="<%=basePath %>static/js/dhtmlxscheduler/codebase/sources/ext/dhtmlxscheduler_minical.js" type="text/javascript"></script>
	<script src="<%=basePath %>static/js/dhtmlxscheduler/codebase/sources/dhtmlxscheduler.js" type="text/javascript"></script>
	<script src="<%=basePath %>static/js/dhtmlxscheduler/codebase/ext/dhtmlxscheduler_minical.js" type="text/javascript"></script>
	<script src="<%=basePath %>static/js/dhtmlxscheduler/codebase/sources/locale/locale_cn.js" type="text/javascript"></script>

<style type="text/css" media="screen">
   html, body{
      margin:0px;
      padding:0px;
      height:100%;
      overflow:hidden;
   }   
</style>

<script type="text/javascript" charset="utf-8">
$(function() {
    init();
    $("#dhx_minical_icon").click(show_minical);


	function init() {
		scheduler.config.multi_day = true;  
		scheduler.config.drag_move = false;
		scheduler.config.icons_edit = ['icon_custom', 'icon_save', 'icon_cancel'];
		scheduler.config.icons_select = ['icon_details', 'icon_delete'];
        scheduler.config.xml_date="%Y-%m-%d %H:%i";  
        scheduler.init('scheduler_here',new Date(),"month");  
		$.ajax({    
	        url: '/calendar/calendar',  
	        cache:false,    
	        success:function(data) {    
	            var events = [];    
	            var info = eval(data);    
	            for (var i = 0; i < info.length; i++) {
	                var ev = info[i];
	                var title = ev.event;
	                var start = ev.startDate;
	                var end = ev.endDate;
	                var id = ev.pid;
	                //组装日程
	               events.push({
	                    id:id,
	                    text:title,
	                    start_date:start,
	                    end_date:end
	               });
	                 
	            }
	            scheduler.parse(events, "json");
	          },
	          error:function() {
	              alert('数据错误!');
	          }
	      });
	      
	      /**
	      *添加保存事件数据操作
	      */
	      scheduler.attachEvent("onEventSave",function(id,ev,is_new){
    	if (!ev.text) {
    		alert("描述信息不能为空!");
    		
        	return false;
    		}
    	if(ev.start_date>ev.end_date){
    		alert("开始时间不能在结束时间之后");
    		return false;
    	}
    		var parms = {pid:id,event:ev.text,startDate:ev.start_date,endDate:ev.end_date};
    		$.post("/calendar/add",parms,function(data,status){
    			if(data.result=="SUCCESS"){
    				
    				$.dialog({
						title: '消息',
						id: "T90" ,
					    time: 3 ,
					    icon: 'warning' ,
					    content: data.msg,
					    close:function(){
							$("#loginName").focus();
					    }
					});

    			}
    			if(data.result=="ERROR"){
    				$.dialog({
						title: '消息',
						id: "T90" ,
					    time: 3 ,
					    icon: 'warning' ,
					    content: data.msg ,
					    close:function(){
							$("#loginName").focus();
					    }
					});
    				scheduler.deleteEvent(id); 
    			}
    			
    		});
    		return true;
});		
	      /**
	      *添加删除事件数据操作
	      */
	      scheduler.attachEvent("onBeforeEventDelete", function(id,e){
	    	  var parms = {pid:id};
	    		$.post("/calendar/delete",parms,function(data,status){
	    			if(data.result=="SUCCESS"){
	    				$.dialog({
	    					title: '消息',
	    					id: "T90" ,
	    				    time: 3 ,
	    				    icon: 'warning' ,
	    				    content: data.msg ,
	    				    close:function(){
	    						$("#loginName").focus();
	    				    }
	    				});
	    			}
	    		});	    		
	    	    return true;
	    	});
	      /**
		      *添加编辑事件数据操作
		      */
	      scheduler.attachEvent("onEventChanged", function(id,ev){
	    	  var parms = {pid:id,event:ev.text,startDate:ev.start_date,endDate:ev.end_date};
	    		$.post("/calendar/add",parms,function(data,status){
	    			
	    			if(data.result=="SUCCESS"){
	    				$.dialog({
	    					title: '消息',
	    					id: "T90" ,
	    				    time: 3 ,
	    				    icon: 'warning' ,
	    				    content: data.msg ,
	    				    close:function(){
	    						$("#loginName").focus();
	    				    }
	    				});
	    			}
	    		});
	    		return true;
	    	});
	}
	//显示迷你日历表
	function show_minical(){
		if (scheduler.isCalendarVisible())
			scheduler.destroyCalendar();
		else
			scheduler.renderCalendar({
				position:"dhx_minical_icon",
				date:scheduler._date,
				navigation:true,
				handler:function(date,calendar){
					scheduler.setCurrentView(date);
					scheduler.destroyCalendar()
				}
			});
	}
});

</script>

<body>
	<%@ include file="/WEB-INF/layouts/header.jsp"%>
   <div id="scheduler_here" class="dhx_cal_container" style='width:100%; height:64%;'>
      <div class="dhx_cal_navline">
         <div class="dhx_cal_prev_button"> </div>
         <div class="dhx_cal_next_button"> </div>
         <div class="dhx_cal_today_button"></div>
         <div class="dhx_cal_date"></div>
         <div class="dhx_minical_icon" id="dhx_minical_icon"> </div>
         <div class="dhx_cal_tab" name="day_tab" style="right:204px;"></div>
         <div class="dhx_cal_tab" name="week_tab" style="right:140px;"></div>
         <div class="dhx_cal_tab" name="month_tab" style="right:76px;"></div>
      </div>
      <div class="dhx_cal_header">
      </div>
      <div class="dhx_cal_data">
      </div>
   </div>
   <%@ include file="/WEB-INF/layouts/footer.jsp"%>
</body>  
  
</html>

这是jsp代码,下面是calendarPo.java:

package com.glory.learn.po.studentLog;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

import org.codehaus.jackson.map.annotate.JsonSerialize;

import com.glory.learn.util.CustomDateSerializer;

/**
 * 日程表
 * @param 
 * @param 
 * @return
 */
@Entity
@Table(name = "calendar_info")
public class CalendarPo {

	private Integer id;		//数据库标识
	private String pid;		//页面ID
	private Integer studentId;		//学生Id
	private String event;	//事件
	private Date startDate;	//开始时间
	private Date endDate;	//结束时间
	
	@Id
	@Column(name = "id")
	@GeneratedValue(strategy = GenerationType.AUTO)
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	
	@Column(name = "pid")
	public String getPid() {
		return pid;
	}
	public void setPid(String pid) {
		this.pid = pid;
	}
	@Column(name = "studentId")
	public Integer getStudentId() {
		return studentId;
	}
	public void setStudentId(Integer studentId) {
		this.studentId = studentId;
	}
	
	@Column(name = "event")
	public String getEvent() {
		return event;
	}
	public void setEvent(String event) {
		this.event = event;
	}
	
	@Column(name = "startDate")
	@Temporal(TemporalType.TIMESTAMP)
	@JsonSerialize(using = CustomDateSerializer.class)
	public Date getStartDate() {
		return startDate;
	}
	public void setStartDate(Date startDate) {
		this.startDate = startDate;
	}
	
	@Column(name = "endDate")
	@Temporal(TemporalType.TIMESTAMP)
	@JsonSerialize(using = CustomDateSerializer.class)
	public Date getEndDate() {
		return endDate;
	}
	public void setEndDate(Date endDate) {
		this.endDate = endDate;
	}
	
	
}

日期get方法上的@JsonSerialize(using = CustomDateSerializer.class)是让json返回的日期类型按指定的样式返回。CustomDateSerializer.java代码如下:

package com.glory.learn.util;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.JsonSerializer;
import org.codehaus.jackson.map.SerializerProvider;

/**
 * 自定义返回JSON 数据格中日期格式化处理
*
 * @author <a href="http://www.micmiu.com">Michael Sun</a>
*/
public class CustomDateSerializer extends JsonSerializer<Date> {

@Override

public void serialize(Date value, JsonGenerator jgen,



SerializerProvider provider) throws IOException,



JsonProcessingException {


SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


String formattedDate = formatter.format(value);


jgen.writeString(formattedDate);

}

}

下面为controller代码:
package com.glory.learn.action.student.log;

import java.util.List;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.glory.learn.bo.studentLog.CalendarBo;
import com.glory.learn.po.studentLog.CalendarPo;
import com.glory.learn.po.user.UserPo;
import com.glory.learn.util.Statics;
import com.glory.learn.vo.common.JsonResult;
import com.glory.learn.vo.common.Result;

@Controller
@RequestMapping(value = "/student/calendar/")
public class CalendarController {
	
	@Autowired
	CalendarBo calendarBo;
	
	@RequestMapping(value = "list",method = RequestMethod.GET)
	public String goPage() {
		
		return "student/calendar/dhtmlcal";
	}
	
	
	/**
	 * 返回用户所有日程信息(json格式)
	 * @param session
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "calendar",method = RequestMethod.GET)
	public @ResponseBody List<CalendarPo> getPage(HttpSession session,HttpServletResponse response) {
		UserPo userPo = (UserPo) session.getAttribute(Statics.USERPO);
		List<CalendarPo> list = calendarBo.getByStudent(userPo.getId());
		
		return list;
	}
	
	/**
	 * 添加OR修改
	 * @param session
	 * @param calendarPo
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "add")
	public @ResponseBody JsonResult addCalendar(HttpSession session,CalendarPo calendarPo){
		JsonResult jResult = new JsonResult();
		
		if (calendarPo==null) {
			jResult.setResult(Result.ERROR);
			jResult.setMsg("日程信息添加失败,请重新输入!");
		}
		
		UserPo userPo = (UserPo) session.getAttribute(Statics.USERPO);
		CalendarPo cpoPo= calendarBo.getByPid(userPo.getId(), calendarPo.getPid());
		System.out.println(cpoPo);
		if(cpoPo!=null){
			cpoPo.setEvent(calendarPo.getEvent());
			cpoPo.setStartDate(calendarPo.getStartDate());
			cpoPo.setEndDate(calendarPo.getEndDate());
			calendarBo.updateCalendar(cpoPo);
			jResult.setResult(Result.SUCCESS);
			jResult.setMsg("日程信息修改成功!");
		}else if (calendarBo.getByDate(calendarPo.getStartDate(), calendarPo.getEndDate(), userPo.getId())!=null) {
			jResult.setResult(Result.ERROR);
			jResult.setMsg("日程信息时间冲突,请重新选择时间");
		}else {
		
		calendarPo.setStudentId(userPo.getId());
		calendarBo.saveCalendar(calendarPo);
		jResult.setResult(Result.SUCCESS);
		jResult.setMsg("已添加日程!");		
		}
		return jResult;
	}
	
	/**
	 * 删除日程
	 * @param session
	 * @param pid
	 * @return
	 */
	@RequestMapping(value = "delete")
	public @ResponseBody JsonResult deleteCalendar(HttpSession session,String pid){
		JsonResult jResult = new JsonResult();
		
		UserPo userPo = (UserPo) session.getAttribute(Statics.USERPO);
		CalendarPo calendarPos = calendarBo.getByPid(userPo.getId(), pid);
		calendarBo.deleteCalendar(calendarPos);
		jResult.setResult(Result.SUCCESS);
		jResult.setMsg("已删除此日程");
		return jResult;
		
	}
}
添加时前台接受过来的也是标准时间,所以就没有做日期转换,有需要就肯定要转换的。

如果你的Po参数跟插件的日程属性匹配,返回json直接可以用,不用在组装。我这边是用fullcalendar写好了,难得改。呵呵。数据库表结构如下:

CREATE TABLE `calendar_info` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `pid` varchar(20) DEFAULT NULL,
  `studentId` int(11) DEFAULT NULL,
  `event` varchar(200) NOT NULL,
  `startDate` datetime NOT NULL,
  `endDate` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=43 DEFAULT CHARSET=utf8;
这插件功能还有许多没有搞清楚,这只是最基本的功能,界面也还不美观,有懂的朋友请指导下,不胜感激。


郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。