Servlet做简单的ajax增删改查(分页)

jdbc.java

 1 package servlet;
 2
 3 import java.sql.Connection;
 4 import java.sql.DriverManager;
 5 import java.sql.ResultSet;
 6 import java.sql.SQLException;
 7 import java.sql.Statement;
 8
 9 public class Jdbc {
10     Connection conn;
11     Statement stem;
12     ResultSet re;
13     /*
14      * jdbc五步走:
15      *          1:加载驱动
16      *          2:创建连接
17      *               2.1:地址
18      *               2.2:用户名  root
19      *               2.3:密码      123
20      *          3:创建发送执行sql语句对象
21      *          4:发送执行sql语句
22      *          5:操作结果集
23      */
24
25     private void lianjie() {
26         try {
27              Class.forName("com.mysql.jdbc.Driver");
28               conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/guoyihua", "root", "123");
29              stem = conn.createStatement();
30         } catch (Exception e) {
31             e.printStackTrace();
32         }
33     }
34
35     private void guanbi() {
36         try {
37             if (re!=null) {
38                 re.close();
39             }
40
41             if (stem!=null) {
42                 stem.close();
43             }
44             if (conn!=null) {
45                 conn.close();
46             }
47         } catch (SQLException e) {
48             // TODO Auto-generated catch block
49             e.printStackTrace();
50         }
51     }
52
53     /*
54      * 创建一个应用于任何查询的show方法。
55      * 但凡查询功能一定返回一个结果集
56      */
57     public   ResultSet   show (  String sql  ){
58         this.lianjie();
59         try {
60             re=stem.executeQuery(sql);
61         } catch (SQLException e) {
62         }
63         return  re;
64     }
65
66
67     public   int    update (  String sql  ){
68         this.lianjie();
69         int i;
70         try {
71             i = stem.executeUpdate(sql);
72             this.guanbi();
73             return i;
74         } catch (SQLException e) {
75         }
76         return 0;
77     }
78
79
80 }

UserService.java

 1 package servlet;
 2
 3 import java.sql.ResultSet;
 4 import java.sql.SQLException;
 5 import java.util.ArrayList;
 6 import java.util.HashMap;
 7 import java.util.List;
 8 import java.util.Map;
 9 import java.util.Random;
10
11 public class UserService {
12     Jdbc jdbc= new Jdbc();
13
14     int page=2;
15
16     public List<Map<String, Object>> show(String ye) {
17         int yee = Integer.parseInt(ye);
18         yee=(yee-1)*page;
19         List<Map<String, Object>> list  =new ArrayList<Map<String,Object>>();
20         ResultSet show = jdbc.show("select * from user limit "+yee+" , "+page+" ");
21         try {
22             while (show.next()) {
23                 Map<String,Object> map = new HashMap<String, Object>();
24                 map.put("id", show.getInt("id"));
25                 map.put("name", show.getString("name"));
26                 map.put("password", show.getLong("password"));
27                 list.add(map);
28             }
29         } catch (SQLException e) {
30             // TODO Auto-generated catch block
31             e.printStackTrace();
32         }
33
34         return list;
35     }
36
37
38     public void deletee(String id) {
39         jdbc.update("delete from user where id=‘"+id+"‘ ");
40     }
41
42
43     public Map<String, Object> toupdate(String id) {
44         Map<String, Object> map = new HashMap<String, Object>();
45         ResultSet re = jdbc.show("select * from user where id=‘"+id+"‘");
46         try {
47             while (re.next()) {
48                 map.put("id", re.getInt("id"));
49                 map.put("name", re.getString("name"));
50                 map.put("password", re.getLong("password"));
51             }
52         } catch (SQLException e) {
53             // TODO Auto-generated catch block
54             e.printStackTrace();
55         }
56         return map;
57     }
58
59
60     public void update(String id, String name, String password) {
61         jdbc.update("update user set name=‘"+name+"‘,password=‘"+password+"‘where id=‘"+id+"‘  ");
62     }
63
64
65     public void add(String name, String password) {
66         Random random = new Random();
67         int id = random.nextInt(1000);
68         jdbc.update("insert into user (id,name,password) values(‘"+id+"‘,‘"+name+"‘,‘"+password+"‘)");
69     }
70
71
72     public int tablecount() {
73         int tablecount=0;
74         int count=0;
75         ResultSet re = jdbc.show("select count(*) from  user ");
76         try {
77             while (re.next()) {
78                  tablecount = re.getInt("count(*)");
79             }
80         } catch (SQLException e) {
81             // TODO Auto-generated catch block
82             e.printStackTrace();
83         }
84         if(tablecount%page==0){
85             count = tablecount/page;
86         }
87         if (tablecount%page!=0) {
88
89             count = tablecount/page+1;
90         }
91         return count;
92     }
93
94
95 }

