Ajax+BootStrap+Servlet連接數據庫增刪改查

Ajax連接數據庫增刪改查

1、創建web項目導入相關需要的jar包,和mysql的jar包

在這裏插入圖片描述

2、使用Ajax需要導入jquery的js庫
3、導入Bootstrap庫

在這裏插入圖片描述

4、MVC模式創建controller、dao、entity、service文件夾
5、創建連接池連接數據庫DButils.java,和連接數據庫的配置文件db.properties
package com.yongjie.ajaxweb.common.utils;
import com.alibaba.druid.pool.DruidDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.*;
import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.Properties;

public class DButils {

    //聲明一個連接池
    private static DataSource dataSource;

    //聲明一個集合(配置信息)
    private static Properties config=new Properties();

    //初始化集合
    static {
        initData();
    }

    //初始化數據
    public static void initData(){
        try {
            //通過類加載器加載文件並獲得輸入流
            config.load( Thread.currentThread().getContextClassLoader().getResourceAsStream("com/yongjie/ajaxweb/db.properties")   );
        } catch (IOException e) {
            System.out.println("文件讀取異常");
        }
    }

    //獲得連接池的方法
    public static synchronized DataSource getDataSource() {

        if(dataSource == null){
            //實例化連接池
            DruidDataSource  ds = new DruidDataSource();
            //配置連接池
            ds.configFromPropety(config);
            //賦值
            dataSource = ds;
        }
        return  dataSource;
    }

    //獲得連接對象的方法
    public  static Connection getConnection(){
        try {
            return  getDataSource().getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return  null;
    }


    //封裝CURD 方法
    public static int  update(String sql, Object... args  ) throws SQLException {
        //執行器
        QueryRunner queryRunner = new QueryRunner( getDataSource() );
        return queryRunner.update(sql,args);
    }
    //插入並返回自增主鍵
    public static int  insert(String sql, Object... args  ) throws SQLException {
        //執行器
        QueryRunner queryRunner = new QueryRunner( getDataSource() );
        Object ID= queryRunner.insert(sql, new ScalarHandler<>() ,args);
        Long id=  Long.parseLong(ID.toString());
        return id.intValue();
    }
druid.url=jdbc:mysql://localhost:3306/fiendweb?useUnicode=true&characterEncoding=utf-8
druid.username=root
druid.password=root
druid.driverClassName=com.mysql.jdbc.Driver
druid.maxActive=20
druid.maxWait=2000
6、Ajax查詢數據庫數據。

1、創建 AjaxController.java文件和相關的到層service層,使用Servlet的get請求來 來查詢數據。

private NoticeService service=null;
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    resp.setCharacterEncoding("utf-8");
    req.setCharacterEncoding("utf-8");
    resp.setContentType("application/json;charset=utf-8");
   service=new NoticeServiceImpl();
    //獲取數據
   List<Notice>list=service.findAll();
    //將數據轉換爲json字符串
    String json = JSON.toJSONString(list);
    System.out.println(json);
    //將json字符串f發送到前端
    resp.getWriter().println(json);
}

2、Ajax前端接收後臺的數據,由於後臺使用的是get請求,所欲ajax獲取數據的方式爲get方式。注意不要忘記$.get()方法里加上,接收數據的格式,由於後臺傳送的是就送字符串,這裏的格式爲json

$.get('/ajax.do',function (data) {
  $('#tbDta').empty()
  $.each(data,function (i,n) {
    var tr=$('<tr></tr> ')
    var id=$('<td></td> ').text(n.id)
    var title=$('<td></td> ').text(n.title)
    var content=$('<td></td> ').text(n.content)
    var time=$('<td></td> ').text(n.ptime)
    var btn=$('<td><button class="btn-danger" οnclick="deleteHander('+n.id+')"> 刪除</button>' +
            '<button type="button" class="btn-danger"  data-toggle="modal"   data-target="#updatemyModal" οnclick="Valus('+n.id+')"> 修改數據</button></td> ')
    tr.append(id,title,content,time,btn);
    $('#tblist tbody').append(tr)
  })

},'json')
7、Ajax添加數據。

1、前端使用Boostrap的模態框來實現輸入的添加數據
在這裏插入圖片描述

2、後臺創建NoticeAddController.java 以及相關的業務層,使用pot請求接收前端傳來的添加數據

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    resp.setCharacterEncoding("utf-8");
    req.setCharacterEncoding("utf-8");
    resp.setContentType("application/json;charset=utf-8");
    //接收前端出來的字段數據
    String title= req.getParameter("title");
    String content= req.getParameter("content");
    Notice notice=new Notice();
    notice.setTitle(title);
    notice.setContent(content);
    //業務層添加數據的方法
    int row=  service.addNotice(notice);
    //返回給前端的添加狀態響應
    if (row>0){
        resp.getWriter().println("{\"msg\":\"添加成功\"}");
    }else{
        resp.getWriter().println("{\"msg\":\"添加失敗\"}");
    }
}

2、由於後臺使用的post請求,所以ajax使用post方法$post()

