DBCP(MySql)+Servlet+BootStrap+Ajax实现用户登录与简单用户管理系统

  目  录

  1. 本次项目通过Maven编写
  2. 本文最后会附上代码
  1. 登录界面
  2. 注册界面
  3. 登录成功进入主页
  4. 增加用户操作
  5. 删除用户操作
  6. 修改用户操作
  1. Dao层代码

  2. DBCP代码
  3. Servlet代码

  4. jsp前端代码

 

  • 实现简单用户登录与注册,登录成功进入系统可以对用户表进行CRUD操作,通过ajax异步刷新表格

      注意:在进行一次或多次操作CRUD之后无法再进行对一条数据的编辑,原因是ajax替换表格数据的时候没有修改编辑按钮onclick函数的参数值,解决方法为将6个参数值添加到editUser函数中传递参数就可以了。

    每次的CRUD操作都是通过ajax自动异步刷新表格,url不会改变。

    本次项目通过Maven编写。

    本文最后会附上代码(Service里没有功能性代码所以不会展示在这里),项目源代码及数据库语句配置都上传在github中。

  • 部分界面截图

   登录界面:(如果登录失败无法查询到用户信息,点击登录后会自动跳转注册界面)

    

   注册界面:(注册成功后会自动跳转登录界面)

   

 

 

     登录成功进入主页:(可实现CRUD操作)

    

 

 

     增加用户操作:(点击“添加用户”按钮后在表格第一列将输入列用JQuery的attr属性将class从hide转换为空来控制输入列的显隐)

   

 

 

     删除用户操作:(点击“删除”按钮将在表格上弹出警告框,点击确定将往后端传递id的值,通过id的值删除对应的表数据)

   

 

 

     修改用户操作:(点击任意列“编辑”按钮这一列表格变为文本框)

   

 

  •  主要代码:

   Dao层代码:

    • UserDao:
package cn.bobozz.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import cn.bobozz.bean.User;
import cn.bobozz.bean.UserPro;
import cn.bobozz.util.JdbcConnection;

public class UserDao {

    private Connection conn = null;
    