UserServlet.java

 1 package servlet;
 2
 3 import java.io.IOException;
 4 import java.io.UnsupportedEncodingException;
 5 import java.util.ArrayList;
 6 import java.util.List;
 7 import java.util.Map;
 8
 9 import javax.servlet.ServletException;
10 import javax.servlet.http.HttpServlet;
11 import javax.servlet.http.HttpServletRequest;
12 import javax.servlet.http.HttpServletResponse;
13
14 public class UserServlet extends HttpServlet{
15     List<Map<String, Object>> list= new ArrayList<Map<String,Object>>();
16     UserService us = new UserService();
17     HttpServletRequest request;
18     HttpServletResponse response;
19     protected void doGet(HttpServletRequest request, HttpServletResponse response)
20             throws ServletException, IOException {
21         this.request= request;
22         this.response= response;
23         String me = request.getParameter("method");
24         if (me.equals("show")) {
25             this.show();
26         }
27         if (me.equals("deletee")) {
28             this.deletee();
29         }
30         if (me.equals("toupdate")) {
31             this.toupdate();
32         }
33         if (me.equals("update")) {
34             this.update();
35         }if (me.equals("add")) {
36             this.add();
37         }
38     }
39     private void add() throws IOException {
40         String name = request.getParameter("name");
41         name=new String(name.getBytes("ISO8859-1"), "UTF-8");
42         String password = request.getParameter("password");
43         us.add(name,password);
44         response.getWriter().print("<script type=\"text/javascript\">parent.show(1)</script>");
45     }
46     private void update() throws IOException {
47         String id = request.getParameter("id");
48         String name = request.getParameter("name");
49         String password = request.getParameter("password");
50         name= new String(name.getBytes("ISO8859-1"), "UTF-8");
51         us.update(id,name,password);
52         response.getWriter().print("<script type=\"text/javascript\">parent.show(1)</script>");
53     }
54     private void toupdate() throws ServletException, IOException {
55         String id = request.getParameter("id");
56         Map<String, Object> map = us.toupdate(id);
57         request.setAttribute("map", map);
58         request.getRequestDispatcher("update.jsp").forward(request, response);
59     }
60     private void deletee() throws ServletException, IOException {
61         String id = request.getParameter("id");
62         us.deletee(id);
63         this.show();
64     }
65     private void show() throws ServletException, IOException {
66         String ye = request.getParameter("ye");
67         if (ye==null) {
68             ye="1";
69         }
70         List<Map<String, Object>> list=us.show(ye);
71         request.setAttribute("li", list);
72         int count=us.tablecount();
73         request.setAttribute("count", count);
74         request.getRequestDispatcher("show.jsp").forward(request, response);
75
76     }
77
78 }

index.jsp

 1 <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
 2 <%
 3 String path = request.getContextPath();
 4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
 5 %>
 6
 7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 8 <html>
 9   <head>
10     <base href="<%=basePath%>">
11
12     <title>My JSP ‘index.jsp‘ starting page</title>
13     <meta http-equiv="pragma" content="no-cache">
14     <meta http-equiv="cache-control" content="no-cache">
15     <meta http-equiv="expires" content="0">
16     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
17     <meta http-equiv="description" content="This is my page">
18     <!--
19     <link rel="stylesheet" type="text/css" href="styles.css">
20     -->
21
22   </head>
23     <script type="text/javascript" src="jquery-1.6.js"></script>
24     <script type="text/javascript">
25
26     function show(ye){
27         var d= new Date().getTime();
28         $.get("aa?method=show&ye="+ye+"&d="+d,function(date){
29         $("#div1").html(date)
30             })
31         }
32
33     function deletee(id){
34         var d=new Date().getTime();
35         $.get("aa?method=deletee&id="+id+"&d="+d,function(date){
36         $("#div1").html(date);
37             })
38     }
39
40     function toupdate(id){
41         $.get("aa?method=toupdate&id="+id,function(date){
42         $("#div2").html(date);
43             })
44         }
45     function update(a){
46         a.submit();
47         $(a).hide();
48         }
49     function toadd(){
50         $.get("add.jsp",function(date){
51         $("#div3").html(date);
52             })
53         }
54     function add(a) {
55         a.submit();
56         $(a).hide();
57     }
58     </script>
59
60   <body>
61    <a href="javascript:show(1)">查询user表</a>
62    <div id="div1"></div>
63    <div id="div2"></div>
64    <div id="div3"></div>
65   </body>
66 </html>

show.jsp

 1 <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
 2 <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
 3 <%
 4 String path = request.getContextPath();
 5 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
 6 %>
 7
 8 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 9 <html>
10   <head>
11     <base href="<%=basePath%>">
12
13     <title>My JSP ‘show.jsp‘ starting page</title>
14
15     <meta http-equiv="pragma" content="no-cache">
16     <meta http-equiv="cache-control" content="no-cache">
17     <meta http-equiv="expires" content="0">
18     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
19     <meta http-equiv="description" content="This is my page">
20     <!--
21     <link rel="stylesheet" type="text/css" href="styles.css">
22     -->
23
24   </head>
25
26   <body>
27    <table bgcolor="c0c0c0"  bordercolor="green" cellspacing="1">
28            <tr bordercolor="green">
29                <td>编号</td>
30                <td>姓名</td>
31                <td>密码</td>
32                <td>修改</td>
33                <td>删除</td>
34            </tr>
35            <c:forEach items="${requestScope.li}" var="list">
36                <tr>
37                    <td>${list.id}</td>
38                    <td>${list.name}</td>
39                    <td>${list.password}</td>
40                    <td><a href="javascript:toupdate(${list.id})">修改</a></td>
41                    <td><a href="javascript:deletee(${list.id})">删除</a></td>
42                </tr>
43            </c:forEach>
44    </table>
45
46   <c:if test="${param.ye>1}">
47        <a href="javascript:show(1)">首页</a>
48   </c:if>
49    <c:if test="${param.ye>1}">
50    <a href="javascript:show(${param.ye-1})">上一页</a>
51    </c:if>
52        <c:forEach begin="1" end="${requestScope.count}" varStatus="c">
53        <a href="javascript:show(${c.index})">${c.index}</a>
54        </c:forEach>
55        <c:if test="${param.ye<requestScope.count}">
56    <a href="javascript:show(${param.ye+1})">下一页</a>
57    </c:if>
58   <c:if test="${param.ye<requestScope.count}">
59        <a href="javascript:show(${requestScope.count})">尾页</a>
60   </c:if>
61
62
63        <a href="javascript:toadd()"> 添加 </a>
64   </body>
65 </html>

add.jsp

 1 <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
 2 <%
 3 String path = request.getContextPath();
 4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
 5 %>
 6
 7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 8 <html>
 9   <head>
10     <base href="<%=basePath%>">
11
12     <title>My JSP ‘add.jsp‘ starting page</title>
13
14     <meta http-equiv="pragma" content="no-cache">
15     <meta http-equiv="cache-control" content="no-cache">
16     <meta http-equiv="expires" content="0">
17     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
18     <meta http-equiv="description" content="This is my page">
19     <!--
20     <link rel="stylesheet" type="text/css" href="styles.css">
21     -->
22
23   </head>
24
25   <body>
26   <form action="aa" target="abc">
27       <h3>请输入以下内容</h3>
28       <input type="hidden" name="id">
29       <input type="hidden" name="method" value="add" >
30       请输入姓名<input type="text" name="name" ><br/><br/>
31       请输入密码<input type="text" name="password" ><br/><br/>
32       <input type="button" value="确认添加" onclick="javascript:add(this.form)">
33       <iframe name="abc" style="display: none;" frameborder="1"></iframe>
34   </form>
35   </body>
36 </html>

update.jsp

 1 <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
 2 <%
 3 String path = request.getContextPath();
 4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
 5 %>
 6
 7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 8 <html>
 9   <head>
10     <base href="<%=basePath%>">
11
12     <title>My JSP ‘update.jsp‘ starting page</title>
13
14     <meta http-equiv="pragma" content="no-cache">
15     <meta http-equiv="cache-control" content="no-cache">
16     <meta http-equiv="expires" content="0">
17     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
18     <meta http-equiv="description" content="This is my page">
19     <!--
20     <link rel="stylesheet" type="text/css" href="styles.css">
21     -->
22
23   </head>
24
25   <body>
26   <form action="aa" target="abc">
27    <h3>请修改以下内容</h3>
28     <input type="hidden" name="method" value="update">
29     <input type="hidden" name="id" value="${map.id}"><br/><br/>
30     <input type="text" name="name" value="${map.name}"><br/><br/>
31     <input type="text" name="password" value="${map.password}"><br/><br/>
32     <input type="button" value="确认修改" onclick="javascript:update(this.form)">
33     <iframe name="abc" style="display: none;"></iframe>
34   </form>
35   </body>
36 </html>

