<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>表单提交,存入数据库,从数据库中查看数据,删除数据</title>
    <meta name="Keywords" content="关键字">
    <meta name="description" content="简介">
</head>
<body>
<label><input type="text" class="name"></label>
<input type="submit" value="保存" id="b">
<hr>
<table border="1">
    <thead>
    <!-- tr 行; th 列 -->
    <tr>
        <th>编号</th>
        <th>姓名</th>
        <th>操作</th>
    </tr>
    </thead>
    <tbody id="tb"></tbody>
</table>
<script>
  document.getElementById("b").onclick=()=>{
    fetch("/user",{
        method:"post",
        body:`name=${document.querySelector(".name").value}`,
        headers:new Headers({'Content-Type':'application/x-www-form-urlencoded'})
    })
      .then(res=>res.text())
      .catch(e=>console.log(e))
      .then(msg=>{
          console.log(msg)})
  }

  setInterval(show,1000)

  function show (){
      fetch("/user")
      .then(res=>res.json())
      .catch(err=>console.warn(err))
      .then(msg=>{
          let t = document.getElementById("tb")
          t.innerHTML=""
          msg.forEach(e=>{
              t.innerHTML+=`<tr><td>${e.id}</td><td>${e.name}</td><td><a href="javascript:void(0)" οnclick="del(${e.id})">删除</a></td></tr>`
          })
      })
  }
  show();
  function del(id){
      fetch("/user?id="+id)
  }
</script>
</body>
</html>
package ws.wsj.servlet;

import com.alibaba.fastjson.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;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 卋舉
 * @ProjectName IntelliJ IDEA
 * @ClassName UserController
 * @description: TODO
 * @date 2021/10/20 14:22
 */
/*数据库 存入,查看,删除*/
@WebServlet("/user")
public class UserController extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        Connection con = null;
        try{
            Class.forName("com.mysql.cj.jdbc.Driver");
            con = DriverManager.getConnection("jdbc:mysql:/d3?user=root");
        }catch (Exception e){
            e.printStackTrace();
        }
        //接值保存
        if("POST".equals(req.getMethod())){
            String name = req.getParameter("name");
            try{
                PreparedStatement pst = con.prepareStatement("insert into ws value (null,?)");
                pst.setString(1,name);
                pst.executeUpdate();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        //查数据,并返回
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter out = resp.getWriter();
        if("GET".equals(req.getMethod())){
            //从数据库删除数据
            if (req.getParameter("id")!=null){
                try{
                    //转化为数字 Integer.parseInt
                    // 获取参数 getParameter
                    PreparedStatement pst = con.prepareStatement("delete from ws where id = ?");
                    pst.setInt(1,Integer.parseInt(req.getParameter("id")));
                    pst.executeUpdate();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

            try{
                PreparedStatement pst = con.prepareStatement("select * from ws order by id desc ");
                ResultSet rs = pst.executeQuery();
                //自己写的
                /*StringBuilder sb = new StringBuilder("[");
                while (rs.next()){
                    sb.append(String.format("{\"id\":%d,\"name\":\"%s\"},",rs.getInt("id"),rs.getString("name")));
                }
                sb.replace(sb.length()-1,sb.length(),"]");
                out.print(sb.toString());*/

                //使用fastjson 组件
                List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
                while (rs.next()){
                    Map<String,Object> map = new HashMap<String,Object>();
                    map.put("id",rs.getInt(1));
                    map.put("name",rs.getString(2));
                    list.add(map);
                }
                out.print(JSONObject.toJSON(list));
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}

Logo

DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。

更多推荐