$.post("/ajax.add",$('#addForm').serialize(),function (date) {
    //彈出後臺響應的數據
  alert(date.msg)
  //關閉模態框
  $("#myModal").modal('hide');
},'json')
8、Ajax刪除數據。

1、刪除數據要考慮獲取點擊每條數據的刪除按鈕要獲取這條數據的id。由於之前ajax獲得所有的數據所以在那個方法每條數據上加一個按鈕,並獲取這條id
[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-pmQxyH0J-1574480959306)(en-resource://database/2356:0)]

var btn=$('<td><button class="btn-danger" οnclick="deleteHander('+n.id+')"> 刪除</button>'

2、在後臺控制器創建NoticeDeleteController.java 以及相關的業務層。其主要的思想爲,要獲得前端的傳來的id,然後調用刪除的方法更具id刪除。使用get請求

private NoticeService service=new NoticeServiceImpl();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    resp.setCharacterEncoding("utf-8");
    req.setCharacterEncoding("utf-8");
    resp.setContentType("application/json;charset=utf-8");
    //獲取前端傳來的id
   String id= req.getParameter("id");
   //業務層刪除的方法
   int row= service.deleteNotice(Integer.parseInt(id));
   //刪除響應返回給前端
   if (row>0){
       resp.getWriter().println("{\"msg\":\"刪除成功\"}");
   }else{
       resp.getWriter().println("{\"msg\":\"刪除失敗\"}");
   }
}

3、前端Ajax使用get請求操作發送id和刪除操作

$.get('/ajax.delete',{id:id},function (date) {
    //顯示後臺傳來的響應數據
  alert(date.msg)
},'json')
9、Ajax修改數據數據。

1、主要思路爲,需要獲取的是修改那一條數據,就要獲取該數據的id來查詢該條數據,然後顯示在修改框再來修改數據保存到數據庫。使用BootStrap的模態框記錄修改數據。點擊修改數據,模態框要顯示這條數據的當前內容[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-tmzOiJ1x-1574480959307)(en-resource://database/2358:0)]
2、創建NoticeUpdateController.java及相關的業務層。由於修改數據需要兩個步驟,一個是查詢當前選中修改的數據,二是修改這條數據。所以查詢數據使用get請求,修改數據使用post方法。一個請求同時操作兩個請求。不需要在get裏調用post方法,post方法調用get方法

/**修改數據
 * @author 13468
 */
@WebServlet("/ajax.update")
public class NoticeUpdateController extends HttpServlet {
    private NoticeService service=new NoticeServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("utf-8");
        req.setCharacterEncoding("utf-8");
        resp.setContentType("application/json;charset=utf-8");
        String id=req.getParameter("id");
        //通過ID查詢數據
        Notice notice= service.findNoticeById(Integer.parseInt(id));
      //轉換成JSon數據
        String json = JSON.toJSONString(notice);
        //json數據格式的字符串發送到前端
        resp.getWriter().println(json);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("utf-8");
        req.setCharacterEncoding("utf-8");
        resp.setContentType("application/json;charset=utf-8");
        //接收前端傳來的字段數據
        String id=req.getParameter("id");
        String title= req.getParameter("title");
        String content= req.getParameter("content");
        Notice notice=new Notice();
        notice.setId(Integer.parseInt(id));
        notice.setTitle(title);
        notice.setContent(content);
        //業務層改方法
       int row= service.updateNotice(notice);
       //返回響應給前端
        if (row>0){
            resp.getWriter().println("{\"msg\":\"修改成功\"}");
        }else{
            resp.getWriter().println("{\"msg\":\"修改失敗\"}");
        }
    }
}

3、前端需要點擊修改數據按鈕獲取該數據的id,方便後臺查詢該數據顯示在模態框中。就需要在獲取全部數據的Ajax方法中加上獲取id的值。在這裏需要注意一下,修改數據按鈕需要做兩件事,1.獲取id 2.彈出模態框。總結爲點擊彈出模態框需要傳值。需要在這個按鈕加一個監聽事件來傳這個id。BootStrap也有相應的方法

<button type="button" class="btn-danger"  data-toggle="modal"   data-target="#updatemyModal" onclick="Valus('+n.id+')"> 修改數據</button></td> ')

然後在js中使用Ajax通過前端的id傳入後臺,後臺查詢數據返回給前端

function Valus(id) {
  $.get("/ajax.update",{id:id},function (data) {
         //獲得數據id,通過id獲取數據填入輸入框
        $("#updateForm").find('input[name="id"]').val(id)
        $("#updateForm").find('input[name="title"]').val(data.title)
        $("#updateForm").find('textarea[name="content"]').val(data.content)
      },'json')
}

4、修改數據,後臺使用過post強求接受的前端發送的數據,所以前端Ajax用$Post()方法。serialize()是序列化表單多餘的數據

 $.post("/ajax.update",$("#updateForm").serialize(),function (data) {
      alert(data.msg)
    //關閉對話框
    $('#updatemyModal').modal('hide');
  },'json')
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章