家庭记账本小程序开发第一天

刚学微信开发的小白,写的代码不是很好,各位大佬多指教,嘿嘿嘿。

下面是记账本的页面,使用的工具是:

微信开发者工具

eclipse

 

 

 进入记账页面输入信息,点击确认按钮即可记账成功

                                       

 

 

点击查看账单页面可以查看历史账单:

 

 

 

 

 连接了后台数据库:

 

 

下面是代码实现部分:

 

benn分为user和tally

tally:

package bean;

public class tally {
    private int id;
    private String date;
    private String money;
    private String type;
    private String style;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getDate() {
        return date;
    }
    public void setDate(String date) {
        this.date = date;
    }
    public String getMoney() {
        return money;
    }
    public void setMoney(String money) {
        this.money = money;
    }
    public String getType() {
        return type;
    }
    public void setType(String type) {
        this.type = type;
    }
    public String getStyle() {
        return style;
    }
    public void setStyle(String style) {
        this.style = style;
    }

}

user:

package bean;

public class user {
private int id;
private String name;
private String password;
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;
}

}

dao层:

显示账单:

package dao;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.mysql.jdbc.PreparedStatement;
import com.mysql.jdbc.ResultSet;
import com.mysql.jdbc.Statement;
import bean.tally;
import util.DBUtil;
public class showdao {
    public List<tally> select(){
        Connection conn = DBUtil.getConn(); //连接数据库
        List<tally> list = new ArrayList<tally>();
        try {
            String sql="select * from tally";
            Statement pstmt = (Statement) conn.createStatement();
            ResultSet rs = (ResultSet) pstmt.executeQuery(sql);
            while(rs.next()) {
                tally tally=new tally();
                tally.setDate(rs.getString("date"));
                tally.setMoney(rs.getString("money"));
                tally.setType(rs.getString("type"));
                tally.setStyle(rs.getString("style"));
                list.add(tally);
            }
            System.out.println("showdao运行成功");
            rs.close();
            pstmt.close();
            conn.close();

        }catch(SQLException e) {
            e.printStackTrace();
        }
        return list;
    }
}

记账:

package dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import bean.tally;
import util.DBUtil;
public class tallydao {
    /**
     * 用户记账
     * @param tally
     * @return
     */
    public boolean tally(tally tally) {
        String sql = "insert into tally(date,money,type,style) values(?,?,?,?)";
        Connection conn = DBUtil.getConn(); //连接数据库
        PreparedStatement pstmt = null;
        int count = 0;
        try {
            pstmt = conn.prepareStatement(sql);//用于将 SQL 语句发送到数据库中。
            pstmt.setString(1,tally.getDate());//1代表第一列
            pstmt.setString(2,tally.getMoney());
            pstmt.setString(3,tally.getType());
            pstmt.setString(4,tally.getStyle());
            count = pstmt.executeUpdate();//返回的是受影响的行数(即更新的行数)
        } catch (SQLException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        }
        if(count>0) {
            return true;
        }
        return false;
    }
}

service层:

显示账单:

package service;
import java.util.List;
import dao.showdao;
import bean.tally;
public class showservice {
    private showdao sd=new showdao();
    public List<tally> list() {
        return sd.select();
    }
}

记账:

package service;
import dao.tallydao;
import bean.tally;
import bean.user;
public class tallyservice {
tallydao dao = new tallydao();
/**
 * 用于用户记账
 * @param tally
 * @return
 */
public boolean tally(tally tally) {
    boolean tallySuccess = false;
    
    tallySuccess = dao.tally(tally);//判断是否存入数据库成功
    
    return tallySuccess;
}
}

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 bean.tally;
import dao.showdao;

/**
 * Servlet implementation class showservlet
 */
