具备的测试工具: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下分别创建以下包

java 前后端分离 后端如何测试 javaweb前后端分离实例_Mybatis

其中web其实就是对应action层,这就是典型的MVC模型,这是属于后端

首先创建与你数据库的表结构对应的实体类

1、我的数据库结构如下

建立数据库
create database LoveDB;

建立数据表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
);

然后可以向里面添加一些测试数据

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);

然后实体类的属性参数要和数据库的表结构保持一致,注:实体类是放在entity包下

java 前后端分离 后端如何测试 javaweb前后端分离实例_java 前后端分离 后端如何测试_02

 声明变量以后进行封装,右键选择 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=男<ime=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> 
            <a href="javascript:mydelete(${love.lid})">无刷新删除1</a> 
            <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>

 最终结果图如下:

java 前后端分离 后端如何测试 javaweb前后端分离实例_sql_03