精华内容
下载资源
问答
  • web增删改查

    2017-08-08 18:09:28
    web增删改查,下载即用
  • SQL增删改查源码

    2019-01-12 02:10:42
    SQL增删改查源码
  • java web 增删改查

    2018-04-19 10:53:35
    java web 连接My SQL数据实现增删改查,使用面向对象封装
  • springboot对hadoop增删改查源码,IE通过servlet访问hadoop图片,直接IE显示源码
  • EFCore+WebAPi增删改查

    2018-03-20 14:42:03
    由EFCore配合WebApi搭建的简单框架,通过Ajax实现增删改查,显示部分用了AngularJS。压缩包中包含源码、数据库、搭建流程。
  • SSH实现增删改查源码

    2014-09-03 09:42:36
    struts2 spring hibernate mysql
  • javaweb+servlet+mysql登录+注册+增删改查源码

    千次阅读 多人点赞 2019-04-08 21:39:09
    项目功能简介 功能流程图 源码: 百度网盘链接:https://pan.baidu.com/s/1QpbX1Sz0nZJwlvzEvx7zEw 提取码:ynzu 数据库: 链接:https://pan.baidu.com/s/1p2LIfcOeQ1EKdCDS4D29PA 提取码:mbpc 二.项目详解 1....

    一.项目功能简介

                                      功能流程图

    源码:

    百度网盘链接:https://pan.baidu.com/s/1QpbX1Sz0nZJwlvzEvx7zEw 
    提取码:ynzu

    数据库:

    链接:https://pan.baidu.com/s/1p2LIfcOeQ1EKdCDS4D29PA 
    提取码:mbpc

    二.项目详解

    1.创建javaweb项目

    2.创建目录

    src/com.neusoft.dao存放实体类和数据库操作的java文件

    src/com.neusoft.servlet存放servlet的文件,用来接收前台发来的请求和数据,传到数据库,再返回给前台

    webContent文件夹一般存放jsp、html、js等文件

    web.xml存放在WEB-INF文件夹下

    3.login.jsp(JSP页面用了Bootstrap http://www.bootcss.com/,联网状态加入下边标签,然后标签的class中引入Bootstrap中已有的class即可)

    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">

     

    <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
    <%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    %>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <base href="<%=basePath%>">
        
        <title>My JSP 'login.jsp' starting page</title>
        
        <meta http-equiv="pragma" content="no-cache">
        <meta http-equiv="cache-control" content="no-cache">
        <meta http-equiv="expires" content="0">    
        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
        <meta http-equiv="description" content="This is my page">
        <!--
        <link rel="stylesheet" type="text/css" href="styles.css">
        -->
     <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
      </head>
      
      <body style="background:url('http://localhost:8080/webDomo2/login4.jpg') no-repeat;background-size: cover;">
      <div style="width:30% ;height:376px;margin:136px 10px 10px 825px;border-radius:25px;box-shadow: 5px 5px 5px 5px #888888;background-color:">
     <div style="height:70px;margin-left: 172px;margin-top:3px;float:left;">
    		<h1 style="font: bold em Brush Script MT ; color:#222; text-shadow: 0px 2px 3px #666;float:left;"> Login<h1/>
    		</div>
      <form name="myform" method="post" action="LoginServlet" class="form-group"style="position:absolute;left:889px;top:216px;"> 
          
           用户名: <input type="text" name="username" class="form-control" style="width:285px;"/><br/><br/>
          
           密码:<input type="text" name="userpwd" class="form-control" style="width:285px;"/><br/><br/>
          <input type="submit"  class="btn btn-default" value="登录"/>
          <a href="registerStudent.html">注册</a>
      </form>  
      </div>
      </body>
    </html>

    4.LoginServlet.java,接收login.jsp发来的请求,调用数据库文件StudentDAO.java中的doLogin()方法,查询数据返回回来后,根据查询结果跳转页面。

    package com.neusoft.servlet;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.sql.SQLException;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import com.neusoft.dao.StudentDAO;
    import com.neusoft.dao.StudentPO;
    
    public class LoginServlet extends HttpServlet {
    
    
        public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
        	 request.setCharacterEncoding("utf-8");        
    	        String username=request.getParameter("username");
    	        String userpwd=request.getParameter("userpwd");
            
            StudentDAO sd = new StudentDAO();
            try {
            	StudentPO sp=sd.doLogin(username, userpwd);;
                if(sp==null){
                    response.sendRedirect("/login.jsp");
                }else{
                    request.setAttribute("student", sp);
                    if(sp.getUserPower()==1)
                        request.getRequestDispatcher("/main.jsp").forward(request, response);//request对象提供了一个getRequestDispatcher方法,该方法返回一个RequestDispatcher对象,调用这个对象的forward方法可以实现请求转发。
                    else if(sp.getUserPower()==0)
                        request.getRequestDispatcher("/user.jsp").forward(request, response);
                }
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        public void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            doGet(request, response);
        }
    
    }

    5.StudentDAO.java 存放数据库操作的java文件,由servlet调用

    package com.neusoft.dao;
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.util.ArrayList;
    import java.util.List;
    
    
    
    public class StudentDAO {
        //链接数据库
        public Connection getConnection(){
        	    // 数据库连接对象
                Connection conn = null;
                //JDBC驱动
                String driverName="com.mysql.jdbc.Driver";
                // 数据库连接地址
                String connectionString="jdbc:mysql://localhost:3306/test?"+"user=root&password=123456&useUnicode=true&characterEncoding=utf-8";
                try{
                	//加载驱动
                    Class.forName(driverName);
                  //通过DriverManager类的getConenction方法指定三个参数,连接数据库
                    conn=DriverManager.getConnection(connectionString);
                    //conn.close();
                }catch(ClassNotFoundException e){
                    e.printStackTrace();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                return conn;
        }
        //用户登录
        public StudentPO doLogin(String username,String userpwd) throws SQLException{
           //定义SQL语句
        	String sql="select * from test where loginname=? and loginpwd=?";
            //获取连接
            Connection conn = getConnection();
            
            PreparedStatement ps = null;  //向数据库中发送数据集
            ResultSet rs = null;          //接受返回的数据集对象-结果集
            StudentPO sp = null;          //将传回的行封装为列对象
            try {
                ps=conn.prepareStatement(sql);//  创建一个Statement对象
                ps.setString(1, username); //向sql语句的问号添加数据
                ps.setString(2, userpwd);
                //返回结果集
                rs = ps.executeQuery();
                /*用Connection接口的createStatement()方法获得Statement对象传递Sql语句
                 * 用它的ExecuteQuery()方法获取单个ResultSet对象.
                 * String Sql = "select * from login";
                 *stt = conn.createStatement();
                 *set = stt.executeQuery(Sql);
                */
                
                //获取数据,遍历结果集,将数据封装到集合中
                while(rs.next()){
                    sp = new StudentPO();
                    sp.setUserName(rs.getString("loginname"));/*********/
                    sp.setUserPwd(rs.getString("loginpwd"));    
                    sp.setuserPower(rs.getInt("power"));
                    sp.setUserId(rs.getInt("id"));
                    sp.setRealName(rs.getString("name"));
                }
                
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }finally{
                rs.close();
                ps.close();
                conn.close();
            }
            
            return sp;
        }
        //按id查找
        public StudentPO selectbyid(int id) throws SQLException{
            //定义SQL语句
         	String sql="select * from test where id=?";
             //获取连接
             Connection conn = getConnection();
             
             PreparedStatement ps = null;  //向数据库中发送数据集
             ResultSet rs = null;          //接受返回的数据集对象-结果集
             StudentPO sp = null;          //将传回的行封装为列对象
             try {
                 ps=conn.prepareStatement(sql);//  创建一个Statement对象
                 ps.setInt(1, id); //向sql语句的问号添加数据
                 //返回结果集
                 rs = ps.executeQuery();
                 /*用Connection接口的createStatement()方法获得Statement对象传递Sql语句
                  * 用它的ExecuteQuery()方法获取单个ResultSet对象.
                  * String Sql = "select * from login";
                  *stt = conn.createStatement();
                  *set = stt.executeQuery(Sql);
                 */
                 
                 //获取数据,遍历结果集,将数据封装到集合中
                 while(rs.next()){
                     sp = new StudentPO();
                     sp.setUserName(rs.getString("loginname"));/*********/
                     sp.setUserPwd(rs.getString("loginpwd"));    
                     sp.setuserPower(rs.getInt("power"));
                     sp.setUserId(rs.getInt("id"));
                     sp.setRealName(rs.getString("name"));
                 }
                 
             } catch (SQLException e) {
                 // TODO Auto-generated catch block
                 e.printStackTrace();
             }finally{
                 rs.close();
                 ps.close();
                 conn.close();
             }
             
             return sp;
         }
        public int executeNonQuery(String sql,Object[]args) throws SQLException{
            Connection conn = getConnection();
            PreparedStatement ps=null;
            int result=0;
            try {
                ps = conn.prepareStatement(sql);
                
                if(args!=null){
                    for(int i=0;i<args.length;i++){
                        System.err.println("2T   "+args[i]);
                        ps.setObject(i+1, args[i]);
                    }
                }
                result=ps.executeUpdate();//返回执行成功的记录的条数 int
                
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }finally{
                ps.close();
                conn.close();
            }
            return result;
        }
        //用户注册
        public int add(int id,String name,String loginpwd,int userage,String realname,int userpower) throws SQLException{
            String sql="insert into test(id,loginname,loginpwd,age,name,power)"
                +"values(?,?,?,?,?,?)";
            
            Object[] args={id,name,loginpwd,userage,realname,userpower};
            for(int i=0;i<5;i++)
            System.err.println("1T   "+args[i]);
            int result=executeNonQuery(sql, args);
            
            return result;
        }
        //刷新用户(在哪调用)
        public int update(int id,String username,String loginpwd,int age,String name) throws SQLException{
            
            String sql="update test set loginname=? ,loginpwd=? ,name=?,age=?"
                +" where id=?";
            Object[] args={username,loginpwd,name,age,id};
            
            int result = executeNonQuery(sql, args);
            
            return result;
        }
        //删除用户信息
        public int delete(int id) throws SQLException{
            String sql="delete from test where id="+id;
            
            int result=executeNonQuery(sql, null);
            
            return result;
            
        }
        
        //封装数据集
        public List<StudentPO> queryAllStudent() throws SQLException{
            String sql="select * from test";
            Connection conn = getConnection();
            
            PreparedStatement ps = null;
            ResultSet rs = null;
            List<StudentPO> list = new ArrayList<StudentPO>();
            try {
                ps=conn.prepareStatement(sql);
                
                rs = ps.executeQuery();
                //遍历结果集,将数据封装到集合中
                
                while(rs.next()){
                    int userid=rs.getInt("id");//***********
                    int userage=rs.getInt("age");
                    int userpower=rs.getInt("power");
                    String username = rs.getString("loginname");
                    String userpwd = rs.getString("loginpwd");
                    String realname=rs.getString("name");
                
                    
                    StudentPO sp = new StudentPO();
                    sp.setUserId(userid);
                    sp.setUserName(username);
                    sp.setRealName(realname);
                    sp.setUserPwd(userpwd);
                    sp.setUserAge(userage);
                    sp.setuserPower(userpower);
                    
                    list.add(sp);
                }
                
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }finally{
                rs.close();
                ps.close();
                conn.close();
            }
            
            return list;
        }
        //注册检索
        public List<StudentPO> queryStudentById(int id) throws SQLException{
            String sql="select * from test where id="+id;
            Connection conn = getConnection();
            
            PreparedStatement ps = null;
            ResultSet rs = null;
            List<StudentPO> list = new ArrayList<StudentPO>();
            try {
                ps=conn.prepareStatement(sql);
                
                rs = ps.executeQuery();
                //遍历结果集,将数据封装到集合中
                
                while(rs.next()){
                    int userid=rs.getInt("id");//**************/
                    int userage=rs.getInt("age");
                    int userpower=rs.getInt("power");
                    String username = rs.getString("loginname");
                    String userpwd = rs.getString("loginpwd");
                    String realname=rs.getString("name");
                    
                    StudentPO sp = new StudentPO();
                    sp.setUserId(userid);
                    sp.setUserName(username);
                    sp.setUserPwd(userpwd);
                    sp.setUserAge(userage);
                    sp.setRealName(realname);
                    sp.setuserPower(userpower);
                    
                    list.add(sp);
                }
                
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }finally{
                rs.close();
                ps.close();
                conn.close();
            }
            return list;
        }
    }

    6.registerStudent.html 注册页面

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <title>registerStudent.html</title>
        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
        <meta http-equiv="description" content="this is my page">
        <meta http-equiv="content-type" content="text/html; charset=UTF-8">
        
        <!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
    
      </head>
      
      <body style="background:url('http://localhost:8080/webDomo2/login4.jpg') no-repeat;background-size: cover;">
        <center>
        <form name="myform" method="post" action="RegisterServlet" style="margin-top:200px">
            用户ID :  <input type="text" name="userid"><br/>
            用户姓名:<input type="text" name="username"/><br/>
              真实姓名:<input type="text" name="realname"><br/>
            用户密码:<input type="text" name="userpwd"><br/>
            用户年龄:<input type="text" name="userage"><br/>
            <input type="radio" name="power" value="0" checked>员工
            <input type="radio" name="power" value="1" checked="true">管理员<br/>
            <input type="submit" value="注册"/>
        </form>
        </center>
      </body>
    </html>

    7.RegisterServlet.java 接收注册页面传来的请求,调用数据库的add()方法,将用户信息添加至数据库,然后跳转登录页面

    package com.neusoft.servlet;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.sql.SQLException;
    
    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 com.neusoft.dao.StudentDAO;
    
    public class RegisterServlet extends HttpServlet{
        /*
         * HttpServlet中有两个方法需要我们自己重写
         * 需要在web.xml文件中进行注册
         */
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException {
        	 System.err.println("进入POST");
            req.setCharacterEncoding("utf-8");
            resp.setCharacterEncoding("utf-8");
            //1.接受客户端数据
            //按照客户端调教数据的name-value的形式来提取数据
            String userid=req.getParameter("userid");
            String username = req.getParameter("username");
            String realname=req.getParameter("realname");
            String userpwd=req.getParameter("userpwd");
            String userage=req.getParameter("userage");
            String userpower=req.getParameter("power");
            System.err.println("查到power"+userage);
            int id = Integer.parseInt(userid);
            int age = Integer.parseInt(userage);
            int power=Integer.parseInt(userpower);
            //2.使用JDBC,将数据添加到数据库中
            StudentDAO sd = new StudentDAO();
            //3.HttpServletResponse对象
            //将HTML代码以数据流的形式响应给客户端
            //客户端使用IE浏览器来解析响应的HTML数据流
            
            //获得一个输出流对象
    //        PrintWriter out = resp.getWriter();
    //        
    //        out.println("<html>");
    //        out.println("<head>");
    //        out.println("<meta http-equiv='content-type' content='text/html; charset=UTF-8'>");
    //        out.println("</head>");
    //        out.println("<body>");
            
            
            try {
                int result=sd.add(id,username,userpwd,age,realname,power);
                System.err.println(result);
                if(result>0){
                    //1.站内跳转,请求转发
                    //只能转发网站内部的资源
                    //转发的是同一个请求和响应对象
                    req.getRequestDispatcher("/login.jsp").forward(req, resp);
                    
                    //2.重定向跳转
                    //可以请求外部资源
                    //由于是客户端重新发起的请求,所以请求和响应对象不是同一个
                    //resp.sendRedirect("/webDemo/success.jsp");
                    
                    //out.println("添加成功");
                }else{
                    //out.println("添加失败");
                }
            } catch (SQLException e) {
                //out.println("添加失败");
            }
        }
        
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException {
            doPost(req, resp);
        }
        
    }

    8.main.jsp 管理员主页面 调用QueryAllStudent.java

    <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
    <%@page import="com.neusoft.dao.StudentPO"%>
    <%
    //java脚本
    //写java的代码
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    %>
    <%
        StudentPO stu=(StudentPO)request.getAttribute("student");
     %>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <base href="<%=basePath%>">
        
        <title>My JSP 'main.jsp' starting page</title>
        
        <meta http-equiv="pragma" content="no-cache">
        <meta http-equiv="cache-control" content="no-cache">
        <meta http-equiv="expires" content="0">    
        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
        <meta http-equiv="description" content="This is my page">
        <link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">  
    	<script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
    	<script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
        <!--
        <link rel="stylesheet" type="text/css" href="styles.css">
        -->
    
      </head>
      
      <body  style="background:url('http://localhost:8080/webDomo2/login4.jpg') no-repeat;background-size: cover;">
    		<div style="height:70px;margin-left: 458px;margin-top:261px;float:left;">
    		<h1 style="font: bold em Brush Script MT ; color:#222; text-shadow: 0px 2px 3px #666;float:left;"> User Management<h1/>
    		</div>
           <a href="QueryAllStudent" style="float:left;margin-left: 15px;margin-top: 281px;">
           <button type="button" class="btn btn-default btn-lg">
              <span class="glyphicon glyphicon-user"></span> <%=stu.getUserName() %>
    		</button>
    		</a>
      </body>
    </html>

    9.QueryAllStudent.java 查询出所有用户信息,跳转至用户信息列表页面

    package com.neusoft.servlet;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.sql.SQLException;
    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.neusoft.dao.StudentDAO;
    import com.neusoft.dao.StudentPO;
    
    public class QueryAllStudent extends HttpServlet {
    
        /**
         * The doGet method of the servlet. <br>
         *
         * This method is called when a form has its tag value method equals to get.
         * 
         * @param request the request send by the client to the server
         * @param response the response send by the server to the client
         * @throws ServletException if an error occurred
         * @throws IOException if an error occurred
         */
        public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            StudentDAO sd = new StudentDAO();
            try {
                List<StudentPO> list=sd.queryAllStudent();
                request.setAttribute("students", list);
                request.getRequestDispatcher("/showStudent.jsp").forward(request, response);
                
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            
        }
    
        public void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            doGet(request, response);
        }
    
    }

    10.showStudents.jsp 用户信息页面,实现查询、更新、删除功能,分别调用各自servlet文件,分别为select.java   Edit.java   Delete.java

    <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
    <%@page import="com.neusoft.dao.StudentPO"%>
    <%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    %>
    <%
        List<StudentPO> list=(List<StudentPO>)request.getAttribute("students");
     %>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <base href="<%=basePath%>">
        
        <title>My JSP 'showStudents.jsp' starting page</title>
        
        <meta http-equiv="pragma" content="no-cache">
        <meta http-equiv="cache-control" content="no-cache">
        <meta http-equiv="expires" content="0">    
        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
        <meta http-equiv="description" content="This is my page">
        <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
        <!--
        <link rel="stylesheet" type="text/css" href="styles.css">
        -->
    
      </head>
      
      <body style="background:url('http://localhost:8080/webDomo2/login4.jpg') no-repeat;background-size: cover;">
      <div style="width:80%;margin:10px auto">
    <div style="height:70px;margin-left: 390px;margin-top: 30px;">
    <h1 style="font: bold em Brush Script MT ; color:#222; text-shadow: 0px 2px 3px #666;float:left;">User Management</h1>
    <img src="http://localhost:8080/webDomo2/List.png" style="width: 50px;height: 50px;float:left;margin-top: 13px;"/>
    </div>
    <form id="select" method="post" action="Select" style="margin-left: 631px">
    		<input id="selectbyname" class="form-control" type="text" name="id"  placeholder="请输入用户id" style="width:200px;float:left;margin-top: 19px;"/>
        	<div class="col-sm-offset-2 col-sm-10 form-group" style="width:202px;margin:10px auto;float:left">
        	  <button type="submit" class="btn btn-default btn-info" style="width:170px; margin:10px auto">查询</button>
       	 </div>
    	</form>
    <form method="POST" id="form">
      <table align="center"  class="table table-hover table-striped" style="height:70px;margin-top: 50px;filter:alpha(opacity=50,Style=0);">
      <tr>
          <th>用户ID</th>
          <th>真实姓名</th>
          <th>用户姓名</th>
          <th>用户年龄</th>
          <th>用户权限</th>
          <th>操作</th>
      </tr>
        <%
            for(StudentPO s :list){
        %>
        <tr>
            <td><%=s.getUserId() %></td>
            <td><%=s.getRealName() %>></td>
            <td><%=s.getUserName() %></td>
            <td><%=s.getUserAge() %></td>
            <td><%=s.getUserPower() %></td>
            <td>
    						<div class="btn btn-default" onclick="update('<%=s.getUserId() %>')">更新</div>
    						<div class="btn btn-default" onclick="deleteUser('<%=s.getUserId() %>')">删除</div>
    					</td>
        </tr>
        
        <% 
            }
         %>
         </table>
    		<input id="user_id" type="hidden" name="userid" />
         </form>
         </div>
      </body>
    <script src="https://code.jquery.com/jquery.js"></script>
      <script type="text/javascript">
    var update=function(id){
    	$("#user_id").val(id);
    	$("#form").attr("action","Edit");
    	$("#form").submit();
    };
    var deleteUser=function(id){
    	$("#user_id").val(id);
    	$("#form").attr("action","Delete");
    	$("#form").submit();
    };
    </script>
    </html>
    

    11.Edit.java  跳转至编辑页面,调用Edit.jsp文件

    package com.neusoft.servlet;
    
    import java.io.IOException;
    import java.sql.SQLException;
    
    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 com.neusoft.dao.StudentDAO;
    import com.neusoft.dao.StudentPO;
    
    public class Edit extends HttpServlet {
    	private static final long serialVersionUID = 1L;
        public Edit() {
            super();
            // TODO Auto-generated constructor stub
        }
    	protected void doGet(HttpServletRequest request, HttpServletResponse response) 
    			throws ServletException, IOException {
    		// TODO Auto-generated method stub
    		System.err.println("进到servlet");
    	        request.setCharacterEncoding("utf-8");        
    	        String id=request.getParameter("userid");
    	        System.err.println("获取id为"+id);
    	        int userid = Integer.parseInt(id);
    	        StudentDAO sd = new StudentDAO();
    	        try {
    	            StudentPO sp=sd.selectbyid(userid);
    	            if(sp==null){
    	            }else{
    	                request.setAttribute("student", sp);
    	                    request.getRequestDispatcher("/Edit.jsp").forward(request, response);//request对象提供了一个getRequestDispatcher方法,该方法返回一个RequestDispatcher对象,调用这个对象的forward方法可以实现请求转发
    	            }
    	        } catch (SQLException e) {
    	            // TODO Auto-generated catch block
    	            e.printStackTrace();
    	        }
    	}
    
    	/**
    	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
    	 */
    	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		// TODO Auto-generated method stub
    		doGet(request, response);
    	}
    
    }
    

    12.Edit.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
          <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <title>修改用户信息页面</title>
    </head>
    <body style="background:url('http://localhost:8080/webDomo2/login4.jpg') no-repeat;background-size: cover;">
    <div style="width:80%;margin:10px auto">
    <div style="height:70px;margin-left: 390px;">
    <h1 style="font: bold em Brush Script MT ; color:#222; text-shadow: 0px 2px 3px #666;float:left;">User Management<h1/>
    <img src="http://localhost:8080/maven02/resources/img/List.png" style="width: 50px;height: 50px;float:left;margin-top: 13px;"/>
    </div>
    	<form class="form-horizontal" action="Editend" method="POST">
    	 
      <div class="form-group">
        <label class="col-sm-2 control-label">用户名:</label>
        <div class="col-sm-10 center-block">
         <input type="text" class="form-control" name="username" id="inputEmail3" value="${student.getUserName()}"> 
        </div>
      </div>
      
      <div class="form-group">
        <label for="inputPassword3" class="col-sm-2 control-label">密码</label>
        <div class="col-sm-10">
          <input type="password" class="form-control" id="inputPassword3" name="password" value="${student.getUserPwd()}">
        </div>
      </div>
      
      <div class="form-group">
        <label for="inputPassword3" class="col-sm-2 control-label">年龄</label>
        <div class="col-sm-10">
          <input type="password" class="form-control" id="inputPassword3" name="age" value="${student.getUserAge()}">
        </div>
      </div>
      
       <div class="form-group">
        <label class="col-sm-2 control-label">真实姓名:</label>
        <div class="col-sm-10 center-block">
         <input type="text" class="form-control" name="name" id="inputEmail3" value="${student.getRealName()}"> 
        </div>
        </div>
        
      <div class="form-group">
        <div class="col-sm-offset-2 col-sm-10">
          <button type="submit" class="btn btn-default">确定</button>
        </div>
      </div>
      	<input id="user_id" type="hidden" name="userid" value="${student.getUserId()}" />
    </form>
    </div>
      <!-- jQuery (Bootstrap 的 JavaScript 插件需要引入 jQuery) -->
          <script src="https://code.jquery.com/jquery.js"></script>
          <!-- 包括所有已编译的插件 -->
          <script src="js/bootstrap.min.js"></script>
          <script type="text/javascript">
    	$(function(){
    		if(""=="${code}"){
    			console.log("没有异常");
    		}else if("500"=="${code}"){
    			alert("${msg}");
    		}
    	});
    </script>
    </body>
    </html>

    13.Editend.java  编辑页面调用Editend.java

    package com.neusoft.servlet;
    
    import java.io.IOException;
    import java.sql.SQLException;
    
    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 com.neusoft.dao.StudentDAO;
    
    /**
     * Servlet implementation class Editend
     */
    public class Editend extends HttpServlet {
    	private static final long serialVersionUID = 1L;
           
        /**
         * @see HttpServlet#HttpServlet()
         */
        public Editend() {
            super();
            // TODO Auto-generated constructor stub
        }
    
    	/**
    	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
    	 */
    	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    		// TODO Auto-generated method stub
    		 System.err.println("进入POST");
    	        req.setCharacterEncoding("utf-8");
    	        resp.setCharacterEncoding("utf-8");
    	        //1.接受客户端数据
    	        //按照客户端调教数据的name-value的形式来提取数据
    	        String userid=req.getParameter("userid");
    	        String username = req.getParameter("username");
    	        String realname=req.getParameter("name");
    	        String userpwd=req.getParameter("password");
    	        String userage=req.getParameter("age");
    	        String userpower=req.getParameter("power");
    	        System.err.println("查到power"+userage);
    	        int id = Integer.parseInt(userid);
    	        int age = Integer.parseInt(userage);
    	        //2.使用JDBC,将数据添加到数据库中
    	        StudentDAO sd = new StudentDAO();
    	        //3.HttpServletResponse对象
    	        //将HTML代码以数据流的形式响应给客户端
    	        //客户端使用IE浏览器来解析响应的HTML数据流
    	        
    	        //获得一个输出流对象
    //	        PrintWriter out = resp.getWriter();
    //	        
    //	        out.println("<html>");
    //	        out.println("<head>");
    //	        out.println("<meta http-equiv='content-type' content='text/html; charset=UTF-8'>");
    //	        out.println("</head>");
    //	        out.println("<body>");
    	        
    	        
    	        try {
    	            int result=sd.update(id,username,userpwd,age,realname);
    	            System.err.println(result);
    	            if(result>0){
    	                //1.站内跳转,请求转发
    	                //只能转发网站内部的资源
    	                //转发的是同一个请求和响应对象
    	                req.getRequestDispatcher("/QueryAllStudent").forward(req, resp);
    	                
    	                //2.重定向跳转
    	                //可以请求外部资源
    	                //由于是客户端重新发起的请求,所以请求和响应对象不是同一个
    	                //resp.sendRedirect("/webDemo/success.jsp");
    	                
    	                //out.println("添加成功");
    	            }else{
    	                //out.println("添加失败");
    	            }
    	        } catch (SQLException e) {
    	            //out.println("添加失败");
    	        }
    	}
    
    	/**
    	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
    	 */
    	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		// TODO Auto-generated method stub
    		doGet(request, response);
    	}
    
    }
    

    14.select.java  接收查询请求

    package com.neusoft.servlet;
    
    import java.io.IOException;
    import java.sql.SQLException;
    
    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 com.neusoft.dao.StudentDAO;
    import com.neusoft.dao.StudentPO;
    
    /**
     * Servlet implementation class Select
     */
    public class Select extends HttpServlet {
    	private static final long serialVersionUID = 1L;
           
        /**
         * @see HttpServlet#HttpServlet()
         */
        public Select() {
            super();
            // TODO Auto-generated constructor stub
        }
    
    	/**
    	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
    	 */
    	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		// TODO Auto-generated method stub
    		System.err.println("进到servlet");
            request.setCharacterEncoding("utf-8");        
            String id=request.getParameter("id");
            System.err.println("获取id为"+id);
            int userid = Integer.parseInt(id);
            StudentDAO sd = new StudentDAO();
            try {
            	StudentPO sp=sd.selectbyid(userid);
                if(sp==null){
                }else{
                    System.err.println("sp"+sp.getRealName());
                        request.getRequestDispatcher("QueryOnlyOne?userid="+sp.getUserId()).forward(request, response);//request对象提供了一个getRequestDispatcher方法,该方法返回一个RequestDispatcher对象,调用这个对象的forward方法可以实现请求转发
                }
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    	}
    
    	/**
    	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
    	 */
    	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		// TODO Auto-generated method stub
    		doGet(request, response);
    	}
    
    }
    

    15.delete.java 接收删除请求

    package com.neusoft.servlet;
    
    import java.io.IOException;
    import java.sql.SQLException;
    
    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 com.neusoft.dao.StudentDAO;
    import com.neusoft.dao.StudentPO;
    
    /**
     * Servlet implementation class delete
     */
    public class Delete extends HttpServlet {
    	private static final long serialVersionUID = 1L;
           
        /**
         * @see HttpServlet#HttpServlet()
         */
        public Delete() {
            super();
            // TODO Auto-generated constructor stub
        }
    
    	/**
    	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
    	 */
    	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		// TODO Auto-generated method stub
    		System.err.println("进到servlet");
            request.setCharacterEncoding("utf-8");        
            String id=request.getParameter("userid");
            System.err.println("获取id为"+id);
            int userid = Integer.parseInt(id);
            StudentDAO sd = new StudentDAO();
            try {
            	int result=sd.delete(userid);
            	 if(result>0){
    	                //1.站内跳转,请求转发
    	                //只能转发网站内部的资源
    	                //转发的是同一个请求和响应对象
            		 request.getRequestDispatcher("/QueryAllStudent").forward(request, response);
    	                
    	                //2.重定向跳转
    	                //可以请求外部资源
    	                //由于是客户端重新发起的请求,所以请求和响应对象不是同一个
    	                //resp.sendRedirect("/webDemo/success.jsp");
    	                
    	                //out.println("添加成功");
    	            }else{
    	                //out.println("添加失败");
    	            }
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    	}
    
    	/**
    	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
    	 */
    	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		// TODO Auto-generated method stub
    		doGet(request, response);
    	}
    
    }
    

    16.QueryOnlyOne.java 接收普通用户的主页面的请求

    package com.neusoft.servlet;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.sql.SQLException;
    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.neusoft.dao.StudentDAO;
    import com.neusoft.dao.StudentPO;
    
    public class QueryOnlyOne extends HttpServlet {
    
        /**
         * The doGet method of the servlet. <br>
         *
         * This method is called when a form has its tag value method equals to get.
         * 
         * @param request the request send by the client to the server
         * @param response the response send by the server to the client
         * @throws ServletException if an error occurred
         * @throws IOException if an error occurred
         */
        public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            StudentDAO sd = new StudentDAO();
            StudentPO  sp = new StudentPO();
            String id=request.getParameter("userid");
            int userid = Integer.parseInt(id);
            
            try {
                    //将对象保存在请求对象中
                    List<StudentPO> list=sd.queryStudentById(userid);
                     request.setAttribute("students", list);
                    request.getRequestDispatcher("/showStudent.jsp").forward(request, response);
                
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            
        }
    
        public void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            doGet(request, response);
        }
    
    }

    17.web.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
      <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
      </welcome-file-list>
      <servlet>
        <servlet-name>RegisterServlet</servlet-name>
        <servlet-class>com.neusoft.servlet.RegisterServlet</servlet-class>
      </servlet>
      <servlet>
        <servlet-name>Edit</servlet-name>
        <servlet-class>com.neusoft.servlet.Edit</servlet-class>
      </servlet>
      <servlet>
        <servlet-name>Select</servlet-name>
        <servlet-class>com.neusoft.servlet.Select</servlet-class>
      </servlet>
      <servlet>
        <servlet-name>Delete</servlet-name>
        <servlet-class>com.neusoft.servlet.Delete</servlet-class>
      </servlet>
      <servlet>
        <servlet-name>Editend</servlet-name>
        <servlet-class>com.neusoft.servlet.Editend</servlet-class>
      </servlet>
      <servlet>
        <servlet-name>QueryOnlyOne</servlet-name>
        <servlet-class>com.neusoft.servlet.QueryOnlyOne</servlet-class>
      </servlet>
      <servlet>
        <servlet-name>LoginServlet</servlet-name>
        <servlet-class>com.neusoft.servlet.LoginServlet</servlet-class>
      </servlet>
      <servlet>
        <description>This is the description of my J2EE component</description>
        <display-name>This is the display name of my J2EE component</display-name>
        <servlet-name>QueryAllStudent</servlet-name>
        <servlet-class>com.neusoft.servlet.QueryAllStudent</servlet-class>
      </servlet>
      <servlet-mapping>
        <servlet-name>QueryOnlyOne</servlet-name>
        <url-pattern>/QueryOnlyOne</url-pattern>
      </servlet-mapping>
      <servlet-mapping>
        <servlet-name>RegisterServlet</servlet-name>
        <url-pattern>/RegisterServlet</url-pattern>
      </servlet-mapping>
      <servlet-mapping>
        <servlet-name>LoginServlet</servlet-name>
        <url-pattern>/LoginServlet</url-pattern>
      </servlet-mapping>
      <servlet-mapping>
        <servlet-name>QueryAllStudent</servlet-name>
        <url-pattern>/QueryAllStudent</url-pattern>
      </servlet-mapping>
      <servlet-mapping>
        <servlet-name>Edit</servlet-name>
        <url-pattern>/Edit</url-pattern>
      </servlet-mapping>
        <servlet-mapping>
        <servlet-name>Select</servlet-name>
        <url-pattern>/Select</url-pattern>
      </servlet-mapping>
      <servlet-mapping>
        <servlet-name>Delete</servlet-name>
        <url-pattern>/Delete</url-pattern>
      </servlet-mapping>
      <servlet-mapping>
        <servlet-name>Editend</servlet-name>
        <url-pattern>/Editend</url-pattern>
      </servlet-mapping>
    </web-app>

    18.StudentPO.java  实体类

    package com.neusoft.dao;
    
    import java.util.List;
    
    public class StudentPO {
        private int userId;
        private String userName;
        private int userAge;
        private String userPwd;
        private String realName;
        private int userPower;
        public int getUserPower(){
            return userPower;
        }
        public void setuserPower(int userpower) {
            this.userPower = userpower;
        }
        public String getRealName(){
            return realName;
        }
        public void setRealName(String realname) {
            this.realName = realname;
        }
        public String getUserPwd() {
            return userPwd;
        }
        public void setUserPwd(String userpwd) {
            this.userPwd = userpwd;
        }
        public int getUserId() {
            return userId;
        }
        public void setUserId(int userId) {
            this.userId = userId;
        }
        public String getUserName() {
            return userName;
        }
        public void setUserName(String userName) {
            this.userName = userName;
        }
        public int getUserAge() {
            return userAge;
        }
        public void setUserAge(int userAge) {
            this.userAge = userAge;
        }
        
    }

    完成!

     

    三.效果图展示

    1.登录界面——用户的登录注册

    2.主页面——按钮跳转用户信息列表页

    3.用户信息列表——实现用户信息的查询、修改、删除

    4.编辑页面——编辑用户信息

    5.注册页面——实现用户的增加

    展开全文
  • 适合学生交项目,满足增删改查
  • 前言本篇使用Python Web框架Django连接和操作MySQL数据库学生信息管理系统(SMS),主要包含对学生信息增删改查功能,旨在快速入门Python Web,少走弯路。效果演示在项目实战最后一节,文章结尾有整个项目的源码地址。...

    添加学生

    编号

    姓名

    学号

    操作

    {% for student in students %}

    {{ forloop.counter }}

    {{ student.student_name }}

    {{ student.student_no }}

    编辑

    删除

    {% endfor %}

    展开全文
  • 实现web增删改查

    千次阅读 2019-06-11 16:00:41
    1.把该导入的jar包和jquery导入 2.主页的jsp代码: <%@ page contentType="text/html;charset=utf-8" language="java" %> <script src="https://code.jquery.com/jquery-3.2.1.min.js">...script s...

    1.把该导入的jar包和jquery导入

    2.主页的jsp代码:

    <%@ page contentType="text/html;charset=utf-8" language="java" %>
    <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
    <script src="js/util.js"></script>
    <html>
    <head>
        <title>table</title >
    </head>
    <style type="text/css">
        body {
            font: 0.8em 宋体;
        }
        table.tbl{ /* 折叠所有表格边框--使单元格共享边框*/
            border-collapse:collapse;
        }
        table.tbl td,th { /* 给单元格设置边框线 */
            border: 1px solid #99CCCC;
            text-align:left;
            padding:4px 4px;
        }
        table.tbl th[scope="col"] {  /*给列表头文字加粗,加背景色 */
            font: inherit;
            background-color:#00ddcc;
        }
        table.tbl caption {
            font-size: 1.2em;
            margin-bottom: .5em;
        }
        #button1{
            background-color: #EFEEDC;
            height: 60px;
            padding: 10px 0;
            line-height: 28px;
        }
        #button2{
            background-color: #EFEEDC;
            height: 60px;
            padding: 10px 0;
            line-height: 28px;
        }
        #button3{
            background-color: #EFEEDC;
            height: 60px;
            padding: 10px 0;
            line-height: 28px;
        }
        </style>
    <body>
    <table border="1" cellspacing="0" cellpadding="0" id="tbl">
    </table>
    <button id="button1" onclick="add()">添加</button>
    <button id="button2" onclick="deletes()">删除</button>
    <button id="button3" onclick="update()">修改</button>
    <script>
        var servletUrl = "./student";
        var students;
        var selectedIndex;
        var stuId;
    
        $(function () {
            query();
        });
    
        //查询的数据库表单
        function query() {
            var param = {op:"query"};
            // var e = document.getElementById("#id");
            // $("#id")
            $.post(servletUrl,param,function (result) {
                console.log(result);
                var data = JSON.parse(result);
                if (data.success) {
                    students = data.students;
                    var str = "<tr>\n" +
                        "        <th>ID</th>\n" +
                        "        <th>姓名</th>\n" +
                        "        <th>性别</th>\n" +
                        "        <th>生日</th>\n" +
                        "    </tr>";
                    for (var i in data.students) {
                        str += "<tr onclick='selection(this,"+data.students[i].id+","+i+")'>" +
                            "<th>" + data.students[i].id + "</th>" +
                            "<th>" + data.students[i].name + "</th>" +
                            "<th>" + data.students[i].sex + "</th>" +
                            "<th>" + data.students[i].birthday + "</th>" +
                            "</tr>";
                    }
                    $("#tbl").html(str);
                } else {
                    alert(data.msg);
                }
            });
        }
    
        //添加对象
        function add() {
            window.location.href = "reg.jsp";   //跳转到另外一个填写信息的页面
        }
    
        //删除对象
        function deletes() {
            var student = {"id":stuId,"name":"","sex":"","birthday":""};
            var param = {op: "delete", student: JSON.stringify(student)};
            $.post(servletUrl, param, function (result) {
                console.log(result);
                var data = JSON.parse(result);
                if (data.success) {
                    window.location.reload();
                    alert("删除成功");
                } else {
                    alert(data.msg);
                }
            });
        }
    
        //捕客户端选中对象
        function selection(selectedTr,id,index) {
            $("tr").css("background","#fcfbe9");
            $(selectedTr).css("background","#b6b6fc");
            selectedIndex = index;
            stuId = id;
        }
    
        //修改对象
        function update() {
            var param = encodeURI(JSON.stringify(students[selectedIndex])); //Tomcat9.0以上需要自己加上解码命令
            window.location.href = "update.jsp?student="+param;
        }
    </script>
    </body>
    </html>

    页面效果:

    3.跳转添加信息页面jsp代码:

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
    <html>
    <head>
        <title>填写用户信息</title>
    </head>
    <body>
    <form method="post">
        姓名:<input id="username" type="text" name="username"><br>
        性别:<input id="sex" type="radio" name="sex" value="男" checked="checked">男
        <input type="radio" name="sex" value="女">女<br>
        生日:<input id="birthday" type="text" name="birthday"><br>
        <input type="button" value="提交" onclick="get()"><br>
    </form>
    </body>
    <script>
        //得到用户数据
        function get() {
            var username = document.getElementById('username').value;
            var sex = $('input:radio[name="sex"]:checked').val();
            var birthday = document.getElementById('birthday').value;
            var servletUrl = "./student";
            var student = {"name":username,"sex":sex,"birthday":birthday};
            var param = {op: "add", student: JSON.stringify(student)};
            $.post(servletUrl, param, function (result) {
                console.log(result);
                var data = JSON.parse(result);
                if (data.success) {
                    alert("添加成功,一秒后跳转到主页面");
                    setTimeout(function(){
                        window.location.href = "table.jsp";
                    }, 1000);
                } else {
                    alert(data.msg);
                }
            });
        }
    </script>
    </html>

    4.自己在修改信息也是跳转到另外一个jsp页面并保存之前的用户信息: 

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
    <script src="js/util.js"></script>
    <script src="js/jquery.params.js"></script>
    <html>
    <head>
        <title>修改属性</title>
    </head>
    <body>
    <form method="post">
        姓名:<input id="username" type="text" name="username"><br>
        性别:
        <input type="radio" name="sex" value="男" checked="checked">男
        <input type="radio" name="sex" value="女">女<br>
        生日:<input id="birthday" type="text" name="birthday"><br>
        <input type="button" value="提交" onclick="save()"><br>
    </form>
    </body>
    <script>
        var student;
        var id;
    
        $(function () {
            init();
        })
    
        //填充原有属性
        function init() {
            student = JSON.parse($.query.get("student"));
            id = student.id;
            $("#username").val(student.name);
            $("#birthday").val(student.birthday);
            $("input:radio[name=sex][value="+student.sex+"]").attr("checked",true);
        }
    
        //储存修改后数据
        function save() {
            var username = document.getElementById('username').value;
            var sex = $('input:radio[name="sex"]:checked').val();
            var birthday = document.getElementById('birthday').value;
            var servletUrl = "./student";
            var student = {"id":id,"name":username,"sex":sex,"birthday":birthday};
            var param = {op: "update", student: JSON.stringify(student)};
            $.post(servletUrl, param, function (result) {
                console.log(result);
                var data = JSON.parse(result);
                if (data.success) {
                    alert("修改成功,一秒后跳转到主页面");
                    setTimeout(function(){
                        window.location.href = "table.jsp";
                    }, 1000);
                } else {
                    alert(data.msg);
                }
            });
        }
    </script>
    </html>

     servlet端后台代码:

    public class StudentServlet extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            doPost(req, resp);
        }
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            req.setCharacterEncoding("UTF-8");
            resp.setContentType("text/html;charset=UTF-8");
            String op = req.getParameter("op");
            String result = "";
            switch (op){
                case "add":
                    result = add(req);
                break;
                case "delete":
                    result = delete(req);
                    break;
                case "update":
                    result = update(req);
                    break;
                case "query":
                    result = query(req);
            }
            PrintWriter out = resp.getWriter();
            out.println(result);
            out.flush();
            out.close();
        }
    
        /**
         * 修改数据信息
         * @param req
         * @return 成功提示,或失败提示
         */
        private String update(HttpServletRequest req) {
            Student student = JSON.parseObject(req.getParameter("student"),Student.class);
            int effect = StudentDAO.update(student);
            JSONObject json = new JSONObject();
            if(effect == -1){
                json.put("success",false);
                json.put("msg","修改数据错误");
            }else{
                json.put("success",true);
                json.put("effect",effect);
            }
            return json.toString();
        }
    
        /**
         * 删除数据信息
         * @param req
         * @return 成功提示,或失败提示
         */
        private String delete(HttpServletRequest req) {
            Student student = JSON.parseObject(req.getParameter("student"),Student.class);
            int effect = StudentDAO.delete(student.getId());
            JSONObject json = new JSONObject();
            if(effect == -1){
                json.put("success",false);
                json.put("msg","添加数据错误");
            }else{
                json.put("success",true);
                json.put("effect",effect);
            }
            return json.toString();
        }
    
        /**
         * 增添数据信息
         * @param req
         * @return 成功提示,或失败提示
         */
        private String add(HttpServletRequest req) {
            Student student = JSON.parseObject(req.getParameter("student"),Student.class);
            int effect = StudentDAO.insert(student);
            JSONObject json = new JSONObject();
            if(effect == -1){
                json.put("success",false);
                json.put("msg","添加数据错误");
            }else{
                json.put("success",true);
                json.put("effect",effect);
            }
            return json.toString();
        }
    
        /**
         * 查询数据信息
         * @param req
         * @return 成功提示,或失败提示
         */
        private String query(HttpServletRequest req) {
            List<Student> students = StudentDAO.select();
            JSONObject json = new JSONObject();
            if(students == null){
                json.put("success",false);
                json.put("msg","查询数据错误");
            }else{
                json.put("success",true);
                json.put("students",students);
            }
            return json.toString();
        }
    
    }

    Dao层代码就不展示了。

    展开全文
  • 个人认为学习一种MVC框架时,当入了个门之后可以自己写一套增删改查,这样可以巩固认识! 本次Demo使用工具及框架:Myeclipse,Tomcat7.0,jdk1.7 框架:SpringMVC Spring 以下附上目录结构: 我把数据持久化操作写...

    最近在自学SpringMVC,有Spring的基础,但不是很深,仅存在于表面。当前在手书籍有《SpringMVC学习指南》

    个人认为学习一种MVC框架时,当入了个门之后可以自己写一套增删改查,这样可以巩固认识!

    本次Demo使用工具及框架:Myeclipse,Tomcat7.0,jdk1.7 框架:SpringMVC Spring

    以下附上目录结构:


    我把数据持久化操作写在了Service层里,因为只是一个小Demo,所以不操作数据库了,直接有Map做数据存储。

    附上2个Spring配置文件及WEB配置文件





    以下是Controller层的源码





    需要完整源码的留下邮箱地址,新手互相学习,我这里还有Struts2的增删改查Demo,有需要的留言

    展开全文
  • jsp增删改查源代码

    2016-08-31 20:56:17
    jsp简单的web增删改查代码,附上mysql数据库
  • jtds 1.3.1下载 ... 源码(网上下载的,我测试了一下,成功): package com.androidmysqltest; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; im
  • 使用C#技术实现的对单表的增删改查功能!
  • java学习增删改查完整源码(带数据库),特别适合新手上路,祝你们好运!
  • 这次是做一个不使用框架,用最原始的方法实现了java-jsp的web应用,栗子呢包含增删改查、登陆登出、分页、事务处理和权限管理这几个web应用的基本要素,界面就做得很烂了,除了对齐以外就没用到CSS了,也是节约时间...
  • spring boot+layui实现增删改查实战

    千次阅读 多人点赞 2019-12-24 01:43:23
    我知道很多人都有这个需求,为了使大家快速上手,我把自己写的最实用的增删改查案例完整的展示出来。 需要源码的请留下邮箱! Layui官网:https://www.layui.com/doc/ 后台:spring boot2.0,数据的话用的...
  • 使用django开发的Python web demo,包含Python源码和template页面的完整程序,可实现对单表的增删查改的功能
  • 这次是做一个不使用框架,用最原始的方法实现了java-jsp的web应用,栗子呢包含增删改查、登陆登出、分页、事务处理和权限管理这几个web应用的基本要素,界面就做得很烂了,除了对齐以外就没用到CSS了,也是节约时间...
  • 基于SSH框架的增删改查实例附带源码

    万次阅读 多人点赞 2016-12-03 22:18:08
    一步一教你搭建SSH框架,实现简单的增删改查功能 一、首先创建一个Java web项目,并按下图建好项目目录 二、在网上搜索ssh所需jar包,并将其放到WEB_INF下的lib里面(这里截图了部分) 三、如下图配置web.xml...
  • 本篇使用Python Web框架Django连接和操作MySQL数据库学生信息管理系统(SMS),主要包含对学生信息增删改查功能,旨在快速入门Python Web,少走弯路。效果演示在项目实战最后一节,文章结尾有整个项目的源码地址。 开发...
  • SSH实现简单增删改查的功能实例

    万次阅读 2015-07-22 17:05:37
    在网上看到一篇写的很不错的关于SSH 整合实现简单的增删改查功能的实例。 因为也是初次使用SSH框架,通过这样的实例更好的理解SSH框架。对原本的代码进行了修改和优化。如有不足之处,还请指教。 原文链接:...
  • H5-WebSQL的增删改查(Demo)

    千次阅读 2018-08-22 14:06:53
    Web SQL 关于 Web SQL 数据库 API 并不是 HTML5 规范的一部分,但是它是一个独立的规范,引入了一组使用 SQL 操作客户端数据库的 APIs。在当前的主流浏览器中全部支持Web SQL规范。 作用 Web SQL的...
  • 1.增加雇员信息页面:addEmployee.jsp <%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <!DOCTYPE html> <html> <head>...bod
  • Java Web实现MySQL数据库增删改查

    千次阅读 2019-11-03 19:20:40
    JavaWeb案例:实现数据库增删改查功能 一、创建数据库与表 创建JavaWeb项目TestStudent: 1.在WEB-INF里创建lib目录,添加数据库驱动jar包: 2.在web目录里创建META-INF子目录,在里面创建数据源配置文件...
  • 本文实现了用MyEclipse,编写Servlet,实现对SQLServer数据库的增删改查,适合新手入门,文末提供工程文件源码下载。1.新建数据库test以及表users表users共四列(id,name,psd,tel) 具体操作步骤见上篇博文。...
  • Oracel的期末作业,写一个简单的web页面连接oracle数据库实现增删改查 完整源码链接:https://pan.baidu.com/s/1f2TfFt-5NFNspYM43J2muA 提取码: mfdh 开发环境: 编译器:Eclipse 数据库:Oracle 数据库管理...
  • 简单的JDBC的增删改查操作->抽取了基类,附源码

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 23,218
精华内容 9,287
关键字:

web的增删改查源码