Java后台+数据库+Java web前端——记账本

下面是本人实现的网页版(设计思路见上一篇https://www.cnblogs.com/sengzhao666/p/10445984.html

源码下载:https://github.com/yishengxiaobai/JiZhangBen

代码如下:

 

 

 

运行截图:

首页:

 

 创建:

账本删除:(先查找后删除)

 

 

查阅账本:

 

 

 

实体entity层:

package entity;

public class Account {
    private String name;
    private String amount;
    private String time;
    private String money;
    public void setName(String name) {
        this.name=name;
    }
    public String getName() {
        return name;
    }
    public void setAmount(String a) {
        amount=a;
    }
    public String getAmount() {
        return amount;
    }
    public void setTime(String b) {
        time=b;
    }
    public String getTime() {
        return time;
    }
    public void setMoney(String c) {
        money=c;
    }
    public String getMoney() {
        return money;
    }
    public Account() {
    }
    public Account(String a,String b,String c,String d) {
        name=a;
        amount=b;
        money=c;
        time=d;
    }
}

 数据库util层:

package util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class Shujuku {
     public static Connection conn(){
         String url="jdbc:sqlserver://localhost:1433;DatabaseName=account";//填写你的数据库名
         String userName="sa";//填写你的用户名,我的是sa
         String userPwd="tzk19991029";//填写你的密码tzk19991029
         Connection connection=null;

  try{
      Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
      System.out.println("加载驱动成功!");

  }catch(Exception e){

           e.printStackTrace();

           System.out.println("加载驱动失败!");
   }
 try{
    connection=DriverManager.getConnection(url,userName,userPwd);
 System.out.println("连接数据库成功!");
 }catch(Exception e){
        e.printStackTrace();
        System.out.print("SQL Server连接失败!");
  }    
 return connection;
}
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();
        }
    }
}

}

 

servlet层:

package servlet;

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 entity.Account;
import service.Service;

/**
 * Servlet implementation class AccountServlet
 */
