(一) 前端给后端传递文章编号
在文章详情页面添加ajax请求
//2.访问数量改变
jQuery.getJSON("addcount",{
"id":id
},function (data) {
});
(二) 操作数据库修改访问量,每次+1
/**
* 访问量+1
* @param id
* @return
* @throws SQLException
*/
public int addCount(int id) throws SQLException {
int result = 0;
Connection connection = DBUtils.getConnection();
String sql = "update articleinfo set rcount=rcount+1 where id=?";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setInt(1,id);
result = statement.executeUpdate();
DBUtils.close(null,statement,connection);
return result;
}
(三) 后端拿到文章编号并执行业务逻辑
package services;
import dao.ArticleInfoDao;
import utils.ResultJSONUtils;
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.sql.SQLException;
import java.util.HashMap;
/**
* Created with IntelliJ IDEA.
* Description:访问量+1
* User: starry
* Date: 2021 -04 -14
* Time: 14:08
*/
@WebServlet("/addcount")
public class AddCountServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int succ = -1; // succ=1 表示操作成功
String msg = ""; // 错误说明信息
// 1.从前端获取参数
int id = Integer.parseInt(request.getParameter("id"));
// 2.调用数据库执行相应的业务逻辑
if(id > 0) {
ArticleInfoDao dao = new ArticleInfoDao();
try {
succ = dao.addCount(id);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}else {
msg = "无效参数";
}
// 3.将上一步操作的结果返回给前端
HashMap<String, Object> result = new HashMap<>();
result.put("succ", succ);
result.put("msg", msg);
ResultJSONUtils.write(response, result);
}
}
ok,每次点击刷新页面,访问量都会+1啦!!!
(四) 调整每个功能之间页面跳转
注册页面:
登录页面:
我的文章:
文章列表:
添加文章:
文章详情:
文章修改:
哈哈,就剩下项目部署到服务器了
部署之后小伙伴们都可以访问啦!!!😀😀😀