JavaWeb案例(MVC+MySQL+分頁功能)+先後端分離

具有的測試工具:Eclipse,MySQL數據庫,HBuilder,jstl1.2jar,mysql.connector.java.8.0.jar

 

jstl1.2jar下載地址:https://pan.baidu.com/s/1T23zxoEg3jlZHFikrbWtHw

 

mysql.connector.java.8.0.jar包下載地址:https://pan.baidu.com/s/1kqfOuxo3nOT--CTrlp1BmA

 

首先打開Eclipse建立一個動態Web項目(Dynamic Web Project),在Src下分別建立如下包javascript

其中web其實就是對應action層,這就是典型的MVC模型,這是屬於後端html

首先建立與你數據庫的表結構對應的實體類java

一、個人數據庫結構以下mysql

創建數據庫
create database LoveDB;web

創建數據表LoveInHeart
use LoveDB;
create table LoveInHeart(
lid int auto_increment primary key,
lname varchar(50) not null,
lsex varchar(50) not null,
ltime date not null,
lmoney float
);ajax

而後能夠向裏面添加一些測試數據sql

insert into LoveInHeart(lname,lsex,ltime,lmoney)
values ('廖遠平','男','1999-02-15',1000000);數據庫

insert into LoveInHeart(lname,lsex,ltime,lmoney)
values ('彭桂妮','女','1998-8-19',1000);後端

insert into LoveInHeart(lname,lsex,ltime,lmoney)
values ('科比','男','2008-05-05',100);api

而後實體類的屬性參數要和數據庫的表結構保持一致,注:實體類是放在entity包下

 聲明變量之後進行封裝,右鍵選擇 source --> Getter and Setter ,而後select All 點擊完成

 接下來建立與數據庫連接的DatabaseConnection類來完成與數據庫的交互,在dao包下新建一個類,名字爲:BaseDB

package com.nf.dao; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class BaseDao { private static final String DRIVER_CLASS = "com.mysql.cj.jdbc.Driver"; private static final String SERVER_IP = "localhost";// 服務器IP地址
    private static final String DATABASE_NAME = "lovedb";// 鏈接到哪個數據庫
    private static final String USER_NAME = "root";// 用戶名
    private static final String PASSWORD = "123456";// 密碼

    public Connection getConnection() { Connection conn = null; String jdbcUrl = "jdbc:mysql://" + SERVER_IP + ":3306/" + DATABASE_NAME + "?serverTimezone=Asia/Shanghai&useSSL=true"; try { Class.forName(DRIVER_CLASS); conn = DriverManager.getConnection(jdbcUrl, USER_NAME, PASSWORD); } catch (Exception e) { System.out.println("獲取鏈接時,異常" + e.getMessage()); conn = null; } return conn; } public void closeAll(Connection conn, PreparedStatement pst, ResultSet rs) { try { if (rs != null) { rs.close(); } if (pst != null) { pst.close(); } if (conn != null) { conn.close(); } } catch (SQLException e) { // TODO Auto-generated catch block
 e.printStackTrace(); } } }

在dao層下面建立一個Interface類,聲明三個方法(查詢、添加、刪除),名字:LoveInHeartDao

package com.nf.dao; import java.util.List; import com.nf.entity.LoveInHeart; import com.nf.util.MyPage; public interface LoveInHeartDao{ public List<LoveInHeart> getAll(MyPage myPage); public boolean add(LoveInHeart love); public boolean delete(int id); }

而後建立一個實現接口class類(Implments),名字:LoveInHeart_Impl

