• Java web 简单的增删改查程序


    就是简单的对数据进行增删改查。代码如下:

      1.bean层:用来封装属性及其get set方法 toString方法,有参构造方法,无参构造方法等。

    复制代码
    public class Bean {
        private int id;
        private String name;
        private String password;
        private String sex;
        
        public int getId() {
            return id;
        }
    
        public void setId(int id) {
            this.id = id;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public String getPassword() {
            return password;
        }
    
        public void setPassword(String password) {
            this.password = password;
        }
    
        public String getSex() {
            return sex;
        }
    
        public void setSex(String sex) {
            this.sex = sex;
        }
    
        @Override
        public String toString() {
            return "Bean [id=" + id + ", name=" + name + ", password=" + password + ", sex=" + sex + "]";
        }
    
        public Bean(int id, String name, String password, String sex) {
            super();
            this.id = id;
            this.name = name;
            this.password = password;
            this.sex = sex;
        }
    
        public Bean() {
            // TODO Auto-generated constructor stub
        }
    
    }
    复制代码

      2.DBUtil:对数据库连接关闭操作的封装:

    复制代码
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    
    
    public class DBUtil {
        private static String url = "jdbc:mysql://localhost:3306/db10?useUnicode=true&characterEncoding=utf8";
        private static String user = "root";
        private static String password = "root";
        private static String jdbcName="com.mysql.jdbc.Driver";
        private Connection con=null;
        public static  Connection getConnection() {
            Connection con=null;
            try {
                Class.forName(jdbcName);
                con=DriverManager.getConnection(url, user, password);
                //System.out.println("数据库连接成功");
            } catch (Exception e) {
                // TODO Auto-generated catch block
                //System.out.println("数据库连接失败");
                e.printStackTrace();
            }
            return con;
            
        }
        public static void close(Connection con) {
            if(con!=null)
                try {
                    con.close();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            
        }
        public static void close(Statement state, Connection conn) {
            if(state!=null) {
                try {
                    state.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(conn!=null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        
        public static void close(ResultSet rs, Statement state, Connection conn) {
            if(rs!=null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(state!=null) {
                try {
                    state.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(conn!=null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    
    }
    复制代码

    可以将其定义为一个工具类,每次使用的时候直接复制,然后更改url里数据库的名字,这样可以提高效率。

      dao层:对数据库的各种增删改查方法的封装:

    复制代码
      1 import java.sql.Connection;
      2 import java.sql.PreparedStatement;
      3 import java.sql.ResultSet;
      4 import java.sql.SQLException;
      5 import java.sql.Statement;
      6 import java.util.ArrayList;
      7 import java.util.List;
      8 
      9 import org.junit.jupiter.api.Test;
     10 
     11 public class Dao {//dao层
     12         private DBUtil dbutil=new DBUtil();
     13         
     14 
     15     public Dao() {
     16         // TODO Auto-generated constructor stub
     17     }
     18     @Test
     19     public boolean insert(Bean bean) {//插入数据的方法
     20         boolean f=false;
     21         String sql="insert into info(id,name,password,sex) values('"+bean.getId()+"','"+bean.getName()+"','"+bean.getPassword()+"','"+bean.getSex()+"')";
     22         Connection conn=DBUtil.getConnection();//数据库连接,加载驱动
     23         Statement state=null; 
     24         try
     25         {
     26             state=conn.createStatement();//实例化Statement对象,方便对sql语句进行操作
     27             System.out.println(conn);
     28             state.executeUpdate(sql);
     29             f=true;
     30             //执行数据库更新操作用于执行INSERT、UPDATE或DELETE语句以及SQLDDL(数据定义语言)语句,
     31             //例如CREATETABLE和DROPTABLE,(创建表和删除表)
     32         }catch(Exception e)//当try语句中s出现异常时,会执行catch中的语句
     33           {
     34             e.printStackTrace();//捕获异常的语句
     35           }
     36          finally //finally作为异常处理的一部分,它只能用在try/catch语句中,并且附带一个语句块,表示这段语句最终一定会被执行(不管有没有抛出异常),经常被用在需要释放资源的情况下。
     37          {
     38              DBUtil.close(conn);
     39          }
     40         return f;
     41     }
     42     
     43     public boolean delete(int id ) {//删除方法
     44         String sql="delete from info where id='"+id+"'";
     45         boolean f=false;
     46         Connection conn =DBUtil.getConnection();
     47         Statement st=null;
     48         try {
     49             st=conn.createStatement();
     50             st.executeUpdate(sql);
     51             f=true;
     52         } catch (SQLException e) {
     53             // TODO Auto-generated catch block
     54             e.printStackTrace();
     55         }
     56         finally{
     57             DBUtil.close(st, conn);
     58         }
     59         return f;
     60     }
     61     public boolean update(Bean bean) {//更新方法
     62         String sql="update info set name='"+bean.getName()+"',password='"+bean.getPassword()+"',sex='"+bean.getSex()+"'where id='"+bean.getId()+"'";
     63         Connection conn=DBUtil.getConnection();
     64         boolean f=false;
     65         Statement st=null;
     66         try {
     67             st=conn.createStatement();
     68             st.executeUpdate(sql);
     69             f=true;
     70         } catch (SQLException e) {
     71             // TODO Auto-generated catch block
     72             e.printStackTrace();
     73         }
     74         return f;
     75     }
     76     
     77     public List<Bean> list(){//查询所有方法
     78         String sql="select * from info order by id ASC";
     79         Connection conn=DBUtil.getConnection();
     80         Statement st=null;
     81         List<Bean> list=new ArrayList<>();
     82         ResultSet rs=null;
     83         Bean bean=null;
     84         try {
     85             st=conn.createStatement();
     86             st.executeQuery(sql);
     87             rs=st.executeQuery(sql);
     88             while(rs.next()) {
     89                 
     90                 int id=rs.getInt("id");
     91                 String name = rs.getString("name");
     92                 String password = rs.getString("password");
     93                 String sex = rs.getString("sex");
     94                 bean=new Bean(id,name,password,sex);
     95                 list.add(bean);
     96             }
     97         } catch (SQLException e) {
     98             // TODO Auto-generated catch block
     99             e.printStackTrace();
    100         }
    101         finally {
    102             DBUtil.close(rs, st, conn);
    103         }
    104         return list;
    105     }
    106     
    107     
    108     
    109     
    110     
    111     }
    复制代码

    对数据库进行操作的方法都封装在里面。

      servlet:简单说servlet就是跳转的类,当什么情况下干什么跳转到哪里。

    复制代码
    import java.io.IOException;
    import java.io.UnsupportedEncodingException;
    import java.util.List;
    
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    /**
     * Servlet implementation class servlet
     */
    @WebServlet("/servlet")
    public class servlet extends HttpServlet {
        Dao dao=new Dao();
        private static final long serialVersionUID = 1L;
        /**
         * @see HttpServlet#HttpServlet()
         */
        public servlet() {
            super();
            // TODO Auto-generated constructor stub
        }
    
    
        private void update(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            // TODO Auto-generated method stub
            request.setCharacterEncoding("utf-8");
            int id = Integer.parseInt(request.getParameter("id"));
            String name = request.getParameter("name");
            String password = request.getParameter("password");
            String sex = request.getParameter("sex");
            Bean bean=new Bean(id,name,password,sex);
            dao.update(bean);
            request.setAttribute("message", "修改成功");
            request.getRequestDispatcher("servlet?method=list").forward(request, response);
        }
    
        private void list(HttpServletRequest request, HttpServletResponse response) throws Exception {
            // TODO Auto-generated method stub
            request.setCharacterEncoding("utf-8");
            List<Bean> list = dao.list();
            request.setAttribute("list", list);
            request.getRequestDispatcher("list.jsp").forward(request,response);
        }
    
        private void delete(HttpServletRequest request, HttpServletResponse response) throws Exception, IOException {
            // TODO Auto-generated method stub
            request.setCharacterEncoding("UTF-8");
            int id=Integer.parseInt(request.getParameter("id"));
            dao.delete(id); //进行数据库的删除操作
            request.setAttribute("message", "删除成功");
            request.getRequestDispatcher("servlet?method=list").forward(request, response);
        }
    
        private void insert(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
            // TODO Auto-generated method stub
            request.setCharacterEncoding("utf-8");
            int id = Integer.parseInt(request.getParameter("id"));
            String name = request.getParameter("name");
            String password = request.getParameter("password");
            String sex = request.getParameter("sex");
            Bean bean=new Bean(id,name,password,sex);
            if(dao.insert(bean)) {
                request.setAttribute("message", "添加成功");
                request.getRequestDispatcher("index.jsp").forward(request, response);
            }
        }
        
        
    
        /**
         * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
         */
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            // TODO Auto-generated method stub
            request.setCharacterEncoding("utf-8");
            String method=request.getParameter("method");
            if("insert".equals(method)) {
                insert(request,response);
                
            }
            else if("delete".equals(method)) {
                try {
                    delete(request,response);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                
            }
            else if("update".equals(method)) {
                update(request,response);
            }
            else if("list".equals(method)) {
                try {
                    list(request,response);
                } catch (Exception 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);
        }
    
    }
    复制代码

    注意:在创建的时候一定要选择创建servlet而不是类如图:

      

     输入完名字以后点击next选择自己要写的方法:

    jsp页面:

      index.jsp:主页面:

    复制代码
    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>首页</title>
    
    </head>
    <body><% 
    Object message =request.getAttribute("message");
    if(message!=null&&!"".equals(message)){
    %>
        <script type="text/javascript">
        alert("<%=request.getAttribute("message")%>");
        </script>
    <%}%>
    
    
    
        <div align="center">
            <h1>简单的增删改查</h1>
            <div>
                <a href="insert.jsp">添加</a>
            </div>
            <div>
                <a href="servlet?method=list">删除</a>
            </div>
            <div>
                <a href="servlet?method=list">修改</a>
            </div>
            <div>
                <a href="servlet?method=list">查询</a>
            </div>
    
    
        </div>
    </body>
    </html>
    复制代码

    主页面就是一个菜单,至于为什么删除修改查询的链接都是servlet?method=list,那是因为他们都去调用servlet里面的list方法:

    复制代码
        private void list(HttpServletRequest request, HttpServletResponse response) throws Exception {
            // TODO Auto-generated method stub
            request.setCharacterEncoding("utf-8");
            List<Bean> list = dao.list();
            request.setAttribute("list", list);
            request.getRequestDispatcher("list.jsp").forward(request,response);
        }
    复制代码

    先把数据库里所有的信息显示出来,然后在通过request.getRequestDispatcher("list.jsp").forward(request,response);进行跳转,跳转到list.jsp界面,并将之前的所有数据(request,response)一并转发过去

    insert.jsp:

    复制代码
    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>添加</title>
    </head>
    <body>
        <%
            Object message = request.getAttribute("message");
            if (message != null && !"".equals(message)) {
        %>
        <script type="text/javascript">
                  alert("<%=request.getAttribute("message")%>"); //弹出对话框
        </script>
        <%
            }
        %>
        <div align="center">
            <h1>添加信息</h1>
            <a href="index.jsp">返回主页</a>
            <form action="servlet?method=insert" method="post">
            <div>
                id<input type="text" id="id" name="id" />
            </div>
            <div>
                name<input type="text" id="name" name="name" />
            </div>
            <div>
                password<input type="text" id="password" name="password" />
            </div>
            <div>
                sex<input type="radio" id="sex" name="sex" value="男"/>男 <input type="radio"
                    id="sex" name="sex" value="女" />女
            </div>
            <div>
                <button type="submit">添&nbsp;&nbsp;&nbsp;加</button>
            </div>
            </form>
        </div>
    </body>
    </html>
    复制代码

    正常的添加页面。

      list.jsp界面:

    复制代码
    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
       <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    </head>
    <body>
    <%
             Object message = request.getAttribute("message");
             Object grade_list = request.getAttribute("grade_list");
             if(message!=null && !"".equals(message)){
         
        %>
             <script type="text/javascript">
                  alert("<%=request.getAttribute("message")%>");
             </script>
        <%} %>
        <div align="center">
            <h1 >信息列表</h1>
            <a href="index.jsp">返回主页</a>
            <table >
                <tr>
                    <td>id</td>
                    <td>姓名</td>
                    <td>密码</td>
                    <td>性别</td>
                    <td align="center" colspan="2">操作</td>
                </tr>
                <c:forEach items="${list}" var="item">
                    <tr>
                        <td>${item.id}</td>
                        <td>${item.name}</td>
                        <td>${item.password}</td>
                        <td>${item.sex}</td>
                        <td><a href="update.jsp?id=${item.id}&name=${item.name}&password=${item.password}&sex=${item.sex}">修改</a></td>
                        <td><a href="servlet?method=delete&id=${item.id}">删除</a></td>
                    </tr>
                </c:forEach>
            </table>
        </div>
        
    </body>
    </html>
    复制代码

    其中用到了标签库(<c:forEach>),需要导入jstl的包,并且加入其核心依赖,为固定值,如果不了解请点击:https://www.cnblogs.com/tkg1314/p/12008284.html查看jstl标签库。用<c:forEach>来遍历信息,然后每行信息都有删除和修改操作。修改的话跳转到update.jsp并且将id,name,password,sex的值传过去。删除是跳转到servlet的delete方法:

    复制代码
    private void delete(HttpServletRequest request, HttpServletResponse response) throws Exception, IOException {
            // TODO Auto-generated method stub
            request.setCharacterEncoding("UTF-8");
            int id=Integer.parseInt(request.getParameter("id"));
            dao.delete(id); //进行数据库的删除操作
            request.setAttribute("message", "删除成功");
            request.getRequestDispatcher("servlet?method=list").forward(request, response);
        }
    复制代码

    因为delete只需要id所以只需要将id传过去。

    至于每个jsp里面的:

    复制代码
    <%
             Object message = request.getAttribute("message");
             Object grade_list = request.getAttribute("grade_list");
             if(message!=null && !"".equals(message)){
         
        %>
             <script type="text/javascript">
                  alert("<%=request.getAttribute("message")%>");
             </script>
        <%} %>
    复制代码

    是用来获取servlet里面你通过setAttribute方法添加的信息(红色加粗):并且提示出来

    复制代码
        private void insert(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
            // TODO Auto-generated method stub
            request.setCharacterEncoding("utf-8");
            int id = Integer.parseInt(request.getParameter("id"));
            String name = request.getParameter("name");
            String password = request.getParameter("password");
            String sex = request.getParameter("sex");
            Bean bean=new Bean(id,name,password,sex);
            if(dao.insert(bean)) {
                request.setAttribute("message", "添加成功");
                request.getRequestDispatcher("index.jsp").forward(request, response);
            }
        }
    复制代码

    这样便完成了一个简单的java web 数据库的简单增删改查,没有做页面,那个password不是密码,只是一个名字,因此<input>标签没用password类型。

    运行结果:

    主页面:

     添加操作:

     

     添加之前的表数据:

    添加之后

    修改操作:

     

     删除操作:

     

    体会:做了一个简单的增删改查明白了每个类的作用以及联系。bean是用将属性的get,set等方法进行封装。dao层,是对数据库表操作的封装,里面有sql语句的执行等。而DBUtil是对数据库连接和关闭等操作的封装。servlet是跳转,通过调用dao层的方法实现跳转操作。然后jsp页面,有一个主页面 写超链接链接到其他页面。当然你对数据的删改都是在查询的基础上操作的,如果没有显示出信息就不能去删除和修改。当然我把id设为了主键自增,但我没有写验证主键的条件。另外还有什么不对的地方希望大家和老师多多指点!

    转自:https://www.cnblogs.com/tkg1314/p/12014713.html

  • 相关阅读:
    用jquery判断当前显示器的分辨率,加载不同CSS
    [置顶] Android SDK下载和更新失败的解决方法!!!
    [置顶] 最全的Android开发开发资料
    [置顶] Android入门教程导入现有Android工程
    [置顶] 用Android访问本地站点(localhost,10.0.2.2)
    [置顶] Android入门教程Android工程目录结构介绍
    [置顶] 解决Android解析图片的OOM问题
    [置顶] Android入门教程环境搭建
    [置顶] Android 中的拿来主义(编译,反编译,AXMLPrinter2,smali,baksmali)
    Windows 8 平板电脑体验及思考
  • 原文地址:https://www.cnblogs.com/csk001/p/14504502.html
Copyright © 2020-2023  润新知