此文章仅为个人学习记录文件,为个人所记笔记。

可供大家参考

但是注释甚少

如有疑问可以留言

希望可以帮助到初学者

2017-08-1119:53:30

时间: 2024-10-23 10:05:48

Servlet做简单的ajax增删改查(分页)的相关文章

【Mybatis】简单的mybatis增删改查模板

简单的mybatis增删改查模板: <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > <mapper namespace="com.sunee

Mybatis实现简单的数据库增删改查操作

Mybatis实现简单的数据库增删改查操作 框架:mybatis(3.5.2) 数据库:mysql 工具:idea 1.新建一个maven项目,在pom文件中添加mybatis依赖及MySQL依赖 <!-- mybatis核心依赖 --> <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis --> <dependency> <groupId>org.mybatis</groupId&g

OracleHelper(对增删改查分页查询操作进行了面向对象的封装,对批量增删改操作的事务封装)

公司的一个新项目使用ASP.NET MVC开发,经理让我写个OracleHelper,我从网上找了一个比较全的OracleHelper类,缺点是查询的时候返回DataSet,数据增删改要写很多代码(当然,可以用代码生成器,不过配套的代码生成器暂时没有):又从网上找了一个封装了泛型方法的OracleHelper类,整合到一起,但貌似数据增删改查依然不方便:于是花了两天时间,在原有基础上对增删改查分页查询操作进行了面向对象的封装,并且对批量增删改操作进行事务封装,写事务代码更方便. 原理: 1.利用

Salesforce零基础(三)简单的数据增删改查页面的构建(Ajax样式)

VisualForce封装了很多的标签用来进行页面设计 下面以一个单一的表进行数据增删改查.表结构如图1所示.通过图可以看出GOODS表自己定义的参数主要包括以下: GoodsName__c,GoodsType__c,GoodsBrand__c,GoodsDescribe__c,GoodsPrice__c. 图1 VF每个页面都是以<apex:page>标签起始</apex:page>结束,每个VF页面都有一个Controller用来控制其业务逻辑.本篇例子中主要用到的控件包括如下

web项目总结——通过jsp+servlet实现对oracle的增删改查功能

1.DAO模式 分包:依次建立 entity:实体包,放的是跟oracle数据库中表结构相对应的对象的属性,也就是这个对象有什么 dao:增删改查接口,实现增删改查的具体方法 service:同dao,也是一个接口,一个接口的实现类,方法什么的都跟dao差不多 servlet:新建servlet类,继承HttpServlet类,一个方法建立一个servlet类,根据不同的方法选择使用doGet().doPost()方法 .services()既包含doGet 又包含doPost 新建jsp页面

富文本内容简单的的增删改查

由于html本身的textarea标签的文本编辑功能较为简单,不能设置文字的样式,因此需要富文本控件来增强textarea的功能.       一些常见的富文本控件有:UEditor.kindeditor.simditor.bootstrap-wysiwyg.wangEditor.CKEditor.tinymce,各有优缺点,网上也有对不介绍,不再赘述. 此处选用tinymce,因其兼容性较好,插入页面也较为简单,此外还有丰富的插件可以扩展功能. 首先,在页面上使用tinymce:1.引入js文

Hibernate全套增删改查+分页

1.创建一个web工程 2.导入jar包 3.创建Student表 4.创建实体类 package com.entity; public class Student { private Integer sid; private String sname; private String password; private String sex; private Integer cid; public Student() { } public Student(Integer sid, String

Asp.net简单三层+Sqllite 增删改查

新建项目à新建一个空白解决方案 在Model新建一个实体类 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;     namespace factory.Model {     public class factorys     {     //ID INTEGER PRIMARY KEY AUTOINCREMENT

Oracle简单操作语句(增删改查),和代码例子

//创建用户 :             create user c##名字 identified by 密码 ;        //命名规则 :             1 名字必须以字母开头,            2 长度不能超过30个字符(60字节),            3 不能使用oracle的保留字<            4 只能使用a-z,A-Z, 0-9,$,#,_,等... //切换当前用户 : connect 用户名/密码@网络服务器(orcl); //oracle数据