前言
本文是一款基於layui實現的日歷記事本。我們可以根據點擊頁面上的日期,給這一天添加一個事件提醒。靜態資源來自網絡:http://www.jq22.com/jquery-info19169 。后台是用java語言實現。其中用到的技術有:LayUI,jQuery ajax,Servlet,MySQL和DBUtils。非常適合用作JavaWeb階段的綜合練習。
使用IDEA創建web項目后,導入MySQL驅動包,C3P0和DBUtils的jar包。將靜態資源復制到項目的web目錄下。
![]()
經分析,日歷記事本業務只與日期和給這個日期添加的事件有關。所以,設置了mark_date和mark_note兩個字段,分別存儲日期和這個日期對應的事件。另外,又設置了create_time和update_time存儲設置和更改的時間。建表語句如下:
CREATE TABLE `date_note` ( `id` int(11) NOT NULL AUTO_INCREMENT, `mark_date` date DEFAULT NULL, `mark_note` varchar(100) DEFAULT NULL, `create_time` date DEFAULT NULL, `update_time` date DEFAULT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8;
注:本項目只有涉及這一張表。如有需求,可增加用戶表,將用戶表和日歷表進行關聯。
將C3P0的配置文件c3p0-config.xml復制到src下,並將相關信息修改成自己的數據庫信息。C3P0配置文件信息如下:
<c3p0-config> <default-config> <property name="driverClass">com.mysql.jdbc.Driver</property> <property name="jdbcUrl">jdbc:mysql://localhost:3306/date_note</property> <property name="user">root</property> <property name="password">****</property> </default-config></c3p0-config>
使用IDEA配置tomcat啟動項目,項目啟動成功后自動加載首頁。首頁如下:
![]()
所有的前端代碼都在index.html中。js部分使用的是LayUI的語法。
1、頁面加載數據(1)頁面加載時發送ajax請求 //定義json var data={}; //頁面加載后初始化data $.post("/noteWeb/queryAll",function (res) { console.log(res); data = JSON.parse(res); var new_date = new Date(); loding_date(new_date ,data); });
【注意】data是json數據。數據格式如下:
(2) 將加載的數據展示到日歷上
通過LayUI日歷插件的render方法中設置mark參數,將查詢到的數據與日歷插件綁定:
![]()
代碼如下:
//日歷插件調用方法 function loding_date(date_value,data){ laydate.render({ elem: '#test-n2' ,type: 'date' ,theme: 'grid' ,max: '2099-06-16 23:59:59' ,position: 'static' ,range: false ,value:date_value ,calendar: true ,btns:false ,done: function(value, date, endDate){ console.log(value); //得到日期生成的值,如:2017-08-18 console.log(date); //得到日期時間對象:{year: 2017, month: 8, date: 18, hours: 0, minutes: 0, seconds: 0} console.log(endDate); //得結束的日期時間對象,開啟范圍選擇(range: true)才會返回。對象成員同上。 //layer.msg(value) //調用彈出層方法 date_chose(value,data); } , mark:data//重要json! }); }
后台提交的數據是通過LayUI的彈出層收集的。點擊日歷插件上的某一天,會彈出如下圖的彈出層:
![]()
其中彈出層代碼實現如下:
//定義彈出層方法 function date_chose(obj_date,data){ var index = layer.open({ type: 1, skin: 'layui-layer-rim', //加上邊框 title:'添加記錄', area: ['400px', 'auto'], //寬高 btn:['確定','撤銷','取消'], content: '<div class="text_box">'+ '<form class="layui-form" action="">'+ '<div class="layui-form-item layui-form-text">'+ ' <textarea id="text_book" placeholder="請輸入內容" class="layui-textarea"></textarea>'+ '</div>'+ '</form>'+ '</div>' ,success:function(){ $('#text_book').val(data[obj_date]) } ,yes:function (){ //調用添加/編輯標注方法 if($('#text_book').val()!=''){ chose_moban(obj_date,data); layer.close(index); }else{ layer.msg('不能為空', {icon: 2}); } },btn2:function (){ chexiao(obj_date,data); } }); }
彈出層中的數據書寫完畢后,點擊確定按鈕會執行以上代碼的yes:function(){}回調函數,如下圖:
![]()
我們只需要在chose_moban(obj_date,data)方法中通過ajax技術向后台發送請求,將數據插入數據庫即可。具體代碼如下:
//定義添加/編輯標注方法 function chose_moban(obj_date,markJson){ //獲取彈出層val var chose_moban_val = $('#text_book').val(); $('#test-n2').html('');//重要!由於插件是嵌套指定容器,再次調用前需要清空原日歷控件 //添加屬性 markJson[obj_date] = chose_moban_val; console.log(JSON.stringify(markJson)); //使用ajax向后台插入數據 $.post("/noteWeb/insert",{markDate:obj_date,markNote:markJson[obj_date]},function () { }); //再次調用日歷控件, loding_date(obj_date,markJson);//重要!,再標注一個日期后會刷新當前日期變為初始值,所以必須調用當前選定日期。 }
完整前端代碼如下:
<script> layui.use(['layer', 'form','jquery','laydate'], function() { var layer = layui.layer, $ = layui.jquery, laydate = layui.laydate, form = layui.form; //定義json var data={}; //頁面加載后初始化data $.post("/noteWeb/queryAll",function (res) { console.log(res); data = JSON.parse(res); var new_date = new Date(); loding_date(new_date ,data); }); //日歷插件調用方法 function loding_date(date_value,data){ laydate.render({ elem: '#test-n2' ,type: 'date' ,theme: 'grid' ,max: '2099-06-16 23:59:59' ,position: 'static' ,range: false ,value:date_value ,calendar: true ,btns:false ,done: function(value, date, endDate){ console.log(value); //得到日期生成的值,如:2017-08-18 console.log(date); //得到日期時間對象:{year: 2017, month: 8, date: 18, hours: 0, minutes: 0, seconds: 0} console.log(endDate); //得結束的日期時間對象,開啟范圍選擇(range: true)才會返回。對象成員同上。 //layer.msg(value) //調用彈出層方法 date_chose(value,data); } , mark:data//重要json! }); } //獲取隱藏的彈出層內容 var date_choebox = $('.date_box').html(); //定義彈出層方法 function date_chose(obj_date,data){ var index = layer.open({ type: 1, skin: 'layui-layer-rim', //加上邊框 title:'添加記錄', area: ['400px', 'auto'], //寬高 btn:['確定','撤銷','取消'], content: '<div class="text_box">'+ '<form class="layui-form" action="">'+ '<div class="layui-form-item layui-form-text">'+ ' <textarea id="text_book" placeholder="請輸入內容" class="layui-textarea"></textarea>'+ '</div>'+ '</form>'+ '</div>' ,success:function(){ $('#text_book').val(data[obj_date]) } ,yes:function (){ //調用添加/編輯標注方法 if($('#text_book').val()!=''){ chose_moban(obj_date,data); layer.close(index); }else{ layer.msg('不能為空', {icon: 2}); } },btn2:function (){ chexiao(obj_date,data); } }); } //定義添加/編輯標注方法 function chose_moban(obj_date,markJson){ //獲取彈出層val var chose_moban_val = $('#text_book').val(); $('#test-n2').html('');//重要!由於插件是嵌套指定容器,再次調用前需要清空原日歷控件 //添加屬性 markJson[obj_date] = chose_moban_val; console.log(JSON.stringify(markJson)); //使用ajax向后台插入數據 $.post("/noteWeb/insert",{markDate:obj_date,markNote:markJson[obj_date]},function () { }); //再次調用日歷控件, loding_date(obj_date,markJson);//重要!,再標注一個日期后會刷新當前日期變為初始值,所以必須調用當前選定日期。 } //撤銷選擇 function chexiao(obj_date,markJson){ //刪除指定日期標注 delete markJson[obj_date]; console.log(JSON.stringify(markJson)); //原理同添加一致 $('#test-n2').html(''); loding_date(obj_date,markJson); }});</script>
后台使用的技術是Servlet+DBUtils+MySQL。
1、查詢所有
頁面加載時向后台發送請求查詢數據。查詢到的數據手動拼接成JSON字符串,數據返回到頁面后再使用JSON.parse()方法解析。查詢邏輯代碼如下:
web層代碼:
@WebServlet(name = "QueryListServlet",urlPatterns = "/noteWeb/queryAll") public class QueryListServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); NoteService noteService = new NoteService(); String jsonStr = noteService.queryStringList(); response.getWriter().write(jsonStr); }}
service層代碼如下:
public String queryStringList() { NoteDao noteDao = new NoteDao(); List<NoteMark> noteMarkList = noteDao.queryAll(); //將集合拼接成JSON字符串 StringBuffer sb = new StringBuffer(); if(null != noteMarkList && noteMarkList.size()>0){ for (NoteMark noteMark:noteMarkList) { sb.append(",\""+noteMark.getMarkDate()+"\":\""+noteMark.getMarkNote()+"\""); } } String sbStr = sb.toString().replaceAll("\n",""); String str ="{"+ sbStr.substring(1,sbStr.length())+"}"; return str; }
dao層代碼如下:
public List<NoteMark> queryAll() { QueryRunner qr = new QueryRunner(JDBCUtil.getDataSource()); String sql = "select id,mark_date as markDate,mark_note as markNote,create_time as createDate,update_time as updateDate from date_note "; try { List<NoteMark> noteMarkList = qr.query(sql, new BeanListHandler<>(NoteMark.class)); return noteMarkList; } catch (SQLException e) { e.printStackTrace(); } return null; }
用戶通過點擊頁面上某個日期后向后台發送請求添加數據。請求的數據如下:
{markDate:obj_date,markNote:markJson[obj_date]}
后台拿到數據后,需要根據markDate進行判斷。如果這個日期已經插入數據,則根據日期更新這條數據。如果這個日期的數據沒有插入則插入這條數據:
Web層代碼如下:
@WebServlet(name = "NoteInsertServlet",urlPatterns = "/noteWeb/insert") public class NoteInsertServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //插入日歷記事本數據 //獲取日期 String markDate = request.getParameter("markDate"); //獲取事件 String markNote = request.getParameter("markNote"); //將數據封裝到實體類中 NoteMark noteMark = new NoteMark(); noteMark.setUpdateDate(new Date()); noteMark.setMarkDate(DateFormartUtil.getDateFromStrDate(markDate)); noteMark.setMarkNote(markNote); //調用service層處理相關業務 NoteService noteService = new NoteService(); noteService.insertOrUpdateNoteMark(noteMark); } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { }}
Service層代碼如下:
package com.heima.service; import com.heima.bean.NoteMark;import com.heima.dao.NoteDao;import com.heima.util.JDBCUtil;import java.sql.Connection;import java.sql.SQLException;import java.util.Date;import java.util.List;/** * @author buguniao * @date 2018-06-18 18:34 */public class NoteService { public void insertOrUpdateNoteMark(NoteMark noteMark) { //Dao NoteDao noteDao = new NoteDao(); Connection connection = null; try { connection = JDBCUtil.getConnection(); } catch (SQLException e) { e.printStackTrace(); } //根據日期判斷是新增還是更新操作 Date markDate = noteMark.getMarkDate(); NoteMark myNoteMark = noteDao.getNoteByNoteDate(markDate); if(null == myNoteMark){ //新增操作 noteMark.setCreateDate(new Date()); noteDao.insertDateNote(noteMark); }else{ myNoteMark.setMarkNote(noteMark.getMarkNote()); myNoteMark.setUpdateDate(new Date()); //更新操作 noteDao.updateDateNote(myNoteMark); } }}
Dao層代碼如下:
package com.heima.dao; import com.heima.bean.NoteMark;import com.heima.util.JDBCUtil;import org.apache.commons.dbutils.QueryRunner;import org.apache.commons.dbutils.handlers.BeanHandler;import org.apache.commons.dbutils.handlers.BeanListHandler;import java.sql.Connection;import java.sql.SQLException;import java.util.Date;import java.util.List;/** * @author buguniao * @date 2018-06-18 18:34 */public class NoteDao { /** * 根據日期查詢存儲的事件 * @param markDate * @return */ public NoteMark getNoteByNoteDate(Date markDate) { QueryRunner qr = new QueryRunner(JDBCUtil.getDataSource()); String sql = "select id,mark_date as markDate,mark_note as markNote,create_time as createDate,update_time as updateDate from date_note where mark_date = ?"; try { NoteMark noteMark = qr.query(sql, new BeanHandler<>(NoteMark.class), markDate); return noteMark; } catch (SQLException e) { e.printStackTrace(); } return null; } /** * 往數據庫中插入事件 * @param noteMark */ public void insertDateNote( NoteMark noteMark) { QueryRunner qr = new QueryRunner(JDBCUtil.getDataSource()); String sql = "insert into date_note values(null,?,?,?,?)"; try { qr.update(sql,noteMark.getMarkDate(),noteMark.getMarkNote(),noteMark.getCreateDate(),noteMark.getUpdateDate()); } catch (SQLException e) { e.printStackTrace(); } } /** * 根據日期更新 * @param noteMark */ public void updateDateNote( NoteMark noteMark) { QueryRunner qr = new QueryRunner(JDBCUtil.getDataSource()); String sql = "update date_note set mark_note=? ,create_time=? , update_time=? where mark_date = ?"; try { qr.update(sql,noteMark.getMarkNote(),noteMark.getCreateDate(),noteMark.getUpdateDate(),noteMark.getMarkDate()); } catch (SQLException e) { e.printStackTrace(); } }} public class DateFormartUtil { /** * 將字符串date轉化成java.util.Date類型數據 * @param strDate * @return */ public static Date getDateFromStrDate(String strDate){ SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); try { Date parse = sdf.parse(strDate); return parse; } catch (ParseException e) { e.printStackTrace(); return null; } }} 2、JDBC工具類 public class JDBCUtil { private static ComboPooledDataSource cpds = new ComboPooledDataSource(); /** * ThreadLocal */ private static ThreadLocal<Connection> local = new ThreadLocal<Connection>(); public static ComboPooledDataSource getDataSource(){ return cpds; } public static Connection getConnection() throws SQLException{ Connection conn = local.get(); if(conn == null){ conn = cpds.getConnection(); local.set(conn); } return conn; } public static void commitAndClose(Connection conn){ DbUtils.commitAndCloseQuietly(conn); } public static void rollbackAndClose(Connection conn){ DbUtils.rollbackAndCloseQuietly(conn); }} 3、實體類 package com.heima.bean; import java.util.Date;/** * @author buguniao * @date 2018-06-18 18:34 */public class NoteMark { private Integer id; private Date markDate; private String markNote; private Date createDate; private Date updateDate; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Date getMarkDate() { return markDate; } public void setMarkDate(Date markDate) { this.markDate = markDate; } public String getMarkNote() { return markNote; } public void setMarkNote(String markNote) { this.markNote = markNote; } public Date getCreateDate() { return createDate; } public void setCreateDate(Date createDate) { this.createDate = createDate; } public Date getUpdateDate() { return updateDate; } public void setUpdateDate(Date updateDate) { this.updateDate = updateDate; } public NoteMark(Integer id, Date markDate, String markNote, Date createDate, Date updateDate) { this.id = id; this.markDate = markDate; this.markNote = markNote; this.createDate = createDate; this.updateDate = updateDate; } public NoteMark() { } @Override public String toString() { return "NoteMark{" + "id=" + id + ", markDate=" + markDate + ", markNote='" + markNote + '\'' + ", createDate=" + createDate + ", updateDate=" + updateDate + '}'; }}
1、本項目前端代碼絕大部分已經有素材提供者實現,我們只需要在對應的地方添加ajax向后台發送請求即可;
2、本項目是針對JavaWeb階段的學員設計的,所以后台主要使用的是Servlet技術。
|
<ignore_js_op>