通过Ajax实现简单点赞效果

写得很糙,凑合着记录一下。
思路:通过点击按钮触发事件,通过Ajax提交请求,Servlet调用Service的方法进行处理,再通过Servlet将结果返回到JSP页面。
数据库操作:点击按钮,数据库中的num字段自增1,然后再将该数据查询后,返回到button的值中。

目录结构:
在这里插入图片描述

jsp页面

<head>
    <title>$Title$</title>
    <script type="text/javascript" src="js/jquery-1.8.0.min.js"></script>
    <script type="text/javascript">
      $(function () {
          $("#btn").click(function () {
			//	获取参数
              var num = document.getElementById("num").innerText;
			//	发送请求
              $.ajax({
                url:"/dianzan",
                data:"num="+num,
                dataType:"JSON",
                type:"post",
                success:function (result) {
                   document.getElementById("num").innerText=result.num;
                }
              });
          })
      })
    </script>
  </head>
  <body>
    <img src="image/1.jpg"><br><br>
    <button id="btn">点赞<span id="num">0</span></button>
  </body>

dao层的实现类

package com.wjb.dao.Impl;

import com.wjb.bean.Article;
import com.wjb.dao.ArticleDao;
import com.wjb.util.Utils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class ArticleDaoImpl implements ArticleDao {
    @Override
    public boolean update(int num) {
        int k = num+1;
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            conn = Utils.getConnection();
            String sql = "update article set num=? where id=?";
            ps = conn.prepareStatement(sql);
            ps.setString(1, String.valueOf(k));
            ps.setString(2,"10001");
            int i = ps.executeUpdate();
            if(i>0){    //更新成功
                return true;
            }
            return false;
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            Utils.close(rs,ps,conn);
        }
        return false;
    }

    @Override
    public Article search() {
        Connection conn = null;
        try {
            conn = Utils.getConnection();
            String sql = "select * from article where id=?";
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1,"10001");
            ResultSet rs = ps.executeQuery();
            Article article = new Article();
            while(rs.next()){
                article.setId(rs.getInt("id"));
                article.setTitle(rs.getString("title"));
                article.setNum(rs.getInt("num"));
            }
            return article;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

Servlet页面:

package com.wjb.web;

import com.wjb.bean.Article;
import com.wjb.service.ArticleService;
import com.wjb.service.Impl.ArticleServiceImpl;
import net.sf.json.JSONObject;

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(value = "/dianzan")
public class DianZanServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("DianZanServlet执行了");
        //  获取参数
        String str = req.getParameter("num");
        int num = Integer.parseInt(str);
        //  执行service方法
        ArticleService articleService = new ArticleServiceImpl();
        //  增加点赞数
        boolean flag = articleService.update(num);

        Article article = new Article();
        if(flag){
            article = articleService.search();
        }else{
            System.out.println("点赞失败!");
        }

        //  跳转页面
//        对象转为JSON
        JSONObject jsonObject = JSONObject.fromObject(article);
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        writer.println(jsonObject);
    }
}

工具类

package com.wjb.util;

import java.sql.*;

public class Utils {
    public static Connection getConnection() throws ClassNotFoundException, SQLException {
        Class.forName("com.mysql.jdbc.Driver");
        String url = "jdbc:mysql://localhost:3306/task";
        String username = "root";
        String password = "";
        Connection conn = DriverManager.getConnection(url,username,password);
        return conn;
    }

    public static void close(ResultSet rs, PreparedStatement ps,Connection conn){
        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }

        if(ps!=null){
            try {
                ps.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }

       if(conn!=null){
           try {
               conn.close();
           } catch (SQLException throwables) {
               throwables.printStackTrace();
           }
       }
    }
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值