`jquery与ajax页面交互
实现新闻与评论的增删改查``
package project.dao.impl;
import project.dao.BaseDao;
import project.dao.NewsDao;
import project.entity.News;
import project.entity.NewsContent;
import java.io.IOException;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class NewsDaoImpl extends BaseDao implements NewsDao {
@Override
//分页查询全部(模糊查询)新闻 根据时间降序排列
public List selectAllNewsPageing(String title,int pageNo,int pageSize) throws IOException, SQLException {
List list = new ArrayList<>();
String sql = “”;
ResultSet resultSet = null;
if (title=="" ||title==null ){
sql = “SELECT id,title,summary,author,createdate FROM news_detail " +
“ORDER BY createdate DESC LIMIT ?,?”;
Object[]params = {(pageNo-1)*pageSize,pageSize};
resultSet = excuteSql(sql,params);
}else {
sql=“SELECT id,title,summary,author,createdate FROM news_detail WHERE title LIKE ? " +
“ORDER BY createdate DESC LIMIT ?,?”;
Object[]params = {”%”+title+"%",(pageNo-1)*pageSize,pageSize};
resultSet = excuteSql(sql,params);
}
News news = null;
while (resultSet.next()){
int id = resultSet.getInt(“id”);
String newstitle = resultSet.getString(“title”);
String summary = resultSet.getString(“summary”);
String author = resultSet.getString(“author”);
Date createdate = resultSet.getDate(“createdate”);
news = new News(id,newstitle,summary,author,createdate);
list.add(news);
}
return list;
}
@Override
//分页查看评论 通过新闻编号 根据时间降序排列
public List<NewsContent> selectAllContentByNewsId(int newsid,int pageNo,int pageSize) throws IOException, SQLException {
List<NewsContent> list = new ArrayList<>();
String sql = "SELECT id,content,author ,createdate FROM news_commment WHERE newsid = ? ORDER BY createdate DESC LIMIT ?,?";
Object[]params = {newsid,(pageNo-1)*pageSize,pageSize};
ResultSet resultSet = excuteSql(sql,params);
while (resultSet.next()){
int id = resultSet.getInt("id");
String content = resultSet.getString("content");
String author = resultSet.getString("author");
Date createdate = resultSet.getDate("createdate");
NewsContent newsContent = new NewsContent(id,newsid,content,author,createdate);
list.add(newsContent);
}
return list;
}
@Override
//增加评论
public boolean addContent(NewsContent newsContent) throws IOException {
String sql = "INSERT INTO news_commment (newsid,content,author,createdate) VALUE(?,?,?,?) ";
Object[]params = {newsContent.getNewsid(),newsContent.getContent(),newsContent.getAuthor(),newsContent.getCreatedate()};
int line = excuteUpdate(sql,params);
boolean flag = false;
if (line>0){
flag = true;
System.out.println("添加成功!");
}
return flag;
}
@Override
//删除新闻功能(包括评论) 根据主键
public boolean deleteNewsById(int id) throws IOException, SQLException {
String sql = "DELETE FROM news_detail WHERE id = ? ";
Object[]params = {id};
int line = excuteUpdate(sql,params);
String sql2 = "select count(1) from news_commment where newsid = ?";
Object [] params2 = {id};
ResultSet resultSet = excuteSql(sql2,params2);
int i = 0;
while (resultSet.next()){
i = resultSet.getInt(1);
}
boolean b = this.deleteContentByNewsid(id);
boolean flag = false;
if (i>0){
if (line>0&&b==true){
flag=true;
}
}else {
if (line>0){
flag=true;
}
}
return flag;
}
@Override
public boolean deleteContentByNewsid(int newsid) throws IOException {
String sql = " DELETE FROM news_commment WHERE newsid=?";
Object []params = {newsid};
int line = excuteUpdate(sql,params);
boolean flag = false;
if (line>0){
flag=true;
}
return flag;
}
@Override
//查询新闻总数
public int CountNews(String title) throws IOException, SQLException {
String sql = "";
int count = 0;
ResultSet resultSet = null;
if (title=="" ||title==null){
sql = "select count(1) from news_detail";
Object[]params = {};
resultSet = excuteSql(sql,params);
}else {
sql="select count(1) from news_detail where title like ?";
Object[]params = {"%"+title+"%"};
resultSet = excuteSql(sql,params);
}
while (resultSet.next()){
count = resultSet.getInt(1);
}
return count;
}
@Override
//查询评论总数
public int CountContentByNewid(int newsid) throws IOException, SQLException {
String sql = "SELECT COUNT(1)FROM news_commment WHERE newsid = ?";
Object[]params = {newsid};
ResultSet resultSet = excuteSql(sql,params);
int count = 0;
while (resultSet.next()){
count = resultSet.getInt(1);
}
return count;
}
public static void main(String[] args) throws IOException, SQLException {
NewsDao newsDao = new NewsDaoImpl();
}
}
serviceImpl
package project.service.impl;
import project.dao.BaseDao;
import project.dao.NewsDao;
import project.dao.impl.NewsDaoImpl;
import project.entity.News;
import project.entity.NewsContent;
import project.service.NewsService;
import project.util.Page;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
public class NewsServiceImpl extends BaseDao implements NewsService {
private NewsDao newsDao;
public NewsServiceImpl(){
newsDao = new NewsDaoImpl();
}
@Override
public List<News> selectAllNewsPageing(String title, int pageNo, int pageSize) throws IOException, SQLException {
return newsDao.selectAllNewsPageing(title,pageNo,pageSize);
}
@Override
public List<NewsContent> selectAllContentByNewsId(int newsid, int pageNo, int pageSize) throws IOException, SQLException {
return newsDao.selectAllContentByNewsId(newsid,pageNo,pageSize);
}
@Override
public boolean addContent(NewsContent newsContent) throws IOException {
return newsDao.addContent(newsContent);
}
@Override
public boolean deleteNewsById(int id) throws IOException, SQLException {
return newsDao.deleteNewsById(id);
}
@Override
public boolean deleteContentByNewsid(int newsid) throws IOException {
return newsDao.deleteContentByNewsid(newsid);
}
@Override
public int CountNews(String title) throws IOException, SQLException {
return newsDao.CountNews(title);
}
@Override
public int CountContentByNewid(int newsid) throws IOException, SQLException {
return newsDao.CountContentByNewid(newsid);
}
@Override
public Page selectAllNews(String title, int pageNo, int pageSize) throws IOException, SQLException {
Page page = new Page();
int pageSize2 = 3;
page.setPageSize(pageSize2);
page.setCurrentPageNo(pageNo);
page.setCountNo(newsDao.CountNews(title));
page.setNewlist(newsDao.selectAllNewsPageing(title, pageNo, pageSize));
return page;
}
@Override
public Page selectAllContent(int newsid, int pageNo, int pageSize) throws IOException, SQLException {
Page page = new Page();
pageSize = 3;
page.setPageSize(pageSize);
page.setCurrentPageNo(pageNo);
page.setCountNo(newsDao.CountContentByNewid(newsid));
System.out.println("总页码=="+page.getCountNo());
page.setContentlist(newsDao.selectAllContentByNewsId(newsid, pageNo, pageSize));
return page;
}
public static void main(String[] args) throws IOException, SQLException {
NewsService newsService = new NewsServiceImpl();
Page page = newsService.selectAllNews("", 1, 3);
System.out.println(page);
Page page1 = newsService.selectAllContent(3, 1, 3);
System.out.println(page1);
}
}
servlet
package project.servlet;
import com.alibaba.fastjson.JSON;
import project.entity.NewsContent;
import project.service.NewsService;
import project.service.impl.NewsServiceImpl;
import project.util.Page;
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 java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.sql.SQLException;
@WebServlet(name = “NewsServlet”,value = “/newsServlet”)
public class NewsServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
NewsService newsService = new NewsServiceImpl();
PrintWriter out = response.getWriter();
String opr = request.getParameter("opr");
switch (opr){
case "newsList" :
int currentPageNo = Integer.parseInt(request.getParameter("currentPageNo"));
String title = request.getParameter("title");
Page page = null;
int pageSize = 3;
try {
page = newsService.selectAllNews(title,currentPageNo,pageSize);
String jsonInfo = JSON.toJSONStringWithDateFormat(page,"yyyy-MM-dd hh:mm:ss");
out.print(jsonInfo);
} catch (SQLException e) {
e.printStackTrace();
}
break;
case "commentList":
int currentPageNo2 = Integer.parseInt(request.getParameter("currentPageNo"));
int newsId = Integer.parseInt(request.getParameter("newsId"));
int pageSize2 = 3;
try {
Page page1 = newsService.selectAllContent(newsId,currentPageNo2,pageSize2);
System.out.println(page1);
String jsonInfo2 =JSON.toJSONStringWithDateFormat(page1,"yyyy-MM-dd hh:mm:ss");
out.print(jsonInfo2);
} catch (SQLException e) {
e.printStackTrace();
}
break;
case "addComment":
System.out.println("666666666");
int newsId2 = Integer.parseInt(request.getParameter("newsId"));
String content = request.getParameter("content");
System.out.println("oooo=="+content);
String author = request.getParameter("author");
Date date = new Date();
NewsContent newsContent = new NewsContent(newsId2,content,author,date);
boolean flag = newsService.addContent(newsContent);
out.print(flag);
break;
case "delete":
int id = Integer.parseInt(request.getParameter("id"));
System.out.println("iddddd==="+id);
boolean b = false;
try {
b = newsService.deleteNewsById(id);
} catch (SQLException e) {
e.printStackTrace();
}
out.print(b);
break;
default:
}
out.flush();
out.close();
}
}
HTML页面设计
主页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gbk">
<title>首页</title>
<style>
body{
position: relative;
top: 50px;
left: 150px;
}
#top{
position: relative;
left: 300px;
}
table{
width: 1000px;
border-collapse: collapse;
}
#tableContent tr:nth-child(even){background-color: aqua}
#tableContent td{border: 1px solid black;margin: 0;padding:0px; text-align: center ;height: 50px }
#tableTop{
width: 1000px;height: 60px;background-color: darkgrey;font-size: 32px;text-align: center;
}
#page{font-size: 24px;color: chartreuse}
</style>
</head>
<body>
<div id="top">
新闻标题 <input type="text" id="newstitle" name="newstitle"> <button id="selectButton">查询</button>
</div>
<div>
<table id="tableContent">
<caption id="tableTop"> 新闻列表 </caption>
<tr><td>新闻编号</td><td>新闻标题</td><td>新闻摘要</td><td>新闻作者</td><td>创建时间</td><td>操作</td></tr>
</table>
<div id="page"></div>
</div>
<input type="hidden" value="1" id="currentPageNo">
<script src="stastic/js/jquery-3.4.1.js"></script>
<script src="stastic/js/common.js"></script>
<script type="text/javascript">
$(function () {
var countPage = 0;
function initPageInfo() {
var currentPageNo = $("#currentPageNo").val();
var title = $("#newstitle").val();
var params = "currentPageNo="+currentPageNo+"&title="+title;
$.getJSON("/newsServlet",params+"&opr=newsList",success);
function success(data) {
console.log("data=="+data);
$("#currentPageNo").val(data.currentPageNo);
countPage = data.countPageNo;
//显示新闻信息
$("#tableContent tr:gt(0)").remove();
for (var i=0;i<data.newlist.length;i++){
var $tr = $("<tr id='news"+data.newlist[i].id+"'></tr>>");
$("#tableContent").append($tr);
$tr.append('<td>'+data.newlist[i].id+'</td>>')
.append('<td>'+data.newlist[i].title+'</td>>')
.append('<td>'+data.newlist[i].summary+'</td>>')
.append('<td>'+data.newlist[i].author+'</td>>')
.append('<td>'+data.newlist[i].createdate+'</td>>')
.append('<td><a href="comment.html?newsId='+data.newlist[i].id+' ">查看评论</a> <a href="addComment.html?newsId='+data.newlist[i].id+' ">评论</a> ' +
'<a href="#" id="deleteId'+data.newlist[i].id+'" deleteId="'+data.newlist[i].id+'">删除</a></td>');
}
$("#page").html("");
$("#page").append("<span>当前页" + data.currentPageNo + "/" + data.countPageNo + "</span> <span>"+data.countNo+"条记录</span><br>");
if (data.currentPageNo > 1) {
$("#page").append('<a href="#" id="firstPage">首页</a>');
$("#page").append('<a href="#" id="prePage">上一页</a>');
}
if (data.currentPageNo < data.countPageNo) {
$("#page").append('<a href="#" id="nextPage">下一页</a>');
$("#page").append('<a href="#" id="lastPage">末页</a>');
}
}
}
initPageInfo();
$(document).on("click","#firstPage,#prePage,#nextPage,#lastPage",function () {
var ida = $(this).attr("id");
switch (ida){
case "firstPage":
$("#currentPageNo").val(1);
break;
case "prePage":
var currentPageNo = $("#currentPageNo").val();
var pageNo = parseInt(currentPageNo)-1;
$("#currentPageNo").val(pageNo);
break;
case "nextPage":
var currentPageNo = $("#currentPageNo").val();
console.log("pageIndex===="+currentPageNo);
var pageNo = parseInt(currentPageNo)+1;
$("#currentPageNo").val(pageNo);
break;
case "lastPage":
$("#currentPageNo").val(countPage);
break;
}
initPageInfo();
})
$("#selectButton").click(function () {
$("#currentPageNo") .val(1);
initPageInfo();
})
//删除
$(document).on("click","[id*=deleteId]",function () {
var del = confirm("确定要删除新闻及评论吗?");
if (del==true){
var deleteId = $(this).attr("deleteId");
$.get("/newsServlet","id="+deleteId+"&opr=delete",successDel);
function successDel(data) {
console.log("data============"+data);
if (data.toString()=="true"){
$("#news"+deleteId+"").remove();
alert("删除成功");
} else {
alert("删除失败!");
}
}
}
})
})
</script>
</body>
</html>
增加评论
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gbk">
<title>增加评论页面</title>
<style>
table{
width: 500px;
border-collapse: collapse;
}
table td{
border: 1px solid black
}
#tableTop{
width: 500px;height: 60px;background-color: darkgrey;font-size: 32px;text-align: center;
}
#button{
width: 500px;
position: relative;
left: 200px;
}
</style>
</head>
<body>
<div>
<table>
<form action="">
<caption id="tableTop">增加评论</caption>
<tr><td>评论内容 <span>(*)</span></td><td><textarea name="content" id="content" cols="40" rows="5"></textarea>></td></tr>
<tr><td>评论人</td> <td><input type="text" id="author" name="author"></td> </tr>
</form>
</table>
<div id="button"><button id="submit">提交</button> <button id="back">返回</button></div>
</div>
<script src="stastic/js/jquery-3.4.1.js"></script>
<script src="stastic/js/common.js"></script>
<script type="text/javascript">
$("#submit").click(function () {
var newsId = GetQueryString("newsId");
console.log("newsid===="+newsId);
var content = $("#content").val();
var author = $("#author").val();
if (content==""||content==null){
alert("评论内容不能为空!");
}
var date = Date.parse(new Date());
var params = "newsId="+newsId+"&content="+content+"&author="+author+"&createDate="+date;
console.log("ppppppppp=="+params);
$.post("/newsServlet",params+"&opr=addComment",success);
function success(data) {
console.log(data);
if (data.toString()=="true"){
alert("添加成功");
window.location.href="http://localhost:8080/newsShow.html";
} else {
alert("添加失败");
}
}
})
$("#back").click(function () {
window.location.href="http://localhost:8080/newsShow.html";
})
</script>
</body>
</html>
评论显示页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gbk">
<title>评论页面</title>
<style>
#top{
position: relative;
left: 300px;
}
table{
width: 1000px;
border-collapse: collapse;
}
#tableContent tr:nth-child(even){background-color: aqua}
#tableContent td{border: 1px solid black;margin: 0;padding:0px; text-align: center ;height: 50px }
#tableTop{
width: 1000px;height: 60px;background-color: darkgrey;font-size: 32px;text-align: center;
}
#page{font-size: 24px;color: chartreuse}
</style>
</head>
<body>
<div>
<table id="tableContent">
<caption id="tableTop"> 评论列表 <button id="back">返回新闻列表</button> </caption>
<tr><td>评论编号</td><td>评论内容</td><td>评论人</td><td>评论时间</td></tr>
</table>
<div id="page"></div>
</div>
<input type="hidden" id="currentPageNo" name="currentPageNo" value="1">
<script src="stastic/js/jquery-3.4.1.js"></script>
<script src="stastic/js/common.js"></script>
<script type="text/javascript">
var newsId = 0;
var countPage=0;
$(document).ready(function () {
newsId = GetQueryString("newsId")
console.log("newsId===="+newsId);
function content() {
var currentPageNo = $("#currentPageNo").val();
var params = "currentPageNo=" + currentPageNo + "&newsId=" + newsId;
$.getJSON("/newsServlet", params + "&opr=commentList", success);
function success(data) {
console.log("commentData===" + data);
countPage = data.countPageNo;
$("#tableContent tr:gt(0)").remove();
for (var i = 0; i < data.contentlist.length; i++) {
var $tr = $("<tr id='news" + data.contentlist[i].id + "'></tr>>");
$("#tableContent").append($tr);
$tr.append('<td>' + data.contentlist[i].id + '</td>>')
.append('<td>' + data.contentlist[i].content + '</td>>')
.append('<td>' + data.contentlist[i].author + '</td>>')
.append('<td>' + data.contentlist[i].createdate + '</td>>')
}
$("#page").html("");
$("#page").append("<span>当前页" + data.currentPageNo + "/" + data.countPageNo + "</span><br>");
if (data.currentPageNo > 1) {
$("#page").append('<a href="#" id="firstPage">首页</a>');
$("#page").append('<a href="#" id="prePage">上一页</a>');
}
if (data.currentPageNo < data.countPageNo) {
$("#page").append('<a href="#" id="nextPage">下一页</a>');
$("#page").append('<a href="#" id="lastPage">末页</a>');
}
}
}
content();
$(document).on("click","#firstPage,#prePage,#nextPage,#lastPage",function () {
var ida = $(this).attr("id");
switch (ida){
case "firstPage":
$("#currentPageNo").val(1);
break;
case "prePage":
var currentPageNo = $("#currentPageNo").val();
var pageNo = parseInt(currentPageNo)-1;
$("#currentPageNo").val(pageNo);
break;
case "nextPage":
var currentPageNo = $("#currentPageNo").val();
console.log("pageIndex===="+currentPageNo);
var pageNo = parseInt(currentPageNo)+1;
$("#currentPageNo").val(pageNo);
break;
case "lastPage":
$("#currentPageNo").val(countPage);
break;
}
content();
})
$("#back").click(function () {
window.location.href="http://localhost:8080/newsShow.html";
})
})
</script>
</body>
</html>