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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM