<%--
Created by IntelliJ IDEA.
User: xx
Date: 2023/9/4
Time: 10:00
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<script src="js/jquery-3.7.0.js"></script>
<script>
// 1.原始方式
/*function like(){
window.location.href = "likeServlet"
}*/
// 2.原生JS实现异步
function like(){
//获取XmlHttpRequest对象
var xhr = new XMLHttpRequest();
//设置请求
xhr.open("get","likeServlet");
//发送请求
xhr.send();
xhr.onreadystatechange = function (){
//获取状态码
if ( xhr.readyState== 4){
var msg = xhr.responseText;
document.getElementById("num").innerText = msg;
}
}
}
// 3.第一次封装
/*$(function () {
//点击事件
$("#btn").click(function () {
$.ajax({
url:"likeServlet",
data:null,
type:"get",
async:true,
dataType:"text",
success:function (msg) {
$("#num").text(msg);
}
});
});
});*/
// 4.第二次封装
/*$(function (){
$("#btn").click(function (){
$.get("likeServlet",null,function (date) {
$("#num").text(date)
},"text");
});
})*/
</script>
</head>
<body>
<video src="" controls></video>
<input type="button" id="btn" onclick="like()" value="点赞"></input>当前点赞量为:
<span style="color: red" id = "num">
${count}
</span>
</body>
</html>
import javax.servlet.ServletContext;
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;
@WebServlet("/likeServlet")
public class LikeServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//将获取的点赞了存储到ServletContext
ServletContext servletContext = getServletContext();
//获取当前点赞量
Integer count =(Integer) servletContext.getAttribute("count");
//如果是第一个点赞
if (count == null){
count = 1;
} else {
count++;
}
servletContext.setAttribute("count",count);
/*原生js*/
/*resp.sendRedirect("video.jsp");*/
/*ajax*/
PrintWriter writer = resp.getWriter();
writer.print(count);
writer.close();
}
}
原文地址:https://blog.csdn.net/weixin_62971115/article/details/132675798
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.7code.cn/show_46384.html
如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱:suwngjj01@126.com进行投诉反馈,一经查实,立即删除!
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。