@WebServlet("/showservlet")
public class showservlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public showservlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        showdao sd = new showdao();
        List<tally> list = sd.select();
        request.setAttribute("list", list);
        System.out.println("showservlet运行");
        request.getRequestDispatcher("show.jsp").forward(request, response);
    }

    /**
     * @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);
    }

记账:

package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import bean.user;

import java.io.IOException;
import javax.servlet.annotation.WebServlet;

import util.DBUtil;
import dao.tallydao;
import service.tallyservice;
import bean.tally;

/**
 * Servlet implementation class tallyservlet
 */
@WebServlet("/tallyservlet")
public class tallyservlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
       private tallyservice Ser=new tallyservice();
    /**
     * @see HttpServlet#HttpServlet()
     */
    public tallyservlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String date = request.getParameter("date");     //getParameter()获取的是客户端设置的数据。
        String money = request.getParameter("money");
        String type = request.getParameter("type");
        String style = request.getParameter("style");
//        String sql = "select name from tally where ";
//        if (name != "") {
//            sql += "name like '%" + name + "%'";
//        }
//        
//        Connection conn = DBUtil.getConn();
//        Statement state = null;
//        ResultSet rs = null;
//        try {
//            state = conn.createStatement();
//            rs = state.executeQuery(sql);//executeQuery()返回包含给定查询所生成数据的 ResultSet 对象,如果没有查询到信息,返回一个next()为false的ResultSet 对象
//            if(rs.next()==false) {
                //name = rs.getString("name");

                tally tally = new tally();
                tally.setDate(date);
                tally.setMoney(money);
                tally.setType(type);
                tally.setStyle(style);
                response.setCharacterEncoding("gbk");
                PrintWriter out = response.getWriter();
//                System.out.println(" "+user.getName()+" "+user.getPassword());
                if(Ser.tally(tally)) {
                    out.println("<script> alert('添加成功!'); window.location.href='index.jsp'; </script>");
                    
                }else {
                    out.println("<script> alert('添加失败!'); window.location.href='tally.jsp'; </script>");
                }
                out.println("</HTML>");
                out.flush();     //out.flush()表示强制将缓冲区中的数据发送出去,不必等到缓冲区满
                out.close();     
        
//            }
//            else {
//                response.setCharacterEncoding("gbk");
//                PrintWriter out = response.getWriter();
//                out.println("<script> alert('该用户已存在,添加失败!'); window.location.href='register.jsp'; </script>");
//                out.println("</HTML>");
//                out.flush();     //out.flush()表示强制将缓冲区中的数据发送出去,不必等到缓冲区满
//                out.close();     
//            }
//    } 
//                catch (SQLException e) {
//            e.printStackTrace();
//        } finally {
//            DBUtil.close(rs, state, conn);
//        }

        }

    /**
     * @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);
    }

}

连接微信前端的:

显示账单:

package controller;

import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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.google.gson.Gson;

import bean.tally;
import dao.showdao;

/**
 * Servlet implementation class WXServletShow
 */
@WebServlet("/WXServletShow")
public class WXServletShow extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public WXServletShow() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置请求编码
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        /* 设置响应头允许ajax跨域访问 */
        response.setHeader("Access-Control-Allow-Origin", "*");
        /* 星号表示所有的异域请求都可以接受, */
        response.setHeader("Access-Control-Allow-Methods", "GET,POST");
        showdao sd = new showdao();
        List<tally> list = sd.select();
       
        //获取微信小程序get的参数值并打印
        //转成json数据
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("data", list);
        result.put("msg", "后台已收到");
        //使用Gson类需要导入gson-2.8.0.jar
        String json = new Gson().toJson(result);

        //返回值给微信小程序
        Writer out = response.getWriter();
        out.write(json);
        out.flush();
    }

    /**
     * @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);
    }

}

记账:

package controller;

import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

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 org.apache.tomcat.jni.User;

import com.google.gson.Gson;

import bean.tally;
import dao.tallydao;
import service.tallyservice;

/**
 * Servlet implementation class WXServletTally
 */
@WebServlet("/WXServletTally")
public class WXServletTally extends HttpServlet {
    private static final long serialVersionUID = 1L;
//       用于记账
    private tallyservice Ser=new tallyservice();
    /**
     * @see HttpServlet#HttpServlet()
     */
    public WXServletTally() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置请求编码
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        /* 设置响应头允许ajax跨域访问 */
        response.setHeader("Access-Control-Allow-Origin", "*");
        /* 星号表示所有的异域请求都可以接受, */
        response.setHeader("Access-Control-Allow-Methods", "GET,POST");

        tally tally = new tally();
        //获取微信小程序get的参数值并打印
        tally.setDate(request.getParameter("date"));
        tally.setMoney(request.getParameter("money"));
        tally.setType(request.getParameter("type"));
        tally.setStyle(request.getParameter("style"));
        System.out.println("date="+tally.getDate()+" ,money="+tally.getMoney()+",type="+tally.getType()+",style="+tally.getStyle());
        //转成json数据
        Map<String, Object> result = new HashMap<String, Object>();
        if(Ser.tally(tally)) {
        result.put("data", tally);
        result.put("msg", "后台已收到");
        }else {
            result.put("data", tally);
            result.put("msg", "后台没有收到");
        }
        
        //使用Gson类需要导入gson-2.8.0.jar
        String json = new Gson().toJson(result);

        //返回值给微信小程序
        Writer out = response.getWriter();
        out.write(json);
        out.flush();
    }

    /**
     * @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);
    }

}

util层:

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

/**
 * @author 信1805-2 刘子煜 20183542 
 * 2020年2月3日
 *连接数据库操作
 */
public class DBUtil {
    
    public static String db_url = "jdbc:mysql://localhost:3306/Tally";
    public static String db_user = "root";
    public static String db_pass = "101032";
    
    public static Connection getConn () {
        Connection conn = null;
        
        
        try {
            //加载驱动
            Class.forName("com.mysql.jdbc.Driver");
            //获取连接
            conn = DriverManager.getConnection(db_url, db_user, db_pass);
            System.out.println("连接成功!");
            
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return conn;
    }
    public static void main(String[] args) {
        getConn();
    }
    
    /**
     * @param state
     * @param conn
     */
    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();
            }
        }
    }

}

接下来是前端的部分:

记账的:

js文件:

// pages/A/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    date:'',
    money:'',
    type:'',
    style:'',
    error:'',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  // tally: function(){
  //   console.log(this.data);


  // },
  tally: function () {
    // 判断是否为空
    if(!this.data.date){
      this.setData({
        error:"日期不能为空"
      });
      return;
    }
    if (!this.data.money) {
      this.setData({
        error: "金额不能为空"
      });
      return;
    }
    if (!this.data.type) {
      this.setData({
        error: "类型不能为空"
      });
      return;
    }
    if (!this.data.style) {
      this.setData({
        error: "说明不能为空"
      });
      return;
    }
    var that=this;
    wx.request({
      url: 'http://localhost:8080/Tally/WXServletTally',
      data: {
        date: this.data.date,
        money: this.data.money,
        type: this.data.type,
        style: this.data.style
      },
      method: 'POST',
      header: {
        //'content-type': 'application/json' // 默认值
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        console.log(res.data);
        wx.showToast({
          title: '记账成功!',
        })
        // 在一开始用户记账失败产生错误信息后,再次记账成功的话,置错误信息为空
        that.setData({
          error:""
        })
      },
      fail: function (res) {
        console.log(".....fail.....");
        that.setData({
          error:res.data.msg
        });
      }
    })
  },
  inputChange: function(e){
   var prop = e.currentTarget.dataset.type;
    this.data[prop] = e.detail.value;
    // console.log(this.date[prop]);
    // this.setData({
    //   "date": e.detail.value
    // });


  }
})

wxml文件:

<!--pages/A/index.wxml-->
<view class="container">
<input data-type='date' bindinput="inputChange" value="{{date}}" class="textbox" placeholder="请输入日期"></input>
<input data-type='money' bindinput="inputChange" value="{{money}}" class="textbox" placeholder="请输入记账金额"></input>
<input data-type='type' bindinput="inputChange" value="{{type}}" class="textbox" placeholder="请输入类型"></input>
<input data-type='style' bindinput="inputChange" value="{{style}}" class="textbox" placeholder="请输入说明"></input>
<button type="primary" bindtap="tally">确定</button>
<text style="color:red;">{{error}}</text>
</view>

显示账单的:

js文件:

// pages/B/index.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    date:'',
    money:'',
    type:'',
    style:'',
    ty:[[],[]],

  },
  show: function () {
    var that=this;
    wx.request({
      url: 'http://localhost:8080/Tally/WXServletShow',
      data: {
        username: '刘子煜',
        password: '123'
      },
      method: 'POST',
      header: {
        //'content-type': 'application/json' // 默认值
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        console.log(res.data);
        var ty1 = res.data.data;
        that.setData({
          ty:ty1 

        });
        // console.log(ty[0].date);
      },
      fail: function (res) {
        console.log(".....fail.....");
      }
    })
  },
  onLoad: function (option) {
    console.log(option.query)
    const eventChannel = this.getOpenerEventChannel()
    eventChannel.emit('acceptDataFromOpenedPage', { data: 'test' });
    eventChannel.emit('someEvent', { data: 'test' });
    // 监听acceptDataFromOpenerPage事件,获取上一页面通过eventChannel传送到当前页面的数据
    eventChannel.on('acceptDataFromOpenerPage', function (data) {
      console.log(data)
    })
  }
})

wxml文件:

<!--pages/B/index.wxml-->
<view class="container">
  <button bindtap='show'>查看账单</button>
  <!-- <view wx:for="{{[1, 2, 3, 4, 5, 6, 7, 8, 9]}}" wx:for-item="i">
      {{i}} * {{10}} = {{i * 10}}
</view> -->
<view class='tallying'>
<view class='date'>日期</view>
<view class='money'>金额</view>
<view class='type'>类型</view>
<view class='style'>说明</view>
</view>
<view wx:for="{{ty}}" class="ty">
<view class="date1">{{item.date}}</view>
<view class="money1">{{item.money}}</view>
<view class="type1">{{item.type}}</view>
<view class="style1">{{item.style}}</view>
</view>
</view>

wxss文件:

/* pages/B/index.wxss */
.container{
  display: flex;
  flex-direction: column;
}
.tallying{
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: row;
  justify-content: space-around;
  /* align-content: space-around; */
  margin-top: 50rpx;
}
.date{
  background-color: #ccc
}
.money{
  background-color: #ccc
}
.type{
  background-color: #ccc
}
.style{
  background-color: #ccc
}
.ty{
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: row;
  /* justify-content: space-around; */
  /* align-content: space-around; */
  margin-top: 50rpx;
  border-style: solid;
  border-color: pink
}
.date1{
  /* margin-left: 5rpx; */
  width: 50rpx;
  justify-content: flex-start;
  /* border-style: solid */
}
.money1{
  width: 50rpx;
  margin-left: 200rpx;
  justify-content: flex-start
}
.type1{
  width: 50rpx;
  margin-left: 100rpx;
  justify-content: flex-start;
}
.style1{
  width: 50rpx;
  margin-left: 180rpx;
  justify-content: flex-start;
}

app.json文件:

{
  "pages": [
    "pages/index/index",
    "pages/B/index",
    "pages/A/index",
    "utils/util"
  ],
  "window": {
    "backgroundTextStyle": "light",
    "navigationBarBackgroundColor": "#fff",
    "navigationBarTitleText": "家庭记账本",
    "navigationBarTextStyle": "black"
  },
  "style": "v2",
  "sitemapLocation": "sitemap.json"
}

 

由于是刚学习开发微信小程序,只是做了部分功能上的实现,页面的布局和组件的使用没有太多,等今后学习的更深在完善这个小程序吧!!!

 

posted @ 2020-02-06 19:10  ziyuliu  阅读(358)  评论(0编辑  收藏  举报