package com.nf.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import com.nf.entity.LoveInHeart; import com.nf.util.MyPage; public class LoveInHeartDaoImpl extends BaseDao implements LoveInHeartDao { @Override //查詢 public List<LoveInHeart> getAll(MyPage myPage) { // 操做數據庫,須要一個鏈接Connection
        Connection connection = getConnection(); PreparedStatement prepareStatement = null; ResultSet resultSet = null; List<LoveInHeart> loveInHeartList = new ArrayList(); String sql_data = "select * from loveinheart order by lid desc "; String sql_recodeCount = "select count(1) as mycount from loveinheart"; sql_data += "limit "; sql_data += (myPage.getCurrentPage()-1)*myPage.getPerPageSize(); sql_data += ","; sql_data += myPage.getPerPageSize(); System.out.println("分頁的SQL:"+sql_data); try { prepareStatement = connection.prepareStatement(sql_data); resultSet = prepareStatement.executeQuery(); while (resultSet.next()) { LoveInHeart l = new LoveInHeart(); l.setLid(resultSet.getInt("lid")); l.setLname(resultSet.getString("lname")); l.setLsex(resultSet.getString("lsex")); l.setLtime(resultSet.getDate("ltime")); l.setLmoney(resultSet.getFloat("lmoney")); loveInHeartList.add(l); } } catch (SQLException e) { e.printStackTrace(); } try { prepareStatement = connection.prepareStatement(sql_recodeCount); resultSet = prepareStatement.executeQuery(); resultSet.next(); myPage.setRecodeCount( resultSet.getInt("mycount") ); } catch (SQLException e) { e.printStackTrace(); } closeAll(connection, prepareStatement, resultSet); // System.out.println(connection);
        return loveInHeartList; } @Override //添加 public boolean add(LoveInHeart love) { // 操做數據庫,須要一個鏈接Connection
        Connection connection = getConnection(); PreparedStatement prepareStatement = null; try { prepareStatement = connection .prepareStatement("insert into LoveInHeart(lname,lsex,ltime,lmoney) values (?,?,?,?)"); prepareStatement.setString(1, love.getLname()); prepareStatement.setString(2, love.getLsex()); prepareStatement.setDate(3, love.getLtime()); prepareStatement.setFloat(4, love.getLmoney()); prepareStatement.executeUpdate(); closeAll(connection, prepareStatement, null); return true; } catch (SQLException e) { e.printStackTrace(); return false; } } @Override //刪除 public boolean delete(int id) { // 操做數據庫,須要一個鏈接Connection
        Connection connection = getConnection(); PreparedStatement prepareStatement = null; try { prepareStatement = connection .prepareStatement("delete from LoveInHeart where lid=?"); prepareStatement.setInt(1, id); prepareStatement.executeUpdate(); closeAll(connection, prepareStatement, null); return true; } catch (SQLException e) { e.printStackTrace(); return false; } } }

接下來在Service層再建立一個interface類,名字:LoveInHeartService

package com.nf.service; import java.util.List; import com.nf.entity.LoveInHeart; import com.nf.entity.MyData; public interface LoveInHeartService { public MyData getAll(int currentPage); public boolean add(LoveInHeart love); public boolean delete(int id); }

隨機在同Service層下實現該接口,實現類名:LoveInHeartServiceImpl,在這裏實現類的方式直接調用dao層的方法就能夠了

package com.nf.service; import java.util.List; import com.nf.dao.LoveInHeartDao; import com.nf.dao.LoveInHeartDaoImpl; import com.nf.entity.LoveInHeart; import com.nf.entity.MyData; import com.nf.util.MyPage; public class LoveInHeartServiceImpl implements LoveInHeartService { private LoveInHeartDao loveDao = new LoveInHeartDaoImpl(); @Override public MyData getAll(int currentPage) { MyPage myPage = new MyPage(); myPage.setCurrentPage(currentPage); //myPage.setRecodeCount( 0 );//讓Dao層來計算
        myPage.setPerPageSize( 10 );//設置每頁10條
 List<LoveInHeart> loveList = loveDao.getAll( myPage ); MyData myData = new MyData(); myData.setLoveInHeartList(loveList); myData.setMyPage(myPage); return myData; } @Override public boolean add(LoveInHeart love) { return loveDao.add(love); } @Override public boolean delete(int id) { // TODO Auto-generated method stub
        return loveDao.delete(id); } }

接下來就是存放Servlet的action層,Servlet名:LoveInHeartActionGetAll(獲取所有信息的Servlet)

package com.nf.web; import java.io.IOException; 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; import com.nf.entity.LoveInHeart; import com.nf.entity.MyData; import com.nf.service.LoveInHeartService; import com.nf.service.LoveInHeartServiceImpl; @WebServlet("/LoveInHeartActionGetAll") public class LoveInHeartActionGetAll extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //第一步:先得到客戶端的參數
        String currentPage_str = request.getParameter("currentPage"); if (currentPage_str==null){ currentPage_str = "1"; } int currentPage = Integer.parseInt(currentPage_str); //第二步:調用Model(service層)的方法,來獲取數據
        LoveInHeartService loveService = new LoveInHeartServiceImpl(); MyData myData = loveService.getAll(currentPage); //第三步:把數據存放到request的屬性中,而後把請求轉發到jsp
        request.setAttribute("myData", myData); request.getRequestDispatcher("showList.jsp").forward(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }

再在同一層下建立添加的Servlet,Servlet名:LoveInHeartActionAdd

package com.nf.web;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;

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.nf.entity.LoveInHeart;
import com.nf.service.LoveInHeartService;
import com.nf.service.LoveInHeartServiceImpl;


@WebServlet("/LoveInHeartActionAdd")
public class LoveInHeartActionAdd extends HttpServlet {
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //獲取參數
        //?lname=123&lsex=男&ltime=111&lmoney=222
        String lname = request.getParameter("lname");
        String lsex = request.getParameter("lsex");
        String ltime = request.getParameter("ltime");
        String lmoney = request.getParameter("lmoney");
        //把參數構形成一個實體類
        LoveInHeart love = new LoveInHeart();
        love.setLname(lname);
        love.setLsex(lsex);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        
        try {
            love.setLtime( new java.sql.Date( sdf.parse(ltime).getTime() ) );
        } catch (ParseException e) {
            System.out.println("日期格式轉換錯誤");
            e.printStackTrace();
        }
        love.setLmoney( Float.parseFloat(lmoney) );
        