    public boolean loginUser(User user) {
        
        PreparedStatement pstm = null;
        String sql = "select * from user where username=? and password=? limit 1";
        boolean b = false;
        try {
            conn = JdbcConnection.getConn();
            pstm = conn.prepareStatement(sql);
            pstm.setString(1, user.getUsername());
            pstm.setString(2, user.getPassword());
            ResultSet rs = pstm.executeQuery();
            if(rs.next()) {
                b = true;
                pstm.close();
                conn.close();
            }else {
                pstm.close();
                conn.close();
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return b;
    }
    
    
    public boolean reqUser(UserPro userpro) {
        
        PreparedStatement pstm = null;
        String sql = "insert into user_pro values(?,?,?,?,?,?)";
        String sql1 = "insert into user values(?,?,?)";
        boolean r = false;
        try {
            conn = JdbcConnection.getConn();
            pstm = conn.prepareStatement(sql);
            pstm.setString(1, userpro.getUid());
            pstm.setString(2, userpro.getUsername());
            pstm.setString(3, userpro.getPassword());
            pstm.setString(4, userpro.getAddress());
            pstm.setString(5, userpro.getTel());
            pstm.setString(6, userpro.getEmail());
            PreparedStatement pstm1 = conn.prepareStatement(sql1);
            pstm1.setString(1, userpro.getUid());
            pstm1.setString(2, userpro.getUsername());
            pstm1.setString(3, userpro.getPassword());
            pstm1.executeUpdate();
            int rs = pstm.executeUpdate();
            if(rs != 0) {
                r = true;
                pstm.close();
                conn.close();
            }else {
                pstm.close();
                conn.close();
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return r;
    }
    
    
    public List<UserPro> queryUser(){
        PreparedStatement pstm = null;
        List<UserPro> userpros = new ArrayList<UserPro>();
        String sql = "select * from user_pro";
        try {
            conn = JdbcConnection.getConn();
            pstm = conn.prepareStatement(sql);
            ResultSet rs = pstm.executeQuery();
            userpros = new ArrayList<UserPro>();
            while(rs.next()) {
                UserPro userpro = new UserPro();
                userpro.setUid(rs.getString(1));
                userpro.setUsername(rs.getString(2));
                userpro.setPassword(rs.getString(3));
                userpro.setAddress(rs.getString(4));
                userpro.setTel(rs.getString(5));
                userpro.setEmail(rs.getString(6));
                userpros.add(userpro);
            }
            pstm.close();
            conn.close();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        return userpros;
    }
    
    
    public boolean deleteUser(String uid) {
        PreparedStatement pstm = null;
        boolean d = false;
        String sql = "delete from user where uid=?";
        String sql1 = "delete from  user_pro where uid=?";
        try {
            conn = JdbcConnection.getConn();
            pstm = conn.prepareStatement(sql);
            PreparedStatement pstm1 = conn.prepareStatement(sql1);
            pstm.setString(1, uid);
            pstm1.setString(1, uid);
            int rs = pstm.executeUpdate();
            pstm1.executeUpdate();
            if(rs != 0) {
                d = true;
            }
            pstm.close();
            pstm1.close();
            conn.close();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return d;
        
    }
    
    
    public boolean editUser(UserPro userpro) {
        PreparedStatement pstm = null;
        String sql = "update user_pro set uid=?,username=?,password=?,address=?,tel=?,email=? where uid=?";
        String sql1 = "update user_pro set uid=?,username=?,password=? where uid=?";
        boolean eu = false;
        try {
            conn = JdbcConnection.getConn();
            pstm = conn.prepareStatement(sql);
            pstm.setString(1, userpro.getUid());
            pstm.setString(2, userpro.getUsername());
            pstm.setString(3, userpro.getPassword());
            pstm.setString(4, userpro.getAddress());
            pstm.setString(5, userpro.getTel());
            pstm.setString(6, userpro.getEmail());
            pstm.setString(7, userpro.getUid());
            PreparedStatement pstm1 = conn.prepareStatement(sql1);
            pstm1.setString(1, userpro.getUid());
            pstm1.setString(2, userpro.getUsername());
            pstm1.setString(3, userpro.getPassword());
            pstm1.setString(4, userpro.getUid());
            pstm1.executeUpdate();
            int rs = pstm.executeUpdate();
            if(rs != 0) {
                eu = true;
                pstm.close();
                conn.close();
            }else {
                pstm.close();
                conn.close();
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return eu;
    }
}

 DBCP代码:

package cn.bobozz.util;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

import org.apache.commons.dbcp.BasicDataSource;

public class JdbcConnection {

    private static BasicDataSource bs = null;
    
    static {
        Properties p = new Properties();
        try {
            p.load(JdbcConnection.class.getClassLoader().getResourceAsStream("db.properties"));
            String url=p.getProperty("url");
            String driver = p.getProperty("driver");
            String user = p.getProperty("user");
            String password = p.getProperty("password");
            
            bs = new BasicDataSource();
            bs.setUrl(url);
            bs.setDriverClassName(driver);
            bs.setUsername(user);
            bs.setPassword(password);
            
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
    }
    public static Connection getConn() throws SQLException {
        return bs.getConnection();
    }
    
    public static void closeConn(Connection conn) {
        if(conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

 Servlet代码:

    • loginServlet: 
package cn.bobozz.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.bobozz.bean.User;
import cn.bobozz.service.UserService;

/**
 * Servlet implementation class loginServlet
 */
public class loginServlet extends HttpServlet {
    
    private User user = new User();
    private UserService userservice = new UserService();
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.setCharacterEncoding("utf-8");
        user.setUsername(request.getParameter("username"));
        user.setPassword(request.getParameter("password"));
        boolean l = userservice.loginUserService(user);
        if(l == true) {
            
            request.getSession().setAttribute("username", request.getParameter("username"));
            response.sendRedirect("queryServlet");
                    
        }else {
            
            response.sendRedirect("/mavenProject/req.jsp");
        }
    }
}
    • ReqServlet:
package cn.bobozz.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.bobozz.bean.UserPro;
import cn.bobozz.service.UserService;

/**
 * Servlet implementation class ReqServlet
 */

public class ReqServlet extends HttpServlet {
    
    private UserPro userpro = new UserPro();
    private UserService userservice = new UserService();
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String flag = request.getParameter("flag");
        userpro.setUid(request.getParameter("uid"));
        userpro.setUsername(request.getParameter("username"));
        userpro.setPassword(request.getParameter("password"));
        userpro.setAddress(request.getParameter("address"));
        userpro.setTel(request.getParameter("tel"));
        userpro.setEmail(request.getParameter("email"));
        boolean r = userservice.reqUserService(userpro);
        if(r == true) {
            if("add".equals(flag)) {
                response.getWriter().print("{'msg':ok}");
            }else {
                response.sendRedirect("/mavenProject/login.jsp");
            }
                
        }else {
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().print("注册失败");
            
        }
        
    }

}
    • queryServlet:
package cn.bobozz.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONArray;

import cn.bobozz.bean.UserPro;
import cn.bobozz.service.UserService;



public class queryServlet extends HttpServlet{

    private UserService userservice = new UserService();
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        List<UserPro> users = userservice.queryUserService();
        if("addfresh".equals(request.getParameter("flag"))){
            response.setContentType("text/html;charset=utf-8");
            String data = JSONArray.toJSONString(users);
            response.getWriter().print(data);
        }else {
            request.setAttribute("users", users);
            request.getRequestDispatcher("index.jsp").forward(request, response);
        }
        
    }
}
    • deleteServlet:
package cn.bobozz.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.bobozz.service.UserService;

public class deleteServlet extends HttpServlet{

    private UserService userservice = new UserService();
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        
        userservice.deleteUserService(request.getParameter("uid"));
        System.out.println(request.getParameter("uid"));
        
    }
}
    • editServlet:
package cn.bobozz.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.bobozz.bean.UserPro;
import cn.bobozz.service.UserService;

public class editServlet extends HttpServlet{

    private UserService userservice = new UserService();
    private UserPro userpro = new UserPro();
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        userpro.setUid(request.getParameter("uid"));
        userpro.setUsername(request.getParameter("username"));
        userpro.setPassword(request.getParameter("password"));
        userpro.setAddress(request.getParameter("address"));
        userpro.setTel(request.getParameter("tel"));
        userpro.setEmail(request.getParameter("email"));
        boolean r = userservice.editUserService(userpro);
        if(r == true) {
                response.getWriter().print("{'msg':ok}");                
        }
    }
}
  • jsp前端代码:

    • login.jsp:
<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>登录</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0,maximum-scale=1.0,user-scalable=no">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link href="bootstrap-3.3.7-dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="bootstrap-3.3.7-dist/jquery.min.js"></script>
    <script src="bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
    <style type="text/css">
    body {
            background: url(img/miku.png) no-repeat;
             -webkit-background-size: cover;
        }

        header {
            display: -webkit-box;
            position: absolute;
            background: -webkit-linear-gradient(top, #6495ED, rgba(100, 149, 237, 0.3));
            width: 100%;
            /* margin-top:-8px;
            margin-left:-8px; */

            border-bottom: 1px solid #8B8B7A;

            height: 75px;
            -webkit-box-pack: center;
            -webkit-box-align: center;

            /* padding-top:15px; */
        }
        
        .htext {
            color: #E6E6FA;
            text-align: center;
            font-size: 30px;
            letter-spacing: 30px;
            margin-top: 15px;
            font-family:'黑体', Times, serif;
        }
        .container1 {
            width: 30%;
            height: 60%;
            background: rgba(100, 149, 237, 0.6);
            /* position: absolute; */
            position: absolute;
            left: 50%;
            top:50%;
            transform: translate(-50%, -50%);
            box-shadow: 0 0 15px #D8BFD8;
        }

        
        .fcenter{
            display: -webkit-box;
            width:100%;
            height:60%;
            margin-top:18%;
            /* margin-left:25%; */
            -webkit-box-pack: center;
            -webkit-box-align: center;
        }
        
        label{
            font-size:18px;
            color:#FFDAB9;
            letter-spacing:3px;
        }
        
        .typesize{
            height:50px;
            width:100%;
        
        }
        
        h3{
            text-align:center;
            margin-bottom:10%;
            letter-spacing:7px;
            color:#fff;
            font-family:'宋体', Times, serif;
        }
        
        .button{
            background:#8FBC8F;
            border:none;
            width:80px;
            height:40px;
            text-align:center;
            color:#fff;
            letter-spacing:5px;
            font-size:15px;
            border-radius: 15px;
            margin-top:10px;
        }
        .button:hover{
            background:#228B22;
            transition:background .4s;
        
        }
        .zhuce{
            background:#DAA520;
            margin:auto 0px auto 36px;
        
        }
        
        .zhuce:hover{
            background:#D2691E;
            transition:background .4s;
        }
        
        
        
        .intext{
            background:rgba(255,255,255,0.7);
            
        }
    
    </style>
</head>

<body>

    <header><div class="htext">登录</div></header>
    <div class="container1">
        
        <div class="center">
        
        <div class="fcenter">
        <form action="<%=request.getContextPath()%>/loginServlet" class="form-horizontal">
        <h3>管理系统</h3>
            <div class="form-group"><label class="control-label">用户名:</label>
            <div class="typesize">
            <input type="text" class="form-control intext" name="username" id="username" placeholder="请输入用户名"/>
            </div>
            </div>
            <div class="form-group"><label class="control-label">密码:</label>
            <div class="typesize">
            <input type="password" class="form-control intext" name="password" id="password" placeholder="请输入密码"/>
            </div>
            </div>
            <input type="submit" value="登录" class="button"/>
            <a href="req.jsp"><input type="button" value="注册" class="button zhuce"/></a>
            
        </form>
        
        </div>    
        </div>
    </div>

</body>

</html>
    • req.jsp:
<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>注册</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0,maximum-scale=1.0,user-scalable=no">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link href="bootstrap-3.3.7-dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="bootstrap-3.3.7-dist/jquery.min.js"></script>
    <script src="bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
    <style type="text/css">
    body {
            background: url(img/miku.png) no-repeat;
             -webkit-background-size: cover;
        }

        header {
            display: -webkit-box;
            position: absolute;
            background: -webkit-linear-gradient(top, #6495ED, rgba(100, 149, 237, 0.3));
            width: 100%;
            /* margin-top:-8px;
            margin-left:-8px; */

            border-bottom: 1px solid #8B8B7A;

            height: 75px;
            -webkit-box-pack: center;
            -webkit-box-align: center;

            /* padding-top:15px; */
        }
        
        .container {
            background: rgba(100, 149, 237, 0.6);
            /* position: absolute; */
            position: absolute;
            left: 50%;
            top:50%;
            transform: translate(-50%, -50%);
            box-shadow: 0 0 10px #fff;
            width:50%;
        }
        .fcenter{

            width:85%;
            /* margin-left:25%; */
            margin:0 auto;    
        }
        .htext {
            color: #E6E6FA;
            text-align: center;
            font-size: 30px;
            letter-spacing: 30px;
            margin-top: 15px;
            font-family:'黑体', Times, serif;
        }
        label{
            font-size:18px;
            color:#FFDAB9;
            letter-spacing:3px;
        }
        
        .typesize{
            height:50px;
            width:100%;
        
        }
        
    /* h3{
            text-align:center;
            letter-spacing:7px;
            margin-top:0px;
        }  */
        
        .button{
            background:#8FBC8F;
            border:none;
            width:80px;
            height:40px;
            text-align:center;
            color:#fff;
            letter-spacing:25px;
            font-size:18px;
            border-radius: 15px;
            display:block;
            margin:0 auto 20px auto;
        }
        .button:hover{
            background:#228B22;
            transition:background .4s;
        
        }
        .zhuce{
            background:#DAA520;
            margin:auto 0px auto 36px;
        
        }
        
        .zhuce:hover{
            background:#D2691E;
            transition:background .4s;
        }
        
        
        
        .intext{
            background:rgba(255,255,255,0.7);
        
        }
    </style>
</head>
<body>

    <div class="container">
        
        <div class="center">
        
        <div class="fcenter">
        <form action="<%=request.getContextPath()%>/ReqServlet" class="form-horizontal">
        
        <h3 class="htext">注册</h3>
            <div class="form-group"><label class="control-label">用户id:</label>
            <div class="typesize">
            <input type="text" class="form-control intext" name="uid" id="uid" placeholder="请输入用户id"/>
            </div>
            </div>
            <div class="form-group"><label class="control-label">用户名:</label>
            <div class="typesize">
            <input type="text" class="form-control intext" name="username" id="username" placeholder="请输入用户名"/>
            </div>
            </div>
            <div class="form-group"><label class="control-label">密码:</label>
            <div class="typesize">
            <input type="password" class="form-control intext" name="password" id="password" placeholder="请输入密码"/>
            </div>
            </div>
            <div class="form-group"><label class="control-label">地址:</label>
            <div class="typesize">
            <input type="text" class="form-control intext" name="address" id="address" placeholder="请输入地址"/>
            </div>
            </div>
            <div class="form-group"><label class="control-label">电话:</label>
            <div class="typesize">
            <input type="text" class="form-control intext" name="tel" id="tel" placeholder="请输入电话"/>
            </div>
            </div>
            <div class="form-group"><label class="control-label">邮箱:</label>
            <div class="typesize">
            <input type="email" class="form-control intext" name="email" id="email" placeholder="请输入邮箱"/>
            </div>
            </div>
            <input type="submit" value="注册" class="button btn-lg btn-block"/>
            
        </form>
        
        </div>    
        </div>
    </div>

</body>
</html>
    • index.jsp:
<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>登录</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0,maximum-scale=1.0,user-scalable=no">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link href="bootstrap-3.3.7-dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="bootstrap-3.3.7-dist/jquery.min.js"></script>
    <script src="bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
    <style type="text/css">

        .navbar-brand{
            padding:4px 15px;
        }    
        .form-control{
            width:130px;
        }
        .id{
            width:120px;
        }

    </style>
</head>

<body>

    
    <nav class="navbar-inverse navbar-default">
  <div class="container">
    
    <div class="navbar-header">
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
      <a class="navbar-brand" href="#"><img alt="" src=""></a>
    </div>   
    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
      <ul class="nav navbar-nav">
        <li class="active"><a href="#">实训教育 <span class="sr-only">(current)</span></a></li>
        <li><a href="#">教学管理</a></li>
          <li><a href="#">规章制度</a></li>
          <li><a href="#">班级管理</a></li>
          <li><a href="#">校园招聘</a></li>
          <li><a href="#">企业文化</a></li>
          <li><a style="color:white;">欢迎${username }登录管理系统</a></li>
      </ul>
      
      
      <form class="navbar-form navbar-right">
      
        <div class="col-lg-6">
    <div class="input-group" style="width:230px;">
      <input type="text" class="form-control" placeholder="Search for...">
      <span class="input-group-btn">
        <button class="btn btn-default" type="button"><span class="glyphicon glyphicon-search" aria-hidden="true"></span></button>
      </span>
    </div><!-- /input-group -->
  </div>  
      </form>
      
    </div>
  </div>
</nav>
<div class="container">
<div class="alert alert-danger alert-dismissible in hide" role="alert" id="deletemsg">
      <h4>提示信息</h4>
      <p>确定要删除该用户吗?</p>
      <p>
        <button type="button" class="btn btn-danger" id="yesyes">确定</button>
        <button type="button" class="btn btn-default" id="nono">取消</button>
      </p>
    </div>
    <div class="table-responsive">
  <table class="table table-striped table-bordered table-hover">
      <tr>
          <th>ID</th>
          <th>用户名</th>
          <th>密码</th>
          <th>地址</th>
          <th>电话</th>
          <th>邮箱</th>
          <th>操作:<a class="btn btn-primary" href="${pageContext.request.contextPath}/queryServlet" id="seall">查询所有用户信息</a>
                    <button type="button" class="btn btn-success"  onclick="addUser()">添加用户</button>
          </th>
      </tr>     
      <tbody id="tbody">
      <tr id="addtr" class="hide">
          <td><input type="text" class="form-control id" placeholder="请输入用户id" id="uid"/></td>
          <td><input type="text" class="form-control id" placeholder="请输入用户名" id="username"/></td>
          <td><input type="text" class="form-control id" placeholder="请输入密码" id="password"/></td>
          <td><input type="text" class="form-control" placeholder="请输入地址" id="address"/></td>
          <td><input type="text" class="form-control id" placeholder="请输入电话" id="tel"/></td>
          <td><input type="text" class="form-control" placeholder="请输入邮箱" id="email"/></td>
          <td>
            <div class="btn-group" role="group" aria-label="...">
              <button type="button" class="btn btn-default" onclick="addNewUser()">添加</button>
              <button type="button" class="btn btn-default" style="color:red;" onclick="noadd()">取消</button>
            </div>
        </td>
        
      </tr>

<c:forEach items="${users }" var="i">
  <tr id=${i.uid }>
          <td>${i.uid }</td>
          <td>${i.username }</td>
          <td>${i.password }</td>
          <td>${i.address }</td>
          <td>${i.tel }</td>
          <td>${i.email }</td>
          <td>
            <div class="btn-group" role="group" aria-label="...">
              <button type="button" class="btn btn-default" onclick="editUser('${i.uid}','${i.username}','${i.password}','${i.address}','${i.tel}','${i.email}')">编辑</button>
              <button type="button" class="btn btn-default" style="color:red;" onclick="deleteUser(${i.uid})">删除</button>
            </div>
        </td>
      </tr>
      </c:forEach>
</tbody>
  </table>
  
  </div>
 </div>
  <script type="text/javascript">
  //添加
  function addUser(){
      $('#addtr').attr("class","");  
  }
  function noadd(){
      $('#addtr').attr("class","hide");
      
  }
  function addNewUser(){
      var uid = $('#uid').val();
      var username = $('#username').val();
      var password = $('#password').val();
      var address = $('#address').val();
      var tel = $('#tel').val();
      var email = $('#email').val();
        $.ajax({
              url:'${pageContext.request.contextPath}/ReqServlet',
              type:'post',
              data:{
                  "flag":"add",
                  "uid":uid,
                  "username":username,
                  "password":password,
                  "address":address,
                  "tel":tel,
                  "email":email    
              },
              error:function(data){
                  $('#addtr').attr("class","hide");    
                  alert('添加失败');
              },
              success:function(data){
                  $('#addtr').attr("class","hide");     
                  $.post("${pageContext.request.contextPath}/queryServlet",{"flag":"addfresh"},function(data){
                      var str = "";
                        $('#tbody').html("");
                        $('#tbody').append("<tr id=\"addtr\" class=\"hide\"><td><input type=\"text\" class=\"form-control id\" placeholder=\"请输入用户id\" id=\"uid\"/></td><td><input type=\"text\" class=\"form-control id\" placeholder=\"请输入用户名\" id=\"username\"/></td><td><input type=\"text\" class=\"form-control id\" placeholder=\"请输入密码\" id=\"password\"/></td><td><input type=\"text\" class=\"form-control\" placeholder=\"请输入地址\" id=\"address\"/></td><td><input type=\"text\" class=\"form-control id\" placeholder=\"请输入电话\" id=\"tel\"/></td><td><input type=\"text\" class=\"form-control\" placeholder=\"请输入邮箱\" id=\"email\"/></td><td><div class=\"btn-group\" role=\"group\" aria-label=\"...\"><button type=\"button\" class=\"btn btn-default\" onclick=\"addNewUser()\">添加</button><button type=\"button\" class=\"btn btn-default\" style=\"color:red;\" onclick=\"noadd()\">取消</button></div></td>    </tr>");
                        var json = JSON.parse(data);
                        for(var i = 0;i<json.length;i++){
                            str = "<tr>"+
                                  "<td>"+json[i].uid+"</td>"+
                                  "<td>"+json[i].username+"</td>"+
                                  "<td>"+json[i].password+"</td>"+
                                  "<td>"+json[i].address+"</td>"+
                                  "<td>"+json[i].tel+"</td>"+
                                  "<td>"+json[i].email+"</td>"+
                                 "<td><div class=\"btn-group\" role=\"group\" aria-label=\"...\"><button type=\"button\" class=\"btn btn-default\" onclick=\"editUser("+json[i].uid+")\">编辑</button><button type=\"button\" class=\"btn btn-default\" style=\"color:red;\" onclick=\"deleteUser("+json[i].uid+")\">删除</button></div></td>"+
                                  "</tr>";                                 
                                  $('#tbody').append(str);
                        }                        
                  });                 
              }             
          });      
  }
  //删除
      function deleteUser(uids){
          uid = uids;
          $('#deletemsg').attr("class","alert alert-danger alert-dismissible");
      }
      $('#nono').click(function(){
          $('#deletemsg').attr("class","hide");         
      });
      $('#yesyes').click(function(){
/*           $.post("${pageContext.request.contextPath}/deleteServlet",
                  {"uid":uid},
                  function(delet){
                      window.location.href="${pageContext.request.contextPath}/queryServlet";
                  }); */
          $.ajax({
              url:'${pageContext.request.contextPath}/deleteServlet',
              type:'post',
              data:{
                  "uid":uid
              },
              error:function(data){
                  $('#deletemsg').attr("class","hide");     
                  alert('请求失败');
              },
              success:function(data){
                  $('#deletemsg').attr("class","hide");     
                  $.post("${pageContext.request.contextPath}/queryServlet",{"flag":"addfresh"},function(data){
                      var str = "";
                        $('#tbody').html("");
                          $('#tbody').append("<tr id=\"addtr\" class=\"hide\"><td><input type=\"text\" class=\"form-control id\" placeholder=\"请输入用户id\" id=\"uid\"/></td><td><input type=\"text\" class=\"form-control id\" placeholder=\"请输入用户名\" id=\"username\"/></td><td><input type=\"text\" class=\"form-control id\" placeholder=\"请输入密码\" id=\"password\"/></td><td><input type=\"text\" class=\"form-control\" placeholder=\"请输入地址\" id=\"address\"/></td><td><input type=\"text\" class=\"form-control id\" placeholder=\"请输入电话\" id=\"tel\"/></td><td><input type=\"text\" class=\"form-control\" placeholder=\"请输入邮箱\" id=\"email\"/></td><td><div class=\"btn-group\" role=\"group\" aria-label=\"...\"><button type=\"button\" class=\"btn btn-default\" onclick=\"addNewUser()\">添加</button><button type=\"button\" class=\"btn btn-default\" style=\"color:red;\" onclick=\"noadd()\">取消</button></div></td>    </tr>");
                        var json = JSON.parse(data);
                        for(var i = 0;i<json.length;i++){
                            str = "<tr>"+
                                  "<td>"+json[i].uid+"</td>"+
                                  "<td>"+json[i].username+"</td>"+
                                  "<td>"+json[i].password+"</td>"+
                                  "<td>"+json[i].address+"</td>"+
                                  "<td>"+json[i].tel+"</td>"+
                                  "<td>"+json[i].email+"</td>"+
                                  "<td><div class=\"btn-group\" role=\"group\" aria-label=\"...\"><button type=\"button\" class=\"btn btn-default\" onclick=\"editUser("+json[i].uid+")\">编辑</button><button type=\"button\" class=\"btn btn-default\" style=\"color:red;\" onclick=\"deleteUser("+json[i].uid+")\">删除</button></div></td>"+
                                  "</tr>";                                 
                                  $('#tbody').append(str);
                        }                       
                  });                  
              }             
          });         
      });
      
      
      //编辑
      function editUser(uuid,uusername,upassword,uaddress,utel,uemail){
          var str = "";
          $("#"+uuid).html("");
          $("#"+uuid).append("<td><input type=\"text\" class=\"form-control id\" id=\"uuid\" value=\""+uuid+"\"></td><td><input type=\"text\" class=\"form-control id\" id=\"uusername\" value=\""+uusername+"\"></td><td><input type=\"text\" class=\"form-control id\" id=\"upassword\" value=\""+upassword+"\"/></td><td><input type=\"text\" class=\"form-control\" id=\"uaddress\" value=\""+uaddress+"\"/></td><td><input type=\"text\" class=\"form-control id\" id=\"utel\" value=\""+utel+"\"/></td><td><input type=\"text\" class=\"form-control\" id=\"uemail\"  value=\""+uemail+"\"/></td><td><div class=\"btn-group\" role=\"group\" aria-label=\"...\"><button type=\"button\" class=\"btn btn-default\" onclick=\"editNewUser()\">编辑</button><button type=\"button\" class=\"btn btn-default\" style=\"color:red;\" onclick=\"noedit()\">取消</button></div></td>");         
      }
      function editNewUser(){
          var uid = $('#uuid').val();
          var username = $('#uusername').val();
          var password = $('#upassword').val();
          var address = $('#uaddress').val();
          var tel = $('#utel').val();
          var email = $('#uemail').val();
          $.ajax({
              url:'${pageContext.request.contextPath}/editServlet',
              type:'post',
              data:{
                  "uid":uid,
                  "username":username,
                  "password":password,
                  "address":address,
                  "tel":tel,
                  "email":email
              },
              error:function(data){
                  $('#deletemsg').attr("class","hide");     
                  alert('请求失败');
              },
              success:function(data){
                  $('#deletemsg').attr("class","hide");     
                  $.post("${pageContext.request.contextPath}/queryServlet",{"flag":"addfresh"},function(data){
                      var str = "";
                        $('#tbody').html("");
                          $('#tbody').append("<tr id=\"addtr\" class=\"hide\"><td><input type=\"text\" class=\"form-control id\" placeholder=\"请输入用户id\" id=\"uid\"/></td><td><input type=\"text\" class=\"form-control id\" placeholder=\"请输入用户名\" id=\"username\"/></td><td><input type=\"text\" class=\"form-control id\" placeholder=\"请输入密码\" id=\"password\"/></td><td><input type=\"text\" class=\"form-control\" placeholder=\"请输入地址\" id=\"address\"/></td><td><input type=\"text\" class=\"form-control id\" placeholder=\"请输入电话\" id=\"tel\"/></td><td><input type=\"text\" class=\"form-control\" placeholder=\"请输入邮箱\" id=\"email\"/></td><td><div class=\"btn-group\" role=\"group\" aria-label=\"...\"><button type=\"button\" class=\"btn btn-default\" onclick=\"addNewUser()\">添加</button><button type=\"button\" class=\"btn btn-default\" style=\"color:red;\" onclick=\"noadd()\">取消</button></div></td>    </tr>");
                        var json = JSON.parse(data);
                        for(var i = 0;i<json.length;i++){
                            str = "<tr>"+
                                  "<td>"+json[i].uid+"</td>"+
                                  "<td>"+json[i].username+"</td>"+
                                  "<td>"+json[i].password+"</td>"+
                                  "<td>"+json[i].address+"</td>"+
                                  "<td>"+json[i].tel+"</td>"+
                                  "<td>"+json[i].email+"</td>"+
                                  "<td><div class=\"btn-group\" role=\"group\" aria-label=\"...\"><button type=\"button\" class=\"btn btn-default\" onclick=\"editUser("+json[i].uid+")\">编辑</button><button type=\"button\" class=\"btn btn-default\" style=\"color:red;\" onclick=\"deleteUser(${i.uid})\">删除</button></div></td>"+
                                  "</tr>";                                 
                                  $('#tbody').append(str);
                        }                       
                  });                  
              }             
          });
      }
      function noedit(uid){
          window.location.href="${pageContext.request.contextPath}/queryServlet";              
      }
  </script>
</body>

</html>
  • 源代码链接:

 源代码项目(带数据库sql文件):https://github.com/1255493195/DBCP-Servlet-BootStrap-Ajax-Project.git

posted @ 2019-09-23 20:37 落成 阅读(...) 评论(...) 编辑 收藏