留言板功能

2017-09-27 08:42:20来源:CSDN作者:baidu_32691373人点击

分享

1.实现获取留言 

2.获取更多留言

3.留言(不刷新加载到html,写入数据库)

4.回复留言(不刷新加载到html,写入数据库)

HTML部分全部代码如下:

<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>吃饭最有趣</title><script src="../../js_css/jquery-3.2.1.js"></script></head><body style="color: olive; background-color: silver;">	<div class="container">				<div class="row clearfix" style="margin-top: 40px">			<!--这是大的DIV包括body和rigth  -->			<!-- 评论区域 -->			<div class="col-md-8 column" id ="show_comment">		<!-- 这里开始写品论的内容-->		<!-- 这里用ajax来获取后台的留言数据 -->		<script type="text/javascript">			$().ready(function() {				//获取留言信息				getComment();				//查询更多				$("#moreComment").click(function () {					var _page_now = $("#moreComment").attr("name");					//alert(_page_now);					var page_now = parseInt(_page_now);					getComment(page_now);				});																});													function  getComment(page_now){		if(page_now == null || page_now < 1){			page_now = 1;		}else{			page_now = page_now + 1 ;		}		$.ajax({			url : "../../CommentServlet?method=getComment&page_now="+page_now+"&com_type=3",				dataType : "JSON",				success : function(data) {				//	var json = jQuery.parseJSON(data); 				//$("#myText").text(json);				$.each(data,function(i,va){//这是可以的					//alert(va["count_all"]);i为data的索引,va为该索引的对象。										//获取当前页,并复制到					$("#moreComment").attr("name",va.page_now);					//alert(va.page_now);					//对象变量名[“属性名”] 得到该对象下该属性名的属性值					var list = va["list"];										//写一个存放所有评论的com_id的数组,用于后面和con_pid进行比较,如果相同,则说明,该评论有回复,就加上回复的内容					$.each(list,function(p,va){						var com_id = va.com_pid;						if(com_id == ""){//没有回复							appendToDiv(va);//直接生成评论						}					});					$.each(list,function(p,va){							var com_id = va.com_pid;							if(com_id != ""){//有回复							var html = jsonToHtml(va);							$("#"+com_id).children(".panel-body").append(html);							//$(html).insertAfter("form[name='pinglun']"); 							}					});					});				},			error : function() {				alert("ajax错误");			}		});	}				function jsonToHtml(va){	var html = "";	html = '<div class="panel panel-danger" id = "'+va.com_id+'">'+			//评论title和时间			'<div class="panel-heading">' +			'<h3 class="panel-title">' +			'<div id="show_name">' + 			'<span class="glyphicon glyphicon-user" aria-hidden="true"></span>' +			'昵称:' + va.com_name +			'<div style="float: right;" id ="show_time">Tiime:'+va.com_date+'</div>' +			'</div>' +			'</h3>' +			'</div>' +			//评论内容			'<div class="panel-body" id="show_content"><div id="show_other"></div>   '+va.com_content+'</div>' +			//评论未			'<div class="panel-footer" align="left">' +			'<div align="right">' +			'<span class="glyphicon glyphicon-send" aria-hidden="true"></span>' +			'<small><button type="button" class="btn btn-sm" id="replay'+va.com_id+'" onclick="replay('+va.com_id+');">回复</button></small>' +			'</div>'+			'</div>'			'</div>';	return html;	}	function appendToDiv(va){		var html = jsonToHtml(va);		$(html).insertBefore("#more"); 	}		function replay(com_id) {//这里把回复留言的com_id拿到,然后直接在该com_id下的id为show_content得div下追加相应的评论功能的表单	var html = "";	html = 	'<form class="form-horizontal" role="form" style="background-color: activeborder;"  ' +			'action="../../CommentServlet" target="tiDai">'  + 			'<input type="hidden" name="method" value="updataComment"/>' +				'<div class="form-group">' +		    '<label for="inputEmail3" class="col-sm-2 control-label">昵称</label>' +		    '<div class="col-sm-4">' +			'<input type="text" name="name"/>' +			'</div>' +			'</div>' +			'<div class="form-group">' +		 	'<label for="inputPassword3" class="col-sm-2 control-label">内容</label>' +			'<div class="col-sm-4">' +			'<textarea rows="9" cols="75%" id="textarea" name="com_content"></textarea>' +			'</div>' +			'</div>' +			'<div class="form-group">' +			'<div class="col-sm-offset-2 col-sm-4"   style="float: right;">'+			'<input type="submit" class="btn" id="submit'+com_id+'" onclick="return submitComment('+com_id+');" value="提交"/>'+			'</div>'+			'</div>'+			'<input type="hidden" name="com_pid" value="'+com_id+'"/>'+			'<input type="hidden" name="com_type" value="3"/>'+			'</form>' +			'<iframe name="tiDai" style="display:none;"></iframe>';	$("#"+com_id).children(".panel-body").append(html);	}			//form完成提交表单和加载到页面的两项任务	function submitForm() {		$("form[name='pinglun']").submit();		submitComment(0);	}		function submitComment(com_id){		if(com_id > 0 ){//这里是对留言的回复做显示()				var $name = $("#"+com_id).children("div:eq(1)").children("form").children("div:eq(0)").children("div").children("input");				var $content = $("#"+com_id).children("div:eq(1)").children("form").children("div:eq(1)").children("div").children("textarea");					var html = "";					html = '<div class="panel panel-danger" id = "">'+					//评论title和时间					'<div class="panel-heading">' +					'<h3 class="panel-title">' +					'<div id="show_name">' + 					'<span class="glyphicon glyphicon-user" aria-hidden="true"></span>' +					'昵称:' + $name.val() +					'<div style="float: right;" id ="show_time">Tiime:'+new Date()+'</div>' +					'</div>' +					'</h3>' +					'</div>' +					//评论内容					'<div class="panel-body" id="show_content"><div id="show_other"></div>   '+					$content.val()+'</div>' +					'</div>'					'</div>';				$("#"+com_id).children(".panel-body").append(html);				//移除这个form元素				$("#"+com_id).children("div:eq(1)").children("form").remove();							}else{//这里就是直接写留言,然后显示								var form_$ = $("form[name='pinglun']");//这里是评论的父节点					var html = "";					html = '<div class="panel panel-danger">'+					//评论title和时间					'<div class="panel-heading">' +					'<h3 class="panel-title">' +					'<div id="show_name">' + 					'<span class="glyphicon glyphicon-user" aria-hidden="true"></span>' +					'昵称:' + form_$.children("div:eq(0)").children("div").children("input").val() +					'<div style="float: right;" id ="show_time">Tiime:'+new Date()+'</div>' +					'</div>' +					'</h3>' +					'</div>' +					//评论内容					'<div class="panel-body" id="show_content"><div id="show_other"></div>   '+					form_$.children("div:eq(1)").children("div").children("textarea").val()+'</div>' +										'</div>'					'</div>';				$(html).insertAfter(form_$);				form_$.children("div:eq(0)").children("div").children("input").val("");				form_$.children("div:eq(1)").children("div").children("textarea").val("");							}	}				</script><!-- 提示  -->			<div class="container-fluid">				<div class="row-fluid">					<div class="span12">						<div class="alert alert-success">							 <button type="button" class="close" data-dismiss="alert">×</button>							<h4>								上帝很美:							</h4> <strong>    心爱的留言功能终于完美完成了....</strong>						</div>					</div>				</div>			</div><!-- 这是另一款评论表单的样式 开始-->			<form class="form-horizontal" role="form" action="../../CommentServlet" method="updataComment" name="pinglun" target="tiDai">			<input type="hidden" name="method" value="updataComment"/>				<div class="form-group" >					 <label for="inputEmail3" class="col-sm-2 control-label">昵称</label>					<div class="col-sm-4">					<input type="text" name="name"/>					</div>				</div>				<div class="form-group">					 <label for="inputPassword3" class="col-sm-2 control-label">内容</label>					<div class="col-sm-4">						<textarea rows="9" cols="75%"  name="com_content"></textarea>					</div>				</div>				<div class="form-group">					<div class="col-sm-offset-2 col-sm-4"  style="float: right;">						 <input type="button" class="btn btn-rigth"  onclick="return submitForm();"  value="提交" />					</div>				</div>				<input type="hidden" name="com_pid" value="no"/>				<input type="hidden" name="com_type" value="3"/>			</form>			<iframe name="tiDai" style="display:none;"></iframe><!-- 这是另一款评论表单的样式 结束-->				<!-- 分页区开始 -->				<!-- 分页区结束-->		<div class="container-fluid" id="more">			<div class="row-fluid">				<div class="span12">					 <button class="btn btn-success btn-block" type="button" id="moreComment" name="">查看更多留言</button>				</div>			</div>		</div>				<!-- 评论部分结束 -->			</div>					</div></body><link href="../../js_css/from.css" rel="stylesheet" /><link href="../../js_css/bootstrap.min.css" rel="stylesheet"><script src="../../js_css/jquery.min.js"></script><script src="../../js_css/bootstrap.min.js"></script></html>

下面是后台传回来的json格式的数据:
[{"count_all":39,"page_now":1,"list":[{"com_type":"3","com_pid":"104","art_id":"0","com_id":108,"com_content":"ss","com_date":"2017/9/26  5:55:24 PM","com_name":"ss"},{"com_type":"3","com_pid":"","art_id":"0","com_id":107,"com_content":"aa","com_date":"2017/9/26  5:55:10 PM","com_name":"df"},{"com_type":"3","com_pid":"","art_id":"0","com_id":106,"com_content":"的","com_date":"2017/9/26  5:41:9 PM","com_name":"的放到"},{"com_type":"3","com_pid":"","art_id":"0","com_id":105,"com_content":"的","com_date":"2017/9/26  5:41:3 PM","com_name":"的放到"},{"com_type":"3","com_pid":"","art_id":"0","com_id":104,"com_content":"放","com_date":"2017/9/26  5:36:18 PM","com_name":"覆盖"},{"com_type":"3","com_pid":"93","art_id":"0","com_id":103,"com_content":"的","com_date":"2017/9/26  5:33:11 PM","com_name":"地方"},{"com_type":"3","com_pid":"92","art_id":"0","com_id":102,"com_content":"第三方三生三世","com_date":"2017/9/26  5:17:20 PM","com_name":"第三方"},{"com_type":"3","com_pid":"96","art_id":"0","com_id":101,"com_content":"电饭锅电饭锅框架","com_date":"2017/9/26  4:37:25 PM","com_name":"电饭锅"},{"com_type":"3","com_pid":"95","art_id":"0","com_id":100,"com_content":"地方规定地方地方规定","com_date":"2017/9/26  4:31:22 PM","com_name":"梵蒂冈"},{"com_type":"3","com_pid":"97","art_id":"0","com_id":99,"com_content":"胜多负少的","com_date":"2017/9/26  4:30:44 PM","com_name":"多福多寿"}],"page_all":4,"url":"CommentServlet?method=getComment&com_type=3","page_size":10}]

下面是servlet内容:

package blog.mkk.comment.web.servlet;import java.io.IOException;import java.io.PrintWriter;import java.sql.SQLException;import java.util.Calendar;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import blog.mkk.comment.domain.Comment;import blog.mkk.comment.service.CommentService;import blog.mkk.commonUtils.Page;import net.sf.json.JSONArray;import net.sf.json.JSONException;/** * Servlet implementation class CommentServlet */public class CommentServlet extends HttpServlet {	private static final long serialVersionUID = 1L;		CommentService commentService = new CommentService(); 		protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {			/*		 * 这里调用相应的方法来解决问题		 * */		String method1 = request.getParameter("method");		if(method1 != null && method1.equals("getComment") ){			try {				getComment(request,response);			} catch (SQLException e) {				// TODO Auto-generated catch block				e.printStackTrace();			} 		}else if(method1 != null && method1.equals("updataComment")){			try {				updataComment(request,response);			} catch (SQLException e) {				// TODO Auto-generated catch block				e.printStackTrace();			}		}			}	/**	 * 2.更新留言的内容	 * @throws SQLException 	 */	 public void updataComment(HttpServletRequest request,HttpServletResponse response) throws SQLException{		 //这里开始获取comment的内容		 //http://localhost:8080/blog/CommentServlet?method=updataComment&name=srg&com_content=sdgsgsdgsd&com_pid=no&com_type=3		 String com_pid = request.getParameter("com_pid");		 String com_content = request.getParameter("com_content");		 String com_name = request.getParameter("name");		 		 if(com_content == "" ||com_name == "" ){			 return;		 }		 		 String com_type = request.getParameter("com_type");		 System.out.println("com_content:"+com_content);		 Comment m = new Comment();		 if(com_pid.equals("no")){//判断pid是否为“no”,如果是,这该内容为新的留言,并不是回复的内容			 m.setCom_pid(null);		 }else{			 m.setCom_pid(com_pid);		 }		 m.setCom_content(com_content);		 	 	Calendar cal = Calendar.getInstance();        int year = cal.get(Calendar.YEAR);//获取年份        int month=cal.get(Calendar.MONTH)+1;//获取月份         int day=cal.get(Calendar.DATE);//获取日         int hour=cal.get(Calendar.HOUR);//小时         int minute=cal.get(Calendar.MINUTE);//分                    int second=cal.get(Calendar.SECOND);//秒         int r = cal.get(Calendar.AM_PM);//询上午还是下午        String AMorPM = "";        if(r!=cal.get(Calendar.AM)){//如果上午        	AMorPM = "AM";        }else {        	AMorPM = "PM";        }		 String date = year+"/"+month+"/"+day+"  "+hour+":"+minute+":"+second+" "+AMorPM;		 m.setCom_date(date);		 m.setCom_type(com_type);		 m.setCom_name(com_name);		 m.setArt_id("0");		 		 //更新		 commentService.updataComment(m);		 	 }			/**	 * 1.获取评论内容	 * @throws SQLException 	 * @throws JSONException 	 */	protected void getComment(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {		request.setCharacterEncoding("utf-8");		response.setContentType("text/html;charset=utf-8");		String com_type = request.getParameter("com_type");		String page_now = request.getParameter("page_now");				Page<Comment> page = commentService.findByCom_typeAndPage_now(com_type, page_now);		String url = "CommentServlet?method=getComment&com_type=3";		page.setUrl(url);				JSONArray json = JSONArray.fromObject(page);				PrintWriter   pw = response.getWriter();		json.write(pw);		System.out.println(json.toString());		pw.flush();		pw.close();		}	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {		// TODO Auto-generated method stub		doGet(request, response);	}}
dao实现:

package blog.mkk.comment.dao;import java.sql.SQLException;import java.util.List;import org.apache.commons.dbutils.QueryRunner;import org.apache.commons.dbutils.handlers.BeanListHandler;import org.apache.commons.dbutils.handlers.ScalarHandler;import blog.mkk.comment.domain.Comment;import blog.mkk.commonUtils.Page;import cn.itcast.jdbc.TxQueryRunner;//这个包可以自己百度上搜索public class CommentDao {	/**	 * 评论相关的持久层代码	 */	QueryRunner queryRunner = new TxQueryRunner();			/*添加新的回复*/	public void updataComment(Comment m) throws SQLException{	String sql = "insert into blog.comment (com_name,com_date,com_content,art_id,com_type,com_pid) values(?,?,?,?,?,?)";	Object[] params = {m.getCom_name(),m.getCom_date(),m.getCom_content(),m.getArt_id(),m.getCom_type(),m.getCom_pid()}; 	queryRunner.update(sql,params);	}				/**	 * 1.根据com_type查询所有评论内容	 * @throws SQLException 	 */	public Page<Comment> findByCom_typeAndPage_now(String com_type,String page_now) throws SQLException{		Page<Comment> page = new Page<>();		int page_size = 10;		String sql = "select count(*) from blog.comment "; 		Number  n = (Number)queryRunner.query(sql, new ScalarHandler());		int count = n.intValue();		int page_all = count % page_size == 0 ? count / page_size :(count / page_size) + 1; 		page.setPage_all(page_all);		page.setCount_all(count);		page.setPage_size(10);		int _page_now = Integer.parseInt(page_now);		page.setPage_now(_page_now);		int count_now = page_size * ( _page_now - 1 );		sql = "SELECT * FROM blog.comment WHERE com_type = ?  order by com_id desc limit ?, ?;";		int _com_type = Integer.parseInt(com_type);		Object[]  params = {_com_type,count_now,page_size};		List<Comment> list = queryRunner.query(sql, new BeanListHandler<Comment>(Comment.class),params);		page.setList(list);		return page;	}	}



最新文章

123

最新摄影

闪念基因

微信扫一扫

第七城市微信公众平台