        //調用Model,保存數據
        LoveInHeartService loveService = new LoveInHeartServiceImpl();
        boolean flag = loveService.add(love);
        
        //跳轉
        if (flag){
            //response.sendRedirect("showList.jsp");
            response.sendRedirect("LoveInHeartActionGetAll");
            
            
        }else{
            response.sendRedirect("error.jsp");
        }
        
        
    }


    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

}

刪除的Servlet,Servlet名:LoveInHeartActionDelete

package com.nf.web; import java.io.IOException; 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.nf.service.LoveInHeartService; import com.nf.service.LoveInHeartServiceImpl; @WebServlet("/LoveInHeartActionDelete") public class LoveInHeartActionDelete extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //獲取參數
        String id_str = request.getParameter("id"); int id = Integer.parseInt(id_str); //調用model的api
        LoveInHeartService loveService = new LoveInHeartServiceImpl(); boolean flag = loveService.delete(id); if (flag){ response.sendRedirect("LoveInHeartActionGetAll"); }else{ response.sendRedirect("error.jsp"); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }

添加JSP代碼,此網頁只有主體,無其它程序文件之類的引用,JSP名:add.jsp

<form action="LoveInHeartActionAdd">
<table border="1" width="80%" align="center">
    <tr>
        <td colspan="2" align="center">中華慈善捐款等級</td>
    </tr>
    <tr>
        <td width="180px">姓名:</td>
        <td><input type="text" name="lname"></td>
    </tr>
    <tr>
        <td width="180px">性別:</td>
        <td>
            <input type="radio" name="lsex" value="男" checked="checked"></input>
            <input type="radio" name="lsex" value="女"></input>
        </td>
    </tr>
    <tr>
        <td width="180px">捐款日期:</td>
        <td><input type="text" name="ltime">(yyyy年MM月dd日)</td>
    </tr>
    <tr>
        <td width="180px">捐款金額:</td>
        <td><input type="text" name="lmoney">(元)</td>
    </tr>
    <tr>
        <td colspan="2" align="center">
            <input type="submit" value="提交">
            <input type="reset" value="重置">
        </td>
    </tr>
</table>
</form>

首頁的所有代碼,這裏只是用來作一箇中轉站,並不實現什麼功能,因此能夠只保留這一點東西,JSP名:index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><% response.sendRedirect("LoveInHeartActionGetAll"); %>

最重要的展現信息界面,包括了刪除功能,JSP名:showList.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 PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>展現全部信息</title>
</head>
<script type="text/javascript">
function mydelete(id){ alert(id); //ajax();
} </script>
<body> 總紀錄條數:${myData.myPage.recodeCount}, 每頁大小:${myData.myPage.perPageSize }, 一共${myData.myPage.pageCount}頁 <br><br>
<c:forEach begin="${myData.myPage.pageBegin}" end="${myData.myPage.pageEnd}" varStatus="sta">
    <a href="LoveInHeartActionGetAll?currentPage=${sta.index}">第${sta.index}頁</a>
</c:forEach>


<table align="center" border="1" >
    <tr>
        <td colspan="6" align="right"> ---中華愛心捐款查詢系統<a href="add.jsp">添加新捐款</a></span>
        </td>
    </tr>
    
    <tr>
        <td>編號</td>
        <td>姓名</td>
        <td>性別</td>
        <td>捐款金額</td>
        <td>捐款時間</td>
        <td>操做</td>
    </tr>

<c:forEach items="${myData.loveInHeartList}" var="love">
    <tr>
        <td>${love.lid}</td>
        <td>${love.lname}</td>
        <td>${love.lsex}</td>
        <td>${love.lmoney}</td>
        <td>${love.ltime}</td>
        <td>
            <a href="LoveInHeartActionDelete?id=${love.lid}">刪除</a>&nbsp;
            <a href="javascript:mydelete(${love.lid})">無刷新刪除1</a>&nbsp;
            <button onclick="mydelete(${love.lid})">無刷新刪除2</button>
        </td>
    </tr>
</c:forEach>

</table>


<c:forEach begin="${myData.myPage.pageBegin}" end="${myData.myPage.pageEnd}" varStatus="sta">
    <a href="LoveInHeartActionGetAll?currentPage=${sta.index}">第${sta.index}頁</a>
</c:forEach>


</body>
</html>

 最終結果圖以下:

有許多不足還請各位大佬指教,謝謝

相關文章
相關標籤/搜索