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

posted @ 2017-08-11 19:56  Angelye  阅读(1736)  评论(0编辑  收藏  举报