@WebServlet("/AccountServlet")
public class AccountServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    Service service=new Service();
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // TODO Auto-generated method stub
        req.setCharacterEncoding("utf-8");
        String method = req.getParameter("method");
        if(method.equals("add"))
        {
            add(req,resp);
        }else if(method.equals("delete")) {
            delete(req,resp);
        }else if(method.equals("update")) {
            update(req,resp);
        }else if(method.equals("list")) {
            list(req,resp);
        }else if(method.equals("getByname")) {
            getByname(req,resp);
        }else if(method.equals("show")) {
            show(req,resp);
        }
        else if(method.equals("getByname2")) {
            getByname2(req,resp);
        }
    }
    private void show(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        List<Account> accounts = service.list();
        req.setAttribute("accounts", accounts);
        req.getRequestDispatcher("show.jsp").forward(req,resp);
    }
    private void add(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String a = req.getParameter("name");
        String b = req.getParameter("amount");
        String c = req.getParameter("money");
        String d=req.getParameter("time");
        Account account=new Account(a,b,c,d);
        int k=service.add(account);
        if(k==2) {
            req.setAttribute("message", "添加成功");//setAttribute方法用于将内容保存在对象中,传到add.jsp中
            req.getRequestDispatcher("add.jsp").forward(req,resp);//getRequestDispatcher方法用于进入下一个页面
        } 
        if(k==0)
        {
            req.setAttribute("message", "重复,请重新录入");
            req.getRequestDispatcher("add.jsp").forward(req,resp);
        }
        if(k==1)
        {
            req.setAttribute("message", "数据库添加失败");
            req.getRequestDispatcher("add.jsp").forward(req,resp);
        }
    }
    private void delete(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String name = req.getParameter("name");
        int k=service.delete(name);
        if(k==0) {
            req.setAttribute("message", "删除失败");
             req.getRequestDispatcher("deleteByname.jsp").forward(req,resp);
        }
        if(k==1) {
            req.setAttribute("message", "删除成功");
             req.getRequestDispatcher("index.jsp").forward(req,resp);
        }
       
    }
    private void update(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {
        // 修改
        req.setCharacterEncoding("utf-8");
        String a = req.getParameter("name");
        String b = req.getParameter("amount");
        String c = req.getParameter("money");
        String d=req.getParameter("time");
        Account account=new Account(a,b,c,d);
        int k=service.update(account);
        if(k==1) {
        req.setAttribute("message", "修改成功");
        req.getRequestDispatcher("AccountServlet?method=show").forward(req,resp);
        }else {
            req.setAttribute("message", "修改失败");
            req.getRequestDispatcher("show.jsp").forward(req,resp);
        }
    }

    private void getByname(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException{
        //按照名字删除
        req.setCharacterEncoding("utf-8");
        String name = req.getParameter("name");
        Account account=service.getByname(name);
        if(account==null) {
            req.setAttribute("message", "查询不到,请重新选择");
            req.getRequestDispatcher("deleteByname.jsp").forward(req,resp);
        }else {
            req.setAttribute("account", account);
            req.getRequestDispatcher("delete.jsp").forward(req,resp);
        }
    }
    
    private void getByname2(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException{
        //通过名字修改
        req.setCharacterEncoding("utf-8");
        String name = req.getParameter("name");
        Account account=service.getByname2(name);
        req.setAttribute("account", account);
        req.getRequestDispatcher("update.jsp").forward(req,resp);
    }
    private void list(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException{
        req.setCharacterEncoding("utf-8");
        List<Account> accounts = service.list();
        req.setAttribute("accounts", accounts);
        req.getRequestDispatcher("list.jsp").forward(req,resp);
    }

}

 service层:

package service;

import java.util.List;

import dao.Dao;
import entity.Account;


public class Service {
    Dao dao=new Dao();

    public List<Account> show(String name) {
        return dao.show(name);
    }

    public int update(Account account) {
        int f=0;
        if(dao.update(account)) {
            f=1;
        }
        return f;
    }

     public int delete(String name) {
            int f=0;
            if(dao.delete(name)) {
                f=1;
            }
            return f;
        }

    public int add(Account account) {
        int f=0;
        if(!dao.rename(account.getName())) {
            f=1;
            if(dao.add(account))
            f=2;
        }
        return f;    
    }


    public Account getByname(String name) {
        return dao.getByname(name);
    }

    public List<Account> list() {
        // TODO 自动生成的方法存根
        return dao.list();
    }

    public Account getByname2(String name) {
        // TODO 自动生成的方法存根
        return dao.getByname2(name);
    }

}

 dao层:

package dao;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;


import entity.Account;
import util.Shujuku;

public class Dao {
    public boolean rename(String name) {
        // 检验名字是否重复
        boolean f=false;
        String sql="select name from account where name='"+name+"'";//数据库语句,查询界面输入和表中name是否重复
        Connection conn = Shujuku.conn();//创建连接
        Statement state = null;//建立Statement对象,执行静态SQL语句
        ResultSet rs = null;//ResultSet对象 是查询数据库时的返回对象,读取返回结果集
        
        try {
            state = conn.createStatement();
            rs = state.executeQuery(sql);
            while (rs.next()) {//不重复,返回true
                f = true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            Shujuku.close(rs, state, conn);
        }
        return f;
    }

    public boolean add(Account account) {
        //添加
        String sql = "insert into account(name,amount,money,time) values('" +account.getName() + "','" + account.getAmount() + "','" + account.getMoney() + "','" +account.getTime() + "')";//添加
        Connection conn = Shujuku.conn();
        Statement state = null;
        boolean f = false;
        int a=0;
        try {
            state = conn.createStatement();
            a=state.executeUpdate(sql);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            Shujuku.close(state, conn);
        }
        if (a > 0) {
            f = true;
        }
        return f;
    }

    
    public boolean delete(String name) {
        // 通过名字删除
        boolean f=false;
        String sql = "delete from account where name ='" + name + "'";//删除
        Connection conn = Shujuku.conn();
        Statement state = null;
        int a=0;
        try {
            state = conn.createStatement();
            a=state.executeUpdate(sql);
        }catch (Exception e) {
            e.printStackTrace();
        } finally {
            Shujuku.close(state, conn);
        }
        if(a>0) {
            f=true;
        }
        return f;
    }
    public boolean update(Account account) {
        // 修改
        String sql = "update account set amount='" + account.getAmount() + "', money='" + account.getMoney()+"',time='" + account.getTime()+"'where name='"+account.getName()+"'";
    Connection conn = Shujuku.conn();
    Statement state = null;
    boolean f = false;
    int a = 0;

    try {
        state = conn.createStatement();
        a = state.executeUpdate(sql);
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        Shujuku.close(state, conn);
    }
    
    if (a > 0) {
        f = true;
    }
    return f;
        
    }
    public List<Account> show(String name) {
        // 列出数据
        String sql = "select * from account";
        Connection conn = Shujuku.conn();
        Statement state = null;
        ResultSet rs = null;
        List<Account> list = new ArrayList<>();
        try {
            state = conn.createStatement();
            rs = state.executeQuery(sql);
            Account bean = null;
            while (rs.next()) {
                
                String a = rs.getString("name");
                String b = rs.getString("amount");
                String c= rs.getString("money");
                String d= rs.getString("time");
                 bean= new Account( a,b,c,d);
                 list.add(bean);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            Shujuku.close(rs, state, conn);
        }
        
        return list;
    }
    
    public Account getByname(String name) {
        //通过名字得到
        //模糊查询
        String sql = "select * from account where ";
        if (name != "") {
            sql += "name like '%" + name + "%'";
        }
        Connection conn = Shujuku.conn();
        Statement state = null;
        ResultSet rs = null;
        Account account = null;
        try {
            state = conn.createStatement();
            rs = state.executeQuery(sql);
            while (rs.next()) {
                String d=rs.getString("name");
                String a = rs.getString("amount");
                String b=rs.getString("money");
                String c=rs.getString("time");
                account = new Account(d,a,b,c);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            Shujuku.close(rs, state, conn);
        }
        
        return account;
    }

    public List<Account> list() {
        String sql = "select * from account";
        List<Account> list = new ArrayList<>();
        Connection conn = Shujuku.conn();
        Statement state = null;
        ResultSet rs = null;

        try {
            state = conn.createStatement();
            rs = state.executeQuery(sql);
            Account bean = null;
            while (rs.next()) {
                
                String a = rs.getString("name");
                String b = rs.getString("amount");
                String c = rs.getString("money");
                String d = rs.getString("time");
                bean = new Account(a,b,c,d);
                list.add(bean);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            Shujuku.close(rs, state, conn);
        }
        
        return list;
    }

    public Account getByname2(String name) {
        String sql = "select * from account where ";
        if (name != "") {
            sql += "name like '%" + name + "%'";
        }
        Connection conn = Shujuku.conn();
        Statement state = null;
        ResultSet rs = null;
        Account account = null;
        try {
            state = conn.createStatement();
            rs = state.executeQuery(sql);
            while (rs.next()) {
                String d=rs.getString("name");
                String a = rs.getString("amount");
                String b=rs.getString("money");
                String c=rs.getString("time");
                account = new Account(d,a,b,c);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            Shujuku.close(rs, state, conn);
        }
        
        return account;
    }
}

 index.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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>
<style >
.a{
        font-size: 26px;
        margin-top: 20px;
    }
</style>
</head>
<body>
<div align="center">
<h1 style="color: red;">家庭记账本</h1>
        <div class="a">
            <a href="add.jsp">创建账本</a>
        </div>
        <div class="a">
            <a href="deleteByname.jsp">账本删除</a>
        </div>
        <div class="a">
            <a href="AccountServlet?method=list">查阅账本</a>
        </div>
</div>
</body>
</html>

 add.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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>Insert title here</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 style="color: red;">信息录入</h1>
        <a href="index.jsp">返回主页</a>
        <form action="AccountServlet?method=add" method="post" onsubmit="return check()">
            <div >
                名称<input type="text" id="name" name="name"/>
            </div>
            <div >
                数量<input type="text" id="amount" name="amount" />
            </div>
            <div >
                消费<input type="text" id="money" name="money" />
            </div>
            <div >
                时间<input type="text" id="time" name="time" />
            </div>
            <div >
                <button type="submit" >保&nbsp;&nbsp;&nbsp;存</button>
            </div>
        </form>
    </div>
    <script type="text/javascript">
        function check() {
            var a = document.getElementById("name");
            var b= document.getElementById("amount");
            var c = document.getElementById("money");
            //非空
            if(a.value == '') {
                alert('名称为空');
                a.focus();
                return false;
            }
            if(b.value == '') {
                alert('数量为空');
                b.focus();
                return false;
            }
            if(c.value == '') {
                alert('消费为空');
                c.focus();
                return false;
            }
        }
    </script>
</body>
</html>

deleteByname.jsp: 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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>
<body>
<%
         Object message = request.getAttribute("message");
         if(message!=null && !"".equals(message)){
     
%>
 <script type="text/javascript">
              alert("<%=request.getAttribute("message")%>");
         </script>
<%} %>
<div align="center">
<h1 style="color: red;"> 查找 </h1>
        <a href="index.jsp">返回主页</a>
        <form action="AccountServlet?method=getByname" method="post" onsubmit="return check()">
        <div >
                名字<input type="text" id="name" name="name"/>
            </div>
            <div >
                <button type="submit" >&nbsp;&nbsp;&nbsp;</button>
            </div>
        </form>
    </div>
    <script type="text/javascript">
        function check() {
            var name = document.getElementById("name");
            
            //非空
            if(name.value == '') {
                alert('名称为空');
                name.focus();
                return false;
            }
        }
    </script>
</body>
</html>

 

delete.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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>
<style>
    .a{
        margin-top: 20px;
    }
    .b{
        font-size: 20px;
        width: 160px;
        color: white;
        background-color: greenyellow;
    }
    .tb, td {
        border: 1px solid black;
        font-size: 22px;
    }
</style>
</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 style="color: red;">账本删除</h1>
        <a href="index.jsp">返回主页</a>
        <table class="tb">
            <tr>
                <td>姓名</td>
                <td>${account.name}</td>
            </tr>
            <tr>
                <td>数量</td>
                <td>${account.amount}</td>
            </tr>
            <tr>
                <td>消费</td>
                <td>${account.money}</td>
            </tr>
            <tr>
                <td>时间</td>
                <td>${account.time}</td>
            </tr>
        </table>
        <div >
            <a onclick="return check()" href="AccountServlet?method=delete&name=${account.name}">&nbsp;&nbsp;&nbsp;</a>
        </div>
    </div>
    <script type="text/javascript">
        function check() {
            if (confirm("真的要删除吗?")){
                return true;
            }else{
                return false;
            }
        }
    </script>
</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 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>Insert title here</title>
<style>
    .a{
        margin-top: 20px;
    }
    .b{
        font-size: 20px;
        width: 160px;
        color: white;
        background-color: greenyellow;
    }
    .tb, td {
        border: 1px solid black;
        font-size: 22px;
    }
</style>
</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 style="color: red;">账单列表</h1>
        <a href="index.jsp">返回主页</a>
        <table class="tb">
            <tr>
                <td>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td>
                <td>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td>
                <td>消费总额</td>
                <td>消费时间</td>
                <td align="center" colspan="2">操作</td>
            </tr>
            <c:forEach items="${accounts}" var="item">
                <tr>
                    <td>${item.name}</td>
                    <td>${item.amount}</td>
                    <td>${item.money}</td>
                    <td>${item.time}</td>
                    <td><a href="AccountServlet?method=getByname2&name=${item.name}">修改</a></td>
                    <td><a href="AccountServlet?method=getByname&name=${item.name}">删除</a></td>
                </tr>
            </c:forEach>
        </table>
    </div>
</body>
</html>

 

update.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style>
    .a{
        margin-top: 20px;
    }
    .b{
        font-size: 20px;
        width: 160px;
        color: white;
        background-color: greenyellow;
    }
</style>
</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 style="color: red;">信息修改</h1>
        <a href="index.jsp">返回主页</a>
        <form action="AccountServlet?method=update" method="post" onsubmit="return check()">
            <div class="a">
                名称<input type="text"  name="name" value="${account.name}"/>
            </div>
            <div class="a">
                数量<input type="text" id="amount" name="amount" value="${account.amount}"/>
            </div>
            <div class="a">
                消费<input type="text" id="money" name="money" value="${account.money}"/>
            </div>
            <div class="a">
                时间<input type="text"  name="time" value="${account.time}"/>
            </div>
            <div class="a">
                <button type="submit" class="b">&nbsp;&nbsp;&nbsp;</button>
            </div>
        </form>
    </div>
    <script type="text/javascript">
        function check() {
            var b = document.getElementById("amount");
            var c = document.getElementById("money");
            
            //非空
            
            if(b.value == '') {
                alert('数量为空');
                b.focus();
                return false;
            }
            if(c.value == '') {
                alert('消费为空');
                c.focus();
                return false;
            }
        }
    </script>
</body>
</html>

 

show.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>
<style>
    .a{
        margin-top: 20px;
    }
    .b{
        font-size: 20px;
        width: 160px;
        color: white;
        background-color: greenyellow;
    }
    .tb, td {
        border: 1px solid black;
        font-size: 22px;
    }
</style>
</head>
<body>
    <div align="center">
        <h1 style="color: red;">信息列表</h1>
        <a href="index.jsp">返回主页</a>
        <table class="tb">
            <tr>
                
                <td>名称</td>
                <td>数量</td>
                <td>消费</td>
                <td>时间</td>
            </tr>
            <!-- forEach遍历出adminBeans -->
            <c:forEach items="${accounts}" var="item" varStatus="status">
                <tr>
                    <td>${item.name}</td>
                    <td><a>${item.amount}</a></td>
                    <td>${item.money}</td>
                    <td>${item.time}</td>
                </tr>
            </c:forEach>
        </table>
    </div>
</body>
</html>
posted @ 2019-02-28 12:20  田智凯  阅读(9716)  评论(4编辑  收藏  举报