2.dao层
继承我们的BaseDao方便编写我们的dao层,如果想深入了解什么是BaseDao的同志可以参考我所编写的自定义MVC。
BaseDao
package com.zking.util; import java.lang.reflect.Field; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * 所有Dao层的父类 BookDao UserDao OrderDao ... * * @author Administrator * * @param <T> */ public class BaseDao<T> { /** * 适合多表联查的数据返回 * @param sql * @param pageBean * @return * @throws SQLException * @throws InstantiationException * @throws IllegalAccessException */ public List<Map<String, Object>> executeQuery(String sql, PageBean pageBean) throws SQLException, InstantiationException, IllegalAccessException { List<Map<String, Object>> list = new ArrayList<>(); Connection con = DBAccess.getConnection(); PreparedStatement pst = null; ResultSet rs = null; /* * 是否需要分页? 无需分页(项目中的下拉框,查询条件教员下拉框,无须分页) 必须分页(项目中列表类需求、订单列表、商品列表、学生列表...) */ if (pageBean != null && pageBean.isPagination()) { // 必须分页(列表需求) String countSQL = getCountSQL(sql); pst = con.prepareStatement(countSQL); rs = pst.executeQuery(); if (rs.next()) { pageBean.setTotal(String.valueOf(rs.getObject(1))); } // 挪动到下面,是因为最后才处理返回的结果集 // -- sql=SELECT * FROM t_mvc_book WHERE bname like '%圣墟%' // -- pageSql=sql limit (page-1)*rows,rows 对应某一页的数据 // -- countSql=select count(1) from (sql) t 符合条件的总记录数 String pageSQL = getPageSQL(sql, pageBean);// 符合条件的某一页数据 pst = con.prepareStatement(pageSQL); rs = pst.executeQuery(); } else { // 不分页(select需求) pst = con.prepareStatement(sql);// 符合条件的所有数据 rs = pst.executeQuery(); } // 获取源数据 ResultSetMetaData md = rs.getMetaData(); int count = md.getColumnCount(); Map<String, Object> map = null; while (rs.next()) { map = new HashMap<>(); for (int i = 1; i <= count; i++) { // map.put(md.getColumnName(i), rs.getObject(i)); map.put(md.getColumnLabel(i), rs.getObject(i)); } list.add(map); } return list; } /** * * @param sql * @param attrs * map中的key * @param paMap * jsp向后台传递的参数集合 * @return * @throws SQLException * @throws NoSuchFieldException * @throws SecurityException * @throws IllegalArgumentException * @throws IllegalAccessException */ public int executeUpdate(String sql, String[] attrs, Map<String, String[]> paMap) throws SQLException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { Connection con = DBAccess.getConnection(); PreparedStatement pst = con.prepareStatement(sql); for (int i = 0; i < attrs.length; i++) { pst.setObject(i + 1, JsonUtils.getParamVal(paMap, attrs[i])); } return pst.executeUpdate(); } /** * 批处理 * @param sqlLst * @return */ public static int executeUpdateBatch(String[] sqlLst) { Connection conn = null; PreparedStatement stmt = null; try { conn = DBAccess.getConnection(); // 设置不自动提交 conn.setAutoCommit(false); for (String sql : sqlLst) { stmt = conn.prepareStatement(sql); stmt.executeUpdate(); } conn.commit(); } catch (Exception e) { try { conn.rollback(); } catch (SQLException e1) { e1.printStackTrace(); throw new RuntimeException(e1); } e.printStackTrace(); throw new RuntimeException(e); } finally { DBAccess.close(conn, stmt, null); } return sqlLst.length; } /** * 通用的增删改方法 * * @param book * @throws Exception */ public int executeUpdate(String sql, T t, String[] attrs) throws Exception { // String[] attrs = new String[] {"bid", "bname", "price"}; Connection con = DBAccess.getConnection(); PreparedStatement pst = con.prepareStatement(sql); // pst.setObject(1, book.getBid()); // pst.setObject(2, book.getBname()); // pst.setObject(3, book.getPrice()); /* * 思路: 1.从传进来的t中读取属性值 2.往预定义对象中设置了值 * * t->book f->bid */ for (int i = 0; i < attrs.length; i++) { Field f = t.getClass().getDeclaredField(attrs[i]); f.setAccessible(true); pst.setObject(i + 1, f.get(t)); } return pst.executeUpdate(); } /** * 通用分页查询 * * @param sql * @param clz * @return * @throws Exception */ public List<T> executeQuery(String sql, Class<T> clz, PageBean pageBean) throws Exception { List<T> list = new ArrayList<T>(); Connection con = DBAccess.getConnection(); ; PreparedStatement pst = null; ResultSet rs = null; /* * 是否需要分页? 无需分页(项目中的下拉框,查询条件教员下拉框,无须分页) 必须分页(项目中列表类需求、订单列表、商品列表、学生列表...) */ if (pageBean != null && pageBean.isPagination()) { // 必须分页(列表需求) String countSQL = getCountSQL(sql); pst = con.prepareStatement(countSQL); rs = pst.executeQuery(); if (rs.next()) { pageBean.setTotal(String.valueOf(rs.getObject(1))); } // 挪动到下面,是因为最后才处理返回的结果集 // -- sql=SELECT * FROM t_mvc_book WHERE bname like '%圣墟%' // -- pageSql=sql limit (page-1)*rows,rows 对应某一页的数据 // -- countSql=select count(1) from (sql) t 符合条件的总记录数 String pageSQL = getPageSQL(sql, pageBean);// 符合条件的某一页数据 pst = con.prepareStatement(pageSQL); rs = pst.executeQuery(); } else { // 不分页(select需求) pst = con.prepareStatement(sql);// 符合条件的所有数据 rs = pst.executeQuery(); } while (rs.next()) { T t = clz.newInstance(); Field[] fields = clz.getDeclaredFields(); for (Field f : fields) { f.setAccessible(true); f.set(t, rs.getObject(f.getName())); } list.add(t); } return list; } /** * 将原生SQL转换成符合条件的总记录数countSQL * * @param sql * @return */ private String getCountSQL(String sql) { // -- countSql=select count(1) from (sql) t 符合条件的总记录数 return "select count(1) from (" + sql + ") t"; } /** * 将原生SQL转换成pageSQL * * @param sql * @param pageBean * @return */ private String getPageSQL(String sql, PageBean pageBean) { // (this.page - 1) * this.rows // pageSql=sql limit (page-1)*rows,rows return sql + " limit " + pageBean.getStartIndex() + "," + pageBean.getRows(); } }
MeetinginfoDaoImpl
package com.xw.dao; import java.sql.SQLException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.Map; import com.xw.entity.Meetinginfo; import com.zking.util.BaseDao; import com.zking.util.PageBean; import com.zking.util.StringUtils; /** * Meetingroominfo数据访问层接口实现 * * @author 索隆 * */ public class MeetinginfoDaoImpl extends BaseDao<Meetinginfo> implements IMeetinginfoDao { /** * 新增会议发布数据 * * @param minfo * @return * @throws Exception */ @Override public int add(Meetinginfo minfo) throws Exception { // sql语句编写 String sql = "insert into t_oa_meeting_info (title,content,canyuze,liexize,zhuchiren,location,startTime,endTime,remark) values(?,?,?,?,?,?,?,?,?)"; return super.executeUpdate(sql, minfo, new String[] { "title", "content", "canyuze", "liexize", "zhuchiren", "location", "startTime", "endTime", "remark" }); } }
3.JSP页面
将官网拷贝下来的内容进行修改后的页面。
addMeeting.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ include file="/common/static.jsp"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <script type="text/javascript" src="../../Layui/static/js/meeting/addMeeting.js"></script> <title>会议发布</title> </head> <body> <form class="layui-form" action="" lay-filter="example"> <div class="layui-form-item"> <button id="btn_add" type="submit" class="layui-btn" lay-submit="" lay-filter="meeting">立即提交</button> <button id="btn_reset" type="reset" class="layui-btn layui-btn-primary">重置</button> </div> <!--------------------------------------------会议标题-------------------------------------------> <div class="layui-form-item"> <label class="layui-form-label">会议标题</label> <div class="layui-input-block"> <input type="text" name="title" lay-verify="required" autocomplete="off" placeholder="请输入标题" class="layui-input"> </div> </div> <!--------------------------------------------会议内容-------------------------------------------> <div class="layui-form-item layui-form-text"> <label class="layui-form-label">会议内容</label> <div class="layui-input-block"> <textarea name="content" lay-verify="required" placeholder="请输入内容" class="layui-textarea"></textarea> </div> </div> <!--------------------------------------------参与者-------------------------------------------> <div class="layui-form-item"> <label class="layui-form-label">参与者</label> <div class="layui-input-block"> <select name="canyuze" xm-select="canyuzhe" xm-select-skin="primary" id="mySelect1"> </select> </div> </div> <!--------------------------------------------列席者-------------------------------------------> <div class="layui-form-item"> <label class="layui-form-label">列席者</label> <div class="layui-input-block"> <select name="liexize" xm-select="liexizhe" xm-select-skin="primary" id="mySelect2"> </select> </div> </div> <!--------------------------------------------主持人-------------------------------------------> <div class="layui-form-item"> <label class="layui-form-label">主持人</label> <div class="layui-input-block"> <input type="text" readonly="readonly" name="" value="${user.name }" autocomplete="off" placeholder="请输入标题" class="layui-input"> <input type="hidden" name="zhuchiren" value="${user.id }" readonly /> </div> </div> <!--------------------------------------------会议地点-------------------------------------------> <div class="layui-form-item"> <label class="layui-form-label">会议地点</label> <div class="layui-input-block"> <select name="location" xm-select="huiyididian" xm-select-radio=""> </select> </div> </div> <!-----------------------------------------------日期范围 ----------------------------------------> <div class="layui-form"> <div class="layui-form-item"> <div class="layui-inline"> <label class="layui-form-label">日期范围</label> <div class="layui-inline" id="test6"> <div class="layui-input-inline"> <input type="text" autocomplete="off" id="startTime" class="layui-input" placeholder="开始日期" name="startTime"> </div> <div class="layui-form-mid">-</div> <div class="layui-input-inline"> <input type="text" autocomplete="off" id="endTime" class="layui-input" placeholder="结束日期" name="endTime"> </div> </div> </div> </div> </div> <!----------------------------------------------会议备注 ----------------------------------------> <div class="layui-form-item layui-form-text"> <label class="layui-form-label">备注</label> <div class="layui-input-block"> <textarea name="remark" placeholder="请输入会议备注" class="layui-textarea"></textarea> </div> </div> </form> </body> </html>
将逻辑代码与jsp页面进行分离,所有我们的逻辑代码都在js里面。
addMeeting.js
//--------------------------------------------------会议发布------------------------------------------------------ layui.use([ 'laydate', 'form', 'formSelects', 'jquery' ],function() { var laydate = layui.laydate, form = layui.form, formSelects = layui.formSelects, $ = layui.jquery; /* * 多功能下拉框 * formSelects.btns(ID, BTNS, config); * * @param ID xm-select的值 @param BTNS 定义操作列表, * 内置三种操作,select:全选, remove:清空, reverse:反选 */ formSelects.btns('canyuzhe', [ 'select', 'remove','reverse' ]); formSelects.btns('liexizhe', [ 'select', 'remove','reverse' ]); $.getJSON("user.action", { methodName : "queryUaerfromSelect" }, function(rs) { // console.log(rs.data); // local模式 formSelects.data('canyuzhe', 'local', { arr : rs.data }); formSelects.data('liexizhe', 'local', { arr : rs.data }); }) $.getJSON("Meetingroom.action", { methodName : "QueryMeetingroomSelect" }, function(rs) { // console.log(rs.data); // local模式 formSelects.data('huiyididian', 'local', { arr : rs.data }); }); //日期范围 laydate.render({ elem: '#test6' ,type: 'datetime' ,range: ['#startTime', '#endTime'] }); // 表单监听事件 form.on('submit(meeting)', function(data) { // 获取表单数据 var formData = data.field; // 发送请求 $.ajax({ url : 'Meetinginfo.action?methodName=add', type : 'POST', data : formData, success : function(data) { // 将字符串解析为对象 var responseData = JSON.parse(data); // 回调处理 if(responseData.success) { layer.alert('会议发布成功,请等待审批通过!!', {icon: 6}); } else { layer.alert('申请失败还请稍后再试💔', {icon: 5}); } } }); return false; }); });