成品圖:
controller:
ScheduleController.java:
- 這是個查詢所有日程的servlet,在頁面首次載入中會被調(diào)用:
events:
{
url: 'scheduleList',
type: 'post'
}
package com.foreknow.controller;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.foreknow.model.Event;
import com.foreknow.model.Schedule;
import com.foreknow.service.ScheduleService;
import com.foreknow.service.impl.ScheduleServiceImpl;
import com.google.gson.Gson;
@WebServlet(name="/ScheduleController",urlPatterns="/scheduleList")
public class ScheduleController extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 服務(wù)器端向客戶端返回的內(nèi)容的類型(MIME)
resp.setContentType("text/html;charset=utf-8");
PrintWriter out = resp.getWriter();
Gson gson = new Gson();
ScheduleService service = new ScheduleServiceImpl();
String userID = "admin";
List<Object> scheduleList = service.listQueryByUserID(userID);
List<Event> list = new ArrayList<>();
if (scheduleList != null) {
for (int i = 0; i < scheduleList.size(); i++) {
Event event = new Event();
SimpleDateFormat format = null;
Schedule schedule = (Schedule) scheduleList.get(i);
System.out.println("schedule.getAllDay()++++++++++++++++"+schedule.getAllDay());
if (schedule.getAllDay().equals(1)) {
format = new SimpleDateFormat("yyyy-MM-dd");
} else {
format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
}
event.setStart(format.format(schedule.getStartTime()));
if (schedule.getEndTime() != null) {
event.setEnd(format.format(schedule.getEndTime()));
}
event.setId(schedule.getId());
event.setTitle(schedule.getTitle());
if (schedule.getIsFinish().equals("0")) {
event.setClassName("unFinish");
} else {
event.setClassName("onFinish");
}
event.setColor(schedule.getColor());
event.setIsFinish(schedule.getIsFinish());
list.add(event);
}
}
out.println(gson.toJson(list));
}
}
ScheduleCreateController.java:
package com.foreknow.controller;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.chrono.JapaneseChronology;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.foreknow.model.Schedule;
import com.foreknow.service.ScheduleService;
import com.foreknow.service.impl.ScheduleServiceImpl;
/**
* Servlet implementation class ScheduleCreateController
*/
@WebServlet(name="/ScheduleCreateController",urlPatterns="/create")
public class ScheduleCreateController extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
Schedule schedule = new Schedule();
// schedule.setId(java.util.UUID.randomUUID().toString());
String title = request.getParameter("title");
String startTimeStr = request.getParameter("startTimeStr");
String endTimeStr = request.getParameter("endTimeStr");
String allDay = request.getParameter("allDay");
String color = request.getParameter("color");
String isFinish = request.getParameter("isFinish");
schedule.setTitle(title);
schedule.setStartTimeStr(startTimeStr);
schedule.setEndTimeStr(endTimeStr);
schedule.setAllDay(allDay);
schedule.setColor(color);
schedule.setIsFinish(isFinish);
String updateID = "";
try {
updateID = request.getParameter("updateID");
schedule.setId(Integer.parseInt(updateID));
} catch (Exception e) {
// TODO: handle exception
System.out.println("沒有updateID");
}
ScheduleService scheduleService = new ScheduleServiceImpl();
String userID = "admin";
schedule.setUserID(userID);
if(schedule.getAllDay().endsWith("1")) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
schedule.setStartTime(sdf.parse(schedule.getStartTimeStr()));
} catch (ParseException e) {
e.printStackTrace();
}
if(!schedule.getEndTimeStr().equals("")){
try {
schedule.setEndTime(sdf.parse(schedule.getEndTimeStr()));
} catch (ParseException e) {
e.printStackTrace();
}
}
}else {
// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
try {
schedule.setStartTime(sdf.parse(schedule.getStartTimeStr()));
} catch (ParseException e) {
e.printStackTrace();
}
if(!schedule.getEndTimeStr().equals("")){
try {
schedule.setEndTime(sdf.parse(schedule.getEndTimeStr()));
} catch (ParseException e) {
e.printStackTrace();
}
}
}
if(schedule.getId()==null)
{
scheduleService.saveInfo(schedule);
System.out.println("schedule.getStartTime()+++++++++++"+schedule.getStartTime());
out.print("SAVE");
// return "SAVE";
}else
{
scheduleService.updateInfo(schedule);
out.print("UPDATE");
// return "UPDATE";
}
}
}
前臺新增的調(diào)用處:(通過ajax調(diào)用)
$(".addBtn").unbind("click").bind("click",function(){
//alert("333333333333333333333");
var title = $("#addForm").find("input[name=title]").val();
var startTime = "";
var endTime ="";
var allDay = $("#addForm").find("input[type=radio]:checked").val();
if(allDay == 1){
startTime = $("#addForm").find(".onAllDay input[name=startTime]").val();
endTime = $("#addForm").find(".onAllDay input[name=endTime]").val();
if(endTime == ""){
endTime = null;
}
}else{
startTime = $("#addForm").find(".unAllDay input[name=startTime]").val();
endTime = $("#addForm").find(".unAllDay input[name=endTime]").val();
if(endTime == ""){
endTime = null;
}
}
var color = $("#addForm").find("select[name=color]").val();
var isFinish = $("#addForm").find("select[name=isFinish]").val();
var addData = {
"title":title,
"startTimeStr":startTime,
"endTimeStr":endTime,
"allDay":allDay,
"color":color,
"isFinish":isFinish
};
$.ajax({
url: 'create',
type: 'post',
data: addData,
dataType: 'text',
success:function(d){
alert(d);
if(d == "SAVE"){
//alert("successfully!");
location.reload();
}else{
alert("SAVE error!");
}
}
})
});
前臺修改的調(diào)用處:(通過ajax調(diào)用)
$(".updateBtn").unbind("click").bind("click",function(){
alert("333333333333333333333");
var title = $("#updateForm").find("input[name=title]").val();
var startTime = "";
var endTime ="";
var allDay = $("#updateForm").find("input[type=radio]:checked").val();
var updateID = $("#updateID").val();
//$("#updateID").val(event.id);
if(allDay == 1){
startTime = $("#updateForm").find(".onAllDay input[name=startTime]").val();
endTime = $("#updateForm").find(".onAllDay input[name=endTime]").val();
if(endTime == ""){
endTime = null;
}
}else{
startTime = $("#updateForm").find(".unAllDay input[name=startTime]").val();
endTime = $("#updateForm").find(".unAllDay input[name=endTime]").val();
if(endTime == ""){
endTime = null;
}
}
var color = $("#updateForm").find("select[name=color]").val();
var isFinish = $("#updateForm").find("select[name=isFinish]").val();
var addData = {
"title":title,
"startTimeStr":startTime,
"endTimeStr":endTime,
"allDay":allDay,
"color":color,
"updateID":updateID,
"isFinish":isFinish
};
$.ajax({
url: 'create',
type: 'post',
data: addData,
dataType: 'text',
success:function(d){
alert(d);
if(d == "UPDATE"){
//alert("successfully!");
location.reload();
}else{
alert("UPDATE error!");
}
}
})
});
Dao層中:
ScheduleDao.java:
package com.foreknow.dao;
import java.sql.SQLException;
import java.util.List;
import com.foreknow.model.Schedule;
public interface ScheduleDao {
/**
* 查詢所有信息
* @return
*/
public List<Object> all()throws SQLException;
/**
* 根據(jù)id查詢用戶信息
* @param userID
* @return
*/
public List<Object> listByUserID(String userID)throws SQLException;
/**
* 添加信息
* @param versionBean
*/
public void save(Schedule versionBean)throws SQLException;
/**
* 修改信息
* @param versionBean
*/
public void update(Schedule versionBean)throws SQLException;
}
Dao層實現(xiàn)類中:(DaoImpl)
ScheduleDaoImpl.java:
package com.foreknow.dao.impl;
import java.sql.Date;
import java.sql.SQLException;
import java.util.List;
import com.foreknow.dao.ScheduleDao;
import com.foreknow.mapping.EntityMapping;
import com.foreknow.mapping.MappingFactory;
import com.foreknow.model.Schedule;
public class ScheduleDaoImpl extends BaseDAO implements ScheduleDao {
@Override
public List<Object> all()throws SQLException {
String sql = "select * from Schedule";
EntityMapping mapping = mappingFactory.getMap(MappingFactory.SCHEDULE_MAPPING);
List<Object> list = jdbcTemplate.query(sql, mapping);
return list;
}
@Override
public List<Object> listByUserID(String userID)throws SQLException {
String sql = "select * from Schedule where userID = ?";
EntityMapping mapping = mappingFactory.getMap(MappingFactory.SCHEDULE_MAPPING);
List<Object> list = jdbcTemplate.query(sql, mapping, userID);
return list;
}
@Override
public void save(Schedule versionBean)throws SQLException {
/* String sql = "insert into Schedule (id,title,startTime,endTime,allDay,color,userID,isFinish,createTime)values(?,?,?,?,?,?,?,?,?)";
jdbcTemplate.update(sql, versionBean.getId(),versionBean.getTitle(), versionBean.getStartTime(), versionBean.getEndTime(),
versionBean.getAllDay(), versionBean.getColor(), versionBean.getUserID(), versionBean.getIsFinish(),
versionBean.getCreateTime());*/
String sql = "insert into Schedule (id,title,startTime,endTime,allDay,color,userID,isFinish,createTime)values(?,?,?,?,?,?,?,?,?)";
Date sqlStartTime = new Date( versionBean.getStartTime().getTime());
// System.out.println("在daoimpl中的sqlStartTime················"+sqlStartTime);
jdbcTemplate.update(sql, versionBean.getId(),versionBean.getTitle(), sqlStartTime, versionBean.getEndTime(),
versionBean.getAllDay(), versionBean.getColor(), versionBean.getUserID(), versionBean.getIsFinish(),
versionBean.getCreateTime());
}
@Override
public void update(Schedule versionBean)throws SQLException {
/*String sql = "update Schedule set title = ?,startTime = ?,endTime = ?,allDay = ?,color = ?,userID = ?,isFinish = ?,createTime = ? where id = ?";
jdbcTemplate.update(sql, versionBean.getTitle(),versionBean.getStartTime(),versionBean.getEndTime(),versionBean.getAllDay(),versionBean.getColor(),versionBean.getUserID(),versionBean.getIsFinish(),versionBean.getCreateTime(),versionBean.getId());*/
String sql = "update Schedule set title = ?,startTime = ?,endTime = ?,allDay = ?,color = ?,userID = ?,isFinish = ?,createTime = ? where id = ?";
Date sqlStartTime = new Date( versionBean.getStartTime().getTime());
System.out.println("在daoimpl中update的sqlStartTime················"+sqlStartTime);
jdbcTemplate.update(sql, versionBean.getTitle(),sqlStartTime,versionBean.getEndTime(),versionBean.getAllDay(),versionBean.getColor(),versionBean.getUserID(),versionBean.getIsFinish(),versionBean.getCreateTime(),versionBean.getId());
}
}
db包中:
DBManager.java:得到數(shù)據(jù)庫的連接:
package com.foreknow.db;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.foreknow.util.PropertyUtil;
public class DBManager {
private Properties prop;
private String path = "src/datainfo.properties";
private PropertyUtil propertyUtil;
private static DBManager dbManager = null;
private Log logger = LogFactory.getLog(DBManager.class);
private DBManager(){
}
public static DBManager getInstance() {
if (dbManager == null) {
dbManager = new DBManager();
}
return dbManager;
}
/**
* @return
* 與數(shù)據(jù)庫進行連接
*/
public Connection getConnection() {
if (propertyUtil == null) {
propertyUtil = PropertyUtil.getInstance();
if (prop == null) {
prop = propertyUtil.getProperty(path);
if (logger.isInfoEnabled()) {
logger.info("讀取數(shù)據(jù)庫配置文件: " + path);
}
}
}
Connection conn = null;
try {
Class.forName(prop.getProperty("DRIVER"));
String url = prop.getProperty("DBURL");
String username = prop.getProperty("USERNAME");
String password = prop.getProperty("USERPWD");
conn = DriverManager.getConnection(prop.getProperty("DBURL"),prop.getProperty("USERNAME"),prop.getProperty("USERPWD"));
conn.setAutoCommit(false);//先這樣簡單自動提交身诺,以后再業(yè)務(wù)層管理事務(wù),就需要設(shè)置為false了
if (logger.isInfoEnabled()) {
logger.info("讀取數(shù)據(jù)庫配置文件成功抛虫!");
}
} catch (ClassNotFoundException e) {
if (logger.isErrorEnabled()) {
logger.error("找不到數(shù)據(jù)庫驅(qū)動柏卤!");
}
} catch (SQLException e) {
if (logger.isErrorEnabled()) {
logger.error("連接失敗莽使!");
}
}
return conn;
}
}
JdbcTemplate.java:包含增刪改查等數(shù)據(jù)庫操作:
package com.foreknow.db;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.foreknow.mapping.EntityMapping;
public class JdbcTemplate {
private Connection con;
private PreparedStatement psta = null;
private ResultSet rs = null;
private static JdbcTemplate jdbcTemplate = null;
private Log logger = LogFactory.getLog(JdbcTemplate.class);
private JdbcTemplate() {
}
public static JdbcTemplate getInstance() {
if (jdbcTemplate == null) {
jdbcTemplate = new JdbcTemplate();
}
return jdbcTemplate;
}
/**
* 注入數(shù)據(jù)庫連接
* @param connection
*/
public void setConnection(Connection connection) {
this.con = connection;
}
/**
* 用于執(zhí)行insert绵跷,update膘螟,delete語句,可帶參數(shù)
* @param sql
* @param values
* @return 返回影響行數(shù)
* @throws DAOException
*/
public int update(String sql,Object... values) {
if (logger.isDebugEnabled()) {
logger.debug("發(fā)送sql語句:" + sql);
}
int row = 0;
try {
psta = con.prepareStatement(sql); //insert into emp values(?,?,?,?)
for (int i = 0; i< values.length; i++){
psta.setObject(i+1, values[i]);
}
row = psta.executeUpdate();
} catch (SQLException e) {
String errorMsg = "sql語句發(fā)生錯誤碾局!sql語句為:" + sql;
if (logger.isErrorEnabled()) {
logger.error(errorMsg, e);
}
throw new RuntimeException(errorMsg);
} finally {
close();
}
return row;
}
/**
* 查詢一個double值
* @param sql
* @return
*/
public double queryDouble(String sql, Object... values) {
if (logger.isDebugEnabled()) {
logger.debug("發(fā)送sql語句:" + sql);
}
double result = 0;
try {
psta = con.prepareStatement(sql);
for (int i = 0; i< values.length; i++){
psta.setObject(i+1, values[i]);
}
rs = psta.executeQuery();
if (rs.next()) {
result = rs.getDouble(1);
}
} catch (SQLException e) {
String errorMsg = "sql語句發(fā)生錯誤荆残!sql語句為:" + sql;
if (logger.isErrorEnabled()) {
logger.error(errorMsg, e);
}
throw new RuntimeException(errorMsg);
} finally {
close();
}
return result;
}
/**
* 用于執(zhí)行select count(*)語句,或者獲取seq序列的語句
* @param sql
* @return 返回第一個值
* @throws DAOException
*/
public int query(String sql){
if (logger.isDebugEnabled()) {
logger.debug("發(fā)送sql語句:" + sql);
}
int result = 0;
try {
psta = con.prepareStatement(sql);
rs = psta.executeQuery();
if (rs.next()) {
result = rs.getInt(1);
}
} catch (SQLException e) {
String errorMsg = "sql語句發(fā)生錯誤!sql語句為:" + sql;
if (logger.isErrorEnabled()) {
logger.error(errorMsg, e);
}
throw new RuntimeException(errorMsg);
} finally {
close();
}
return result;
}
/**
* 用于執(zhí)行查詢返回多個對象的sql語句
* @param sql
* @param mapping
* @param values
* @return 返回對象鏈表
* @throws DAOException
*/
public List<Object> query(String sql, EntityMapping mapping, Object...values){
if (logger.isDebugEnabled()) {
logger.debug("發(fā)送sql語句:" + sql);
}
List<Object> list = new ArrayList<Object>();
try {
psta = con.prepareStatement(sql);
for (int i = 0; i < values.length; i++){
psta.setObject(i+1, values[i]);
}
rs = psta.executeQuery();
while(rs.next()){
list.add(mapping.mapping(rs));
}
} catch (SQLException e) {
String errorMsg = "sql語句發(fā)生錯誤净当!sql語句為:" + sql;
if (logger.isErrorEnabled()) {
logger.error(errorMsg, e);
}
throw new RuntimeException(errorMsg);
} finally {
close();
}
return list;
}
/**
* 關(guān)閉數(shù)據(jù)庫連接
* @throws DAOException
*/
public void close(){
try{
if (psta!=null){
psta.close();
psta=null;
}
if (rs!=null){
rs.close();
rs=null;
}
} catch (SQLException e) {
String errorMsg = "關(guān)閉preparedstatment 和resultset發(fā)生錯誤内斯!";
if (logger.isErrorEnabled()) {
logger.error(errorMsg, e);
}
throw new RuntimeException(errorMsg);
}
}
}
Mapping包中:
EntityMapping.java :mapping實例接口
package com.foreknow.mapping;
import java.sql.ResultSet;
import java.sql.SQLException;
public interface EntityMapping {
/**
* 可以根據(jù)傳入的ResultSet返回一個對象(Object)
*/
public Object mapping(ResultSet rs)throws SQLException;
}
ScheduleMapping.java : mapping的實現(xiàn)類
package com.foreknow.mapping;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.foreknow.model.Schedule;
public class ScheduleMapping implements EntityMapping {
@Override
public Object mapping(ResultSet rs) throws SQLException {
Schedule schedule = new Schedule();
schedule.setId(rs.getInt("id"));
schedule.setTitle(rs.getString("title"));
schedule.setStartTime(rs.getDate("startTime"));
schedule.setEndTime(rs.getDate("endTime"));
schedule.setAllDay(rs.getString("allDay"));
schedule.setColor(rs.getString("color"));
schedule.setUserID(rs.getString("userID"));
schedule.setIsFinish(rs.getString("isFinish"));
schedule.setCreateTime(rs.getDate("createTime"));
return schedule;
}
}
實體類包中:
Event.java :前臺日程的對象
package com.foreknow.model;
public class Event {
private java.lang.Integer id;
private java.lang.String title;// 日程內(nèi)容
private java.lang.String start;// 開始時間
private java.lang.String end;// 結(jié)束時間
private java.lang.String color;// 顏色
private java.lang.String allDay;// 是否全天,1 - 是像啼,0 - 不是
private java.lang.String isFinish;// 是否完成俘闯,1 - 是,0 - 不是
public java.lang.String getIsFinish() {
return isFinish;
}
public void setIsFinish(java.lang.String isFinish) {
this.isFinish = isFinish;
}
private java.lang.String className;
public java.lang.Integer getId()
{
return id;
}
public void setId(java.lang.Integer id)
{
this.id = id;
}
public java.lang.String getTitle()
{
return title;
}
public void setTitle(java.lang.String title)
{
this.title = title;
}
public java.lang.String getStart()
{
return start;
}
public void setStart(java.lang.String start)
{
this.start = start;
}
public java.lang.String getEnd()
{
return end;
}
public void setEnd(java.lang.String end)
{
this.end = end;
}
public java.lang.String getColor()
{
return color;
}
public void setColor(java.lang.String color)
{
this.color = color;
}
public java.lang.String getAllDay()
{
return allDay;
}
public void setAllDay(java.lang.String allDay)
{
this.allDay= allDay;
}
public java.lang.String getClassName()
{
return className;
}
public void setClassName(java.lang.String className)
{
this.className = className;
}
}
Schedule.java : 后臺日歷的實體對象
package com.foreknow.model;
public class Schedule {
private static final long serialVersionUID = 1L;
private java.lang.Integer id;// ID
private java.lang.String title;// 日程內(nèi)容
private java.util.Date startTime;// 開始時間
private java.util.Date endTime;// 結(jié)束時間
private java.lang.String allDay;// 是否全天忽冻,1 - 是真朗,0 - 不是
private java.lang.String color;// 顏色
private java.lang.String userID;// 用戶ID
private java.lang.String isFinish;// 是否完成,1 - 是甚颂,0 - 不是
private java.util.Date createTime;// 創(chuàng)建時間
private java.lang.String startTimeStr;//開始時間String
private java.lang.String endTimeStr;//結(jié)束時間String
public java.lang.String getStartTimeStr() {
return startTimeStr;
}
public void setStartTimeStr(java.lang.String startTimeStr) {
this.startTimeStr = startTimeStr;
}
public java.lang.String getEndTimeStr() {
return endTimeStr;
}
public void setEndTimeStr(java.lang.String endTimeStr) {
this.endTimeStr = endTimeStr;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
public Schedule() {
}
public java.lang.Integer getId() {
return this.id;
}
public void setId(java.lang.Integer id) {
this.id = id;
}
public java.lang.String getTitle() {
return this.title;
}
public void setTitle(java.lang.String title) {
this.title = title;
}
public java.util.Date getStartTime() {
return this.startTime;
}
public void setStartTime(java.util.Date startTime) {
this.startTime = startTime;
}
public java.util.Date getEndTime() {
return this.endTime;
}
public void setEndTime(java.util.Date endTime) {
this.endTime = endTime;
}
public java.lang.String getAllDay() {
return this.allDay;
}
public void setAllDay(java.lang.String allDay) {
this.allDay = allDay;
}
public java.lang.String getColor() {
return this.color;
}
public void setColor(java.lang.String color) {
this.color = color;
}
public java.lang.String getUserID() {
return this.userID;
}
public void setUserID(java.lang.String userID) {
this.userID = userID;
}
public java.util.Date getCreateTime() {
return this.createTime;
}
public void setCreateTime(java.util.Date createTime) {
this.createTime = createTime;
}
public java.lang.String getIsFinish() {
return isFinish;
}
public void setIsFinish(java.lang.String isFinish) {
this.isFinish = isFinish;
}
}
Service接口包中:
ScheduleService.java :
package com.foreknow.service;
import java.util.List;
import com.foreknow.model.Schedule;
public interface ScheduleService {
/**
* 查詢所有信息
* @return
*/
public List<Object> allInfo();
/**
* 根據(jù)id查詢用戶信息
* @param userID
* @return
*/
public List<Object> listQueryByUserID(String userID);
/**
* 添加信息
* @param versionBean
*/
public void saveInfo(Schedule versionBean);
/**
* 修改信息
* @param versionBean
*/
public void updateInfo(Schedule versionBean);
}
ServiceImpl包中:
ScheduleServiceImpl.java :設(shè)置連接蜜猾,調(diào)用Dao的方法
package com.foreknow.service.impl;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;
import com.foreknow.dao.impl.ScheduleDaoImpl;
import com.foreknow.db.DBManager;
import com.foreknow.model.Schedule;
import com.foreknow.service.ScheduleService;
public class ScheduleServiceImpl implements ScheduleService {
@Override
public List<Object> allInfo() {
DBManager dbManager = DBManager.getInstance();
Connection connection = dbManager.getConnection();
//要將DBManager的connection注入到JdbcTemplate中
//實例化dao并調(diào)用dao中的登錄方法
ScheduleDaoImpl daoImpl=new ScheduleDaoImpl();
daoImpl.setConnection(connection);
List<Object> list = null;
try {
list = daoImpl.all();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
@Override
public List<Object> listQueryByUserID(String userID) {
DBManager dbManager = DBManager.getInstance();
Connection connection = dbManager.getConnection();
//要將DBManager的connection注入到JdbcTemplate中
//實例化dao并調(diào)用dao中的登錄方法
ScheduleDaoImpl daoImpl=new ScheduleDaoImpl();
daoImpl.setConnection(connection);
List<Object> list = null;
try {
list = daoImpl.listByUserID(userID);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
@Override
public void saveInfo(Schedule versionBean) {
DBManager dbManager = DBManager.getInstance();
Connection connection = dbManager.getConnection();
//要將DBManager的connection注入到JdbcTemplate中
//實例化dao并調(diào)用dao中的登錄方法
ScheduleDaoImpl daoImpl = new ScheduleDaoImpl();
daoImpl.setConnection(connection);
Date now = new Date();
// versionBean.setId(id);
versionBean.setCreateTime(now);
versionBean.setIsFinish("0");
try {
daoImpl.save(versionBean);
connection.commit();
} catch (SQLException e) {
try {
connection.rollback();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
e.printStackTrace();
}
}
@Override
public void updateInfo(Schedule versionBean) {
DBManager dbManager = DBManager.getInstance();
Connection connection = dbManager.getConnection();
//要將DBManager的connection注入到JdbcTemplate中
//實例化dao并調(diào)用dao中的登錄方法
ScheduleDaoImpl daoImpl=new ScheduleDaoImpl();
daoImpl.setConnection(connection);
try {
daoImpl.update(versionBean);
connection.commit();
} catch (SQLException e) {
try {
connection.rollback();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
e.printStackTrace();
}
}
}
連接數(shù)據(jù)庫的配置文件:datainfo.properties
datainfo.properties:
DRIVER=com.mysql.cj.jdbc.Driver
DBURL=jdbc:mysql://10.25.52.6:3306/childcode?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai
#DBNAME=ORCL
USERNAME=jixiegou
USERPWD=123
主頁面:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link href="/WebFull/css/bootstrap.min.css?_v=1472701731737" media="screen" rel="stylesheet" type="text/css" />
<link href="/WebFull/js/fullcalendar.css?_v=1472701698015" media="screen" rel="stylesheet" type="text/css" />
<link href='js/fullcalendar.css' rel='stylesheet' />
<style>
/* 語言選擇 */
#top {
background: #eee;
border-bottom: 1px solid #ddd;
padding: 0 10px;
line-height: 40px;
font-size: 12px;
}
/* 日歷 */
#calendar {
margin: 40px auto;
padding: 0 10px;
}
/* Event 參數(shù) className 的值 */
.onFinish:before {
content:"【 已完成 】";
background-color:yellow;
color:green;
text-align:center;
font-weight:bold;
width:100%;
}
/* Event 參數(shù) className 的值 */
.unFinish:before {
content:"【 未完成 】";
background-color:yellow;
color:red;
text-align:center;
font-weight:bold;
}
</style>
</head>
<body>
<div id='top'>
<!-- 頁面的語言 -->
Language:
<select id='lang-selector'></select>
</div>
<div id='calendar'></div>
<!-- 模態(tài)框(Modal) -->
<!-- aria-labelledby="myModalLabel"秀菱,------該屬性引用模態(tài)框的標題振诬。 -->
<!-- data-toggle="modal",HTML5 自定義的 data 屬性 data-toggle -------用于打開模態(tài)窗口衍菱。 -->
<!-- 新增的模態(tài)框 -->
<div class="modal fade" id="addModal" tabindex="-1" role="dialog" aria-labelledby="addModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<!--modal-header -->
<div class="modal-header">
<button onclick="hideModal('addModal');" type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="addModalLabel">新增</h4>
</div>
<!--modal-body -->
<div class="modal-body" id="addModalBody">
<form class="form-horizontal" id="addForm">
<div class="alert alert-info" role="alert"><strong>聲明 !</strong> 如果日程時間精確到“天”請選擇 <strong> 全天 </strong> 赶么,如果精確到“時間”請選擇 <strong> 非全天 </strong> !</div>
<div class="form-group">
<label class="col-sm-2 control-label"> </label>
<div class="col-sm-10">
<div style="margin:auto;">
<p class="radio-p" class="allDayType">
<label class="js-radio-box" style="left:0%;">
<input type="radio" value="1" id="7allDayAdd" name="allDay" checked/><label class="genderLab" for="7allDayAdd" style="font-size: 15px;">全天</label>
<input type="radio" value="0" id="8allDayAdd" name="allDay" /><label class="genderLab" for="8allDayAdd" style="font-size: 15px;">非全天</label>
</label>
</p>
</div>
</div>
</div>
<div class="form-group onAllDay">
<label class="col-sm-2 control-label">開始時間:</label>
<div class="col-sm-10">
<input name="startTime" value="" type="text" class="Wdate form-control validate[required,maxSize[60]]" onfocus="WdatePicker({lang:'zh-cn',dateFmt:'yyyy-MM-dd'})" id="form-validation-field-0">
</div>
</div>
<div class="form-group onAllDay">
<label class="col-sm-2 control-label">結(jié)束時間:</label>
<div class="col-sm-10">
<input name="endTime" value="" type="text" class="Wdate form-control validate[required,maxSize[60]]" onfocus="WdatePicker({lang:'zh-cn',dateFmt:'yyyy-MM-dd'})" id="form-validation-field-0">
<span style="color:red;">如果是當天的日程脊串,結(jié)束時間可以不填辫呻!</span>
</div>
</div>
<div class="form-group unAllDay" style="display:none;">
<label class="col-sm-2 control-label">開始時間:</label>
<div class="col-sm-10">
<input name="startTime" value="" type="text" class="Wdate form-control validate[required,maxSize[60]]" onfocus="WdatePicker({lang:'zh-cn',dateFmt:'yyyy-MM-dd HH:mm'})" id="form-validation-field-0">
</div>
</div>
<div class="form-group unAllDay" style="display:none;">
<label class="col-sm-2 control-label">結(jié)束時間:</label>
<div class="col-sm-10">
<input name="endTime" value="" type="text" class="Wdate form-control validate[required,maxSize[60]]" onfocus="WdatePicker({lang:'zh-cn',dateFmt:'yyyy-MM-dd HH:mm'})" id="form-validation-field-0">
<span style="color:red;">如果是當天的日程,結(jié)束時間可以不填琼锋!</span>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">內(nèi)容:</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="title" id="" placeholder="請輸入內(nèi)容">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">類型:</label>
<div class="col-sm-10">
<select id="color" name="color" class="form-control">
<option value="#3a87ad">普通</option>
<option value="red">緊急</option>
</select>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">完成狀態(tài):</label>
<div class="col-sm-10">
<select id="isFinish" name="isFinish" class="form-control">
<option value="0">未完成</option>
</select>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="button" class="btn btn-success addBtn">提交</button>
</div>
</div>
</form>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div>
<!-- 修改的模態(tài)框 -->
<div class="modal fade" id="updateModal" tabindex="-1" role="dialog" aria-labelledby="updatefLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<!--modal-header -->
<div class="modal-header">
<button onclick="hideModal('updateModal');" type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="updateModalLabel">修改</h4>
</div>
<!--modal-body -->
<div class="modal-body" id="updateModalBody">
<form class="form-horizontal" id="updateForm">
<div class="alert alert-info" role="alert"><strong>聲明 !</strong> 如果日程時間精確到“天”請選擇 <strong> 全天 </strong> 放闺,如果精確到“時間”請選擇 <strong> 非全天 </strong> !</div>
<div class="form-group">
<label class="col-sm-2 control-label"> </label>
<input type="hidden" class="form-control" name="id" id="updateID" value="">
<div class="col-sm-10">
<div style="margin:auto;">
<p class="radio-p" class="allDayType">
<label class="js-radio-box" style="left:0%;">
<input type="radio" value="1" id="7allDayUpdate" name="allDay" checked/><label class="genderLab" for="7allDayUpdate" style="font-size: 15px;">全天</label>
<input type="radio" value="0" id="8allDayUpdate" name="allDay" /><label class="genderLab" for="8allDayUpdate" style="font-size: 15px;">非全天</label>
</label>
</p>
</div>
</div>
</div>
<div class="form-group onAllDay">
<label class="col-sm-2 control-label">開始時間:</label>
<div class="col-sm-10">
<input name="startTime" value="" type="text" class="Wdate form-control validate[required,maxSize[60]]" onfocus="WdatePicker({lang:'zh-cn',dateFmt:'yyyy-MM-dd'})" id="form-validation-field-0">
</div>
</div>
<div class="form-group onAllDay">
<label class="col-sm-2 control-label">結(jié)束時間:</label>
<div class="col-sm-10">
<input name="endTime" value="" type="text" class="Wdate form-control validate[required,maxSize[60]]" onfocus="WdatePicker({lang:'zh-cn',dateFmt:'yyyy-MM-dd'})" id="form-validation-field-0">
<span style="color:red;">如果是當天的日程缕坎,結(jié)束時間可以不填怖侦!</span>
</div>
</div>
<div class="form-group unAllDay" style="display:none;">
<label class="col-sm-2 control-label">開始時間:</label>
<div class="col-sm-10">
<input name="startTime" value="" type="text" class="Wdate form-control validate[required,maxSize[60]]" onfocus="WdatePicker({lang:'zh-cn',dateFmt:'yyyy-MM-dd HH:mm'})" id="form-validation-field-0">
</div>
</div>
<div class="form-group unAllDay" style="display:none;">
<label class="col-sm-2 control-label">結(jié)束時間:</label>
<div class="col-sm-10">
<input name="endTime" value="" type="text" class="Wdate form-control validate[required,maxSize[60]]" onfocus="WdatePicker({lang:'zh-cn',dateFmt:'yyyy-MM-dd HH:mm'})" id="form-validation-field-0">
<span style="color:red;">如果是當天的日程,結(jié)束時間可以不填!</span>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">內(nèi)容:</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="title" id="" placeholder="請輸入內(nèi)容">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">類型:</label>
<div class="col-sm-10">
<select id="color" name="color" class="form-control">
<option value="#3a87ad">普通</option>
<option value="red">緊急</option>
</select>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">完成狀態(tài):</label>
<div class="col-sm-10">
<select id="isFinish" name="isFinish" class="form-control">
<option value="0">未完成</option>
<option value="1">已完成</option>
</select>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="button" class="btn btn-success updateBtn">提交</button>
</div>
</div>
</form>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div>
</body>
<script src='js/jquery.min.js'></script>
<script src='js/bootstrap.min.js'></script>
<script src='js/moment.min.js'></script>
<script src='js/fullcalendar.min.js'></script>
<script src='js/lang-all.js'></script>
<script type="text/javascript">
$(document).ready(function() {
//國際化默認值為'en'匾寝,代表使用英文
var initialLangCode = 'en';
//初始化FullCalendar
$('#calendar').fullCalendar({
//設(shè)置頭部信息搬葬,如果不想顯示,可以設(shè)置header為false
header: {
//日歷頭部左邊:初始化切換按鈕
left: 'prev,next today',
//日歷頭部中間:顯示當前日期信息
center: 'title',
//日歷頭部右邊:初始化視圖
right: 'month,agendaWeek,agendaDay'
},
//設(shè)置是否顯示周六和周日艳悔,設(shè)為false則不顯示
weekends: true,
//月視圖的顯示模式急凰,fixed:固定顯示6周高;liquid:高度隨周數(shù)變化猜年;variable: 高度固定
weekMode: 'liquid',
//初始化時的默認視圖抡锈,month、agendaWeek码倦、agendaDay
defaultView: 'month',
//agenda視圖下all-day的顯示文本
allDayText: '全天',
//語言為en --var initialLangCode = 'en';
lang: initialLangCode,
//區(qū)分工作時間
businessHours: true,
//非all-day時企孩,如果沒有指定結(jié)束時間,默認執(zhí)行120分鐘
defaultEventMinutes: 120,
//設(shè)置為true時袁稽,如果數(shù)據(jù)過多超過日歷格子顯示的高度時勿璃,多出去的數(shù)據(jù)不會將格子擠開,而是顯示為 +...more 推汽,點擊后才會完整顯示所有的數(shù)據(jù)
eventLimit: true,
//點擊或者拖動選中之后补疑,點擊日歷外的空白區(qū)域是否取消選中狀態(tài) true為取消 false為不取消,只有重新選擇時才會取消
unselectAuto: true,
eventClick : function( event ){
//do something here...
/* console.log('eventClick中選中Event的id屬性值為:', event.id);
console.log('eventClick中選中Event的title屬性值為:', event.title);
console.log('eventClick中選中Event的start屬性值為:', event.start.format('YYYY-MM-DD HH:mm'));
console.log('eventClick中選中Event的end屬性值為:', event.end==null?'無':event.end.format('YYYY-MM-DD HH:mm'));
console.log('eventClick中選中Event的color屬性值為:', event.color);
console.log('eventClick中選中Event的className屬性值為:', event.className); */
// ...
$("#updateForm").find(".onAllDay input[name=startTime]").val(event.start.format('YYYY-MM-DD'));
$("#updateForm").find(".unAllDay input[name=startTime]").val(event.start.format('YYYY-MM-DD HH:mm'));
if(event.end !== null){
$("#updateForm").find(".onAllDay input[name=endTime]").val(event.end.format('YYYY-MM-DD'));
$("#updateForm").find(".unAllDay input[name=endTime]").val(event.end.format('YYYY-MM-DD HH:mm'));
}
$("#updateForm").find("input[name=title]").val(event.title);
$("#updateForm").find("select[name=color]").val(event.color);
$("#updateForm").find("select[name=isFinish]").val(event.isFinish);
if(!event.allDay){
$("#updateForm").find("input[id=8allDayUpdate]").click();
}
$("#updateID").val(event.id);
$("#updateModal").modal('show');/* id為updateModal(修改)的模態(tài)框顯示出來 */
},
dayClick : function( date ) {
//do something here...
console.log('dayClick觸發(fā)的時間為:', date.format());
// ...
$("#addForm").find(".onAllDay input[name=startTime]").val(date.format('YYYY-MM-DD'));
$("#addForm").find(".unAllDay input[name=startTime]").val(date.format('YYYY-MM-DD HH:mm'));
$("#addModal").modal('show');/* id為addModal(新增)的模態(tài)框顯示出來 */
},
/* select: function( start, end ){
//alert(start);
//alert(end);
//do something here...
console.log('select觸發(fā)的開始時間為:', start.format());
console.log('select觸發(fā)的結(jié)束時間為:', end.format());
// ...
} */
//設(shè)置是否可被單擊或者拖動選擇
selectable: true,
//點擊或者拖動選擇時歹撒,是否顯示時間范圍的提示信息莲组,該屬性只在agenda視圖里可用
selectHelper: true,
select: function(start, end) {
/* alert("11111111111111111111111111");
alert(start);
alert(end); */
var title = prompt('Event Title:');
var eventData;
if (title) {
eventData = {
title: title,
start: start,
end: end
};
/* 渲染一個新的日程到日程表上: event 是 Event Object 對象,至少含有 title 和 start 屬性暖夭。
通常锹杈,用 renderEvent 方法添加的日程會在日程表重載數(shù)據(jù)(refetches)之后消失÷踝牛可以將stick設(shè)置為true
renderEvent 是一個方法 */
$('#calendar').fullCalendar('renderEvent', eventData, false); // stick? = true
}
$('#calendar').fullCalendar('unselect'); //清除當前的選擇竭望。
},
eventMouseover : function( event ) {
//do something here...
console.log('鼠標經(jīng)過 ...');
console.log('eventMouseover被執(zhí)行,選中Event的title屬性值為:', event.title);
// ...
},
eventMouseout : function( event ) {
//do something here...
console.log('eventMouseout被執(zhí)行裕菠,選中Event的title屬性值為:', event.title);
console.log('鼠標離開 ...');
// ...
},
//Event是否可被拖動或者拖拽
editable: true,
//Event被拖動時的不透明度
dragOpacity: 0.5,
eventDrop : function( event, dayDelta, revertFunc ) {
//do something here...
console.log('eventDrop --- start ---');
console.log('eventDrop被執(zhí)行咬清,Event的title屬性值為:', event.title);
if(dayDelta._days != 0){
console.log('eventDrop被執(zhí)行,Event的start和end時間改變了:', dayDelta._days+'天奴潘!');
}else if(dayDelta._milliseconds != 0){
console.log('eventDrop被執(zhí)行旧烧,Event的start和end時間改變了:', dayDelta._milliseconds/1000+'秒!');
}else{
console.log('eventDrop被執(zhí)行画髓,Event的start和end時間沒有改變掘剪!');
}
//revertFunc();
console.log('eventDrop --- end ---');
// ...
},
eventResize : function( event, dayDelta, revertFunc ) {
//do something here...
console.log(' --- start --- eventResize');
console.log('eventResize被執(zhí)行,Event的title屬性值為:', event.title);
if(dayDelta._days != 0){
console.log('eventResize被執(zhí)行奈虾,Event的start和end時間改變了:', dayDelta._days+'天夺谁!');
}else if(dayDelta._milliseconds != 0){
console.log('eventResize被執(zhí)行肆汹,Event的start和end時間改變了:', dayDelta._milliseconds/1000+'秒!');
}else{
console.log('eventResize被執(zhí)行予权,Event的start和end時間沒有改變昂勉!');
}
//revertFunc();
console.log('--- end --- eventResize');
// ...
},
events:
{
url: 'scheduleList',
type: 'post'
}
});
$('#lang-selector').append(
$('<option/>')
.attr('value', "en")
.prop('selected', "en" == initialLangCode)
.text("en")
).append(
$('<option/>')
.attr('value', "zh-cn")
.prop('selected', "zh-cn" == initialLangCode)
.text("zh-cn")
);
$('#lang-selector').on('change', function() {
if (this.value) {
$('#calendar').fullCalendar('option', 'lang', this.value);
}
});
$("#addForm").find("input[type=radio]").each(function(){
var $this = $(this);
$this.bind("click",function(){
if($this.val() == 1){
$("#addForm").find(".onAllDay").show();
$("#addForm").find(".unAllDay").hide();
}else{
$("#addForm").find(".onAllDay").hide();
$("#addForm").find(".unAllDay").show();
}
});
});
$(".addBtn").unbind("click").bind("click",function(){
//alert("333333333333333333333");
var title = $("#addForm").find("input[name=title]").val();
var startTime = "";
var endTime ="";
var allDay = $("#addForm").find("input[type=radio]:checked").val();
if(allDay == 1){
startTime = $("#addForm").find(".onAllDay input[name=startTime]").val();
endTime = $("#addForm").find(".onAllDay input[name=endTime]").val();
if(endTime == ""){
endTime = null;
}
}else{
startTime = $("#addForm").find(".unAllDay input[name=startTime]").val();
endTime = $("#addForm").find(".unAllDay input[name=endTime]").val();
if(endTime == ""){
endTime = null;
}
}
var color = $("#addForm").find("select[name=color]").val();
var isFinish = $("#addForm").find("select[name=isFinish]").val();
var addData = {
"title":title,
"startTimeStr":startTime,
"endTimeStr":endTime,
"allDay":allDay,
"color":color,
"isFinish":isFinish
};
$.ajax({
url: 'create',
type: 'post',
data: addData,
dataType: 'text',
success:function(d){
alert(d);
if(d == "SAVE"){
//alert("successfully!");
location.reload();
}else{
alert("SAVE error!");
}
}
})
});
/*----------------------------------------------------------- */
$(".updateBtn").unbind("click").bind("click",function(){
alert("333333333333333333333");
var title = $("#updateForm").find("input[name=title]").val();
var startTime = "";
var endTime ="";
var allDay = $("#updateForm").find("input[type=radio]:checked").val();
var updateID = $("#updateID").val();
//$("#updateID").val(event.id);
if(allDay == 1){
startTime = $("#updateForm").find(".onAllDay input[name=startTime]").val();
endTime = $("#updateForm").find(".onAllDay input[name=endTime]").val();
if(endTime == ""){
endTime = null;
}
}else{
startTime = $("#updateForm").find(".unAllDay input[name=startTime]").val();
endTime = $("#updateForm").find(".unAllDay input[name=endTime]").val();
if(endTime == ""){
endTime = null;
}
}
var color = $("#updateForm").find("select[name=color]").val();
var isFinish = $("#updateForm").find("select[name=isFinish]").val();
var addData = {
"title":title,
"startTimeStr":startTime,
"endTimeStr":endTime,
"allDay":allDay,
"color":color,
"updateID":updateID,
"isFinish":isFinish
};
$.ajax({
url: 'create',
type: 'post',
data: addData,
dataType: 'text',
success:function(d){
alert(d);
if(d == "UPDATE"){
//alert("successfully!");
location.reload();
}else{
alert("UPDATE error!");
}
}
})
});
/*----------------------------------------------------------- */
//初始化語言選擇的下拉菜單值
/* $.each($.fullCalendar.langs, function(langCode) {
$('#lang-selector').append(
$('<option/>')
.attr('value', langCode)
.prop('selected', langCode == initialLangCode)
.text(langCode)
);
}); */
//當選擇一種語言時觸發(fā)
/* $('#lang-selector').on('change', function() {
if (this.value) {
$('#calendar').fullCalendar('option', 'lang', this.value);
}
}); */
});
</script>
</html>