• 家庭记账本小程序之后台java代码部分(java web基础版二)


    1.数据库连接类

     1 package com.wang.utils;
     2 
     3 import java.sql.Connection;
     4 import java.sql.DriverManager;
     5 import java.sql.ResultSet;
     6 import java.sql.SQLException;
     7 import java.sql.Statement;
     8 
     9 public class DBUtils {
    10                                                               //数据库名
    11     public static String db_url = "jdbc:mysql://localhost:3306/wang?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT";
    12     public static String db_user = "root";   //用户名
    13     public static String db_password = "123456"; //密码
    14      
    15     public static Connection getConn () {
    16         Connection conn = null;
    17         try {
    18             Class.forName("com.mysql.cj.jdbc.Driver");//加载驱动
    19             conn = DriverManager.getConnection(db_url, db_user, db_password);//获取连接对象
    20         } catch (Exception e) {
    21             e.printStackTrace();
    22         }
    23         return conn;
    24     }
    25      
    26     /**
    27      * 关闭连接
    28      * @param state
    29      * @param conn
    30      */
    31     public static void close (Statement state, Connection conn) {
    32         if (state != null) {
    33             try {
    34                 state.close();
    35             } catch (SQLException e) {
    36                 e.printStackTrace();
    37             }
    38         }
    39         if (conn != null) {
    40             try {
    41                 conn.close();
    42             } catch (SQLException e) {
    43                 e.printStackTrace();
    44             }
    45         }
    46     }
    47      
    48     /**
    49      * 关闭连接
    50      * @param rs
    51      * @param state
    52      * @param conn
    53      */
    54     public static void close (ResultSet rs, Statement state, Connection conn) {
    55         if (rs != null) {
    56             try {
    57                 rs.close();
    58             } catch (SQLException e) {
    59                 e.printStackTrace();
    60             }
    61         }
    62         if (state != null) {
    63             try {
    64                 state.close();
    65             } catch (SQLException e) {
    66                 e.printStackTrace();
    67             }
    68         }
    69         if (conn != null) {
    70             try {
    71                 conn.close();
    72             } catch (SQLException e) {
    73                 e.printStackTrace();
    74             }
    75         }
    76     }
    77  
    78 }
    DBUtils.java

    2.实体类

     1 package com.wang.pojo;
     2 
     3 import java.math.BigDecimal;
     4 
     5 public class HomeCost {
     6     
     7     private int id;//id
     8     private String name;//消费名称
     9     private BigDecimal money;//消费金额
    10     private String date;//消费日期
    11     private BigDecimal sum;//累计消费
    12     
    13     
    14     public int getId() {
    15         return id;
    16     }
    17     public void setId(int id) {
    18         this.id = id;
    19     }
    20     public String getName() {
    21         return name;
    22     }
    23     public void setName(String name) {
    24         this.name = name;
    25     }
    26     public BigDecimal getMoney() {
    27         return money;
    28     }
    29     public void setMoney(BigDecimal money) {
    30         this.money = money;
    31     }
    32     public String getDate() {
    33         return date;
    34     }
    35     public void setDate(String date) {
    36         this.date = date;
    37     }
    38     public BigDecimal getSum() {
    39         return sum;
    40     }
    41     public void setSum(BigDecimal sum) {
    42         this.sum = sum;
    43     }
    44     
    45     
    46        
    47     @Override
    48     public String toString() {
    49         return "HomeCost [id=" + id + ", name=" + name + ", money=" + money + ", date=" + date + ", sum=" + sum + "]";
    50     }
    51     
    52     public HomeCost() {}
    53     
    54     public HomeCost(String name, BigDecimal money) {
    55         super();
    56         this.name = name;
    57         this.money = money;
    58     }
    59     
    60     public HomeCost(int id,String name,BigDecimal money, String date) {
    61         super();
    62         this.id=id;
    63         this.name = name;
    64         this.money=money;
    65         this.date=date;
    66     }
    67     public HomeCost(int id, String name, BigDecimal money, String date, BigDecimal sum) {
    68         super();
    69         this.id = id;
    70         this.name = name;
    71         this.money = money;
    72         this.date = date;
    73         this.sum = sum;
    74     }
    75     
    76 }
    HomeCost.java

    3.持久化Dao层

      1 package com.wang.dao;
      2 
      3 import java.math.BigDecimal;
      4 import java.sql.Connection;
      5 import java.sql.ResultSet;
      6 import java.sql.SQLException;
      7 import java.sql.Statement;
      8 import java.util.ArrayList;
      9 import java.util.List;
     10 
     11 import com.wang.pojo.HomeCost;
     12 import com.wang.utils.DBUtils;
     13 
     14 public class HomeCostDao {
     15     
     16     /**
     17      * updatesql()用来执行 insert/update/delete语句
     18      * @param sql 具体的sql语句
     19      * @return 返回-1,说明执行失败;否则为影响数据条数
     20      */
     21     public int updatesql(String sql) {
     22         Connection conn = DBUtils.getConn();//获取连接对象
     23         Statement state = null;
     24         try {
     25             state = conn.createStatement();
     26             return state.executeUpdate(sql);
     27         } catch (Exception e) {
     28             e.printStackTrace();
     29         } finally {
     30             DBUtils.close(state, conn);
     31         }
     32         return -1;       
     33     }
     34     
     35     
     36     //添加
     37     public int add(HomeCost homecost) {
     38         //insert语句,形如insert into 表名(字段1,字段2) values('值1','值2');
     39         String sql = "insert into home(name,money) values('"+ homecost.getName() 
     40             + "','" + homecost.getMoney() +  "')";
     41         return updatesql(sql);
     42     }
     43     
     44     //删除
     45     public int delete (int id) {
     46         //delete语句,形如delete from 表名 where id='值';
     47         String sql = "delete from home where id='" + id + "'";
     48         return updatesql(sql);
     49     }
     50      
     51     //修改
     52     public int update(HomeCost homecost) {
     53         //update语句,形如update 表名 set 字段1 = '值1',字段2 = '值2'where id = '值3';
     54         String sql = "update home set name='" + homecost.getName() + "', money='" 
     55                 + homecost.getMoney()+ "' where id='" + homecost.getId() + "'";
     56         return updatesql(sql);
     57         
     58     }
     59     
     60     //查询
     61     public List<HomeCost> query(String keyword) {
     62         String sql = "select * from home WHERE name LIKE '%"+keyword+"%' OR money LIKE '%"+keyword
     63                 +"%'OR date LIKE '%"+keyword+ "%'";
     64         List<HomeCost> list = new ArrayList<>();
     65         Connection conn = DBUtils.getConn();
     66         Statement state = null;
     67         ResultSet rs = null;
     68         try {
     69             state = conn.createStatement();
     70             rs = state.executeQuery(sql);
     71             while (rs.next()) {
     72                 int id = rs.getInt("id");//获取查询结果中的id
     73                 String name = rs.getString("name");//获取查询结果中的name
     74                 BigDecimal money = rs.getBigDecimal("money");//获取查询结果中的money
     75                 String date = rs.getString("date");//获取查询结果中的date
     76                 HomeCost homeCost = new HomeCost(id,name,money,date);//调用构造方法赋值
     77                 list.add(homeCost);//添加到list集合中
     78             }
     79         } catch (SQLException e) {
     80             e.printStackTrace();
     81         } finally {
     82             DBUtils.close(rs, state, conn);
     83         }
     84         return list;
     85     }
     86     
     87     //通过id找到某条信息
     88     public HomeCost getHomeCostById(int id) {
     89         String sql = "select * from home where id ='" + id + "'";
     90         Connection conn = DBUtils.getConn();
     91         Statement state = null;
     92         ResultSet rs = null;
     93         HomeCost homeCost = null;
     94         try {
     95             state = conn.createStatement();
     96             rs = state.executeQuery(sql);
     97             while (rs.next()) {
     98                 String name = rs.getString("name");
     99                 BigDecimal money = rs.getBigDecimal("money");
    100                 String date = rs.getString("date");
    101                 homeCost = new HomeCost(id,name,money,date);         
    102             }
    103         } catch (Exception e) {
    104             e.printStackTrace();
    105         } finally {
    106             DBUtils.close(rs, state, conn);
    107         }
    108         return homeCost;
    109     }
    110     
    111     /**
    112      * 通过id计算该条消费记录累计消费金额
    113      * @return BigDecimal类型money
    114      */
    115     public BigDecimal queryMoneySum(int id) {
    116         String sql = "select money from home where id <="+id;
    117         BigDecimal sum = new BigDecimal("0.00");
    118         Connection conn = DBUtils.getConn();
    119         Statement state = null;
    120         ResultSet rs = null;
    121         try {
    122             state = conn.createStatement();
    123             rs = state.executeQuery(sql);
    124             while (rs.next()) {
    125                 BigDecimal money = rs.getBigDecimal("money");
    126                 //sum是money累加值
    127                 sum = sum.add(money);
    128             }
    129         } catch (SQLException e) {
    130             e.printStackTrace();
    131         } finally {
    132             DBUtils.close(rs, state, conn);
    133         }
    134         return sum;
    135     }
    136          
    137     //获取全部数据  
    138     public List<HomeCost> list() {
    139         String sql = "select * from home";
    140         List<HomeCost> list = new ArrayList<>();
    141         Connection conn = DBUtils.getConn();
    142         Statement state = null;
    143         ResultSet rs = null;
    144         try {
    145             state = conn.createStatement();
    146             rs = state.executeQuery(sql);
    147             HomeCost homeCost = null;
    148             while (rs.next()) {
    149                 int id = rs.getInt("id");
    150                 BigDecimal sum = queryMoneySum(id);
    151                 String name = rs.getString("name");
    152                 BigDecimal money = rs.getBigDecimal("money");
    153                 String date = rs.getString("date");
    154                 homeCost = new HomeCost(id,name,money,date,sum);
    155                 list.add(homeCost);
    156             }
    157         } catch (SQLException e) {
    158             e.printStackTrace();
    159         } finally {
    160             DBUtils.close(rs, state, conn);
    161         }
    162         return list;
    163     }
    164     
    165     
    166 }
    HomeCostDao.java

    4.事务层Service层

     1 package com.wang.service;
     2 
     3 import java.util.List;
     4 
     5 import com.wang.dao.HomeCostDao;
     6 import com.wang.pojo.HomeCost;
     7 
     8 public class HomeCostService {
     9     
    10     HomeCostDao homeCostDao = new HomeCostDao();
    11     
    12     //新增消费账单
    13     public int add(HomeCost homecost) {
    14         return homeCostDao.add(homecost);
    15     }
    16     
    17     //删除消费账单
    18     public int delete(int id) {
    19         return homeCostDao.delete(id);
    20     }
    21     
    22     //修改消费账单
    23     public int update(HomeCost homecost) {
    24         return homeCostDao.update(homecost);
    25     }
    26     
    27     //关键字查询
    28     public List<HomeCost> query(String keyword) {
    29         return homeCostDao.query(keyword);
    30     }
    31     
    32     //全部消费记录
    33     public List<HomeCost> list() {
    34         return homeCostDao.list();
    35     }
    36     
    37     //由id查找某条消费记录
    38     public HomeCost getHomeCostById(int id) {
    39         return homeCostDao.getHomeCostById(id);
    40     }
    41     
    42 }
    HomeCostService.java

    5.Web层Servlet层

    Servlet创建方式:项目名右键new--Servlet,使用@WebServlet注解,省去配置web.xml的时间

      1 package com.wang.web;
      2 
      3 import java.io.IOException;
      4 import java.math.BigDecimal;
      5 import java.util.List;
      6 
      7 import javax.servlet.ServletException;
      8 import javax.servlet.annotation.WebServlet;
      9 import javax.servlet.http.HttpServlet;
     10 import javax.servlet.http.HttpServletRequest;
     11 import javax.servlet.http.HttpServletResponse;
     12 
     13 import com.wang.pojo.HomeCost;
     14 import com.wang.service.HomeCostService;
     15 import com.wang.utils.WebUtils;
     16 
     17 /**
     18  * 访问地址url:localhost:8080/homeCost/manager/homeCostServlet
     19  * Servlet implementation class HomeCostServlet
     20  */
     21 @WebServlet("/manager/homeCostServlet")
     22 public class HomeCostServlet extends HttpServlet {
     23     private static final long serialVersionUID = 1L;
     24     private HomeCostService homeCostService = new HomeCostService();
     25     
     26     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     27         doPost(request, response);
     28     }
     29 
     30     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     31         String action = request.getParameter("action");
     32         if("add".equals(action)) {
     33             add(request, response);
     34         }else if("delete".equals(action)) {
     35             delete(request, response);
     36         }else if("update".equals(action)) {
     37             update(request, response);
     38         }else if("list".equals(action)) {
     39             list(request, response);
     40         }else if("getHomeCostById".equals(action)) {
     41             getHomeCostById(request, response);
     42         }else if("query".equals(action)) {
     43             query(request, response);
     44         }
     45     }
     46     
     47     //添加消费记录
     48     protected void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     49         //获取网页提交的参数
     50         String name = request.getParameter("name");
     51         BigDecimal money = WebUtils.bigdecimal(request.getParameter("money"), new BigDecimal(0.00));
     52         //封装成类对象
     53         HomeCost homeCost = new HomeCost(name,money);
     54         //执行添加操作,返回1,添加成功,反之失败
     55         if(homeCostService.add(homeCost) == 1) {
     56             //页面重定向
     57             response.sendRedirect(request.getContextPath()+"/manager/homeCostServlet?action=list");
     58         }else {
     59             //请求转发
     60             request.setAttribute("msg", "添加失败,联系管理员");
     61             request.setAttribute("homeCost", homeCost);
     62             request.getRequestDispatcher("/cost_edit.jsp").forward(request, response);
     63         }
     64     }
     65     //删除消费记录
     66     protected void delete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     67         //获取id
     68         int id  = WebUtils.parseInt(request.getParameter("id"), 0);
     69         //执行删除操作,返回1,删除成功,反之失败
     70         if (homeCostService.delete(id) == 1) {
     71             //页面重定向
     72             response.sendRedirect(request.getContextPath()+"/manager/homeCostServlet?action=list");
     73         }else {
     74             //请求转发
     75             request.setAttribute("msg", "删除失败,联系管理员");
     76             request.getRequestDispatcher("/manager/homeCostServlet?action=list").forward(request, response);
     77         }
     78         
     79     }
     80     //修改消费记录
     81     protected void update(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     82         //获取参数
     83         int id  = WebUtils.parseInt(request.getParameter("id"), 0);
     84         String name = request.getParameter("name");
     85         BigDecimal money = WebUtils.bigdecimal(request.getParameter("money"), new BigDecimal(0.00));
     86         String date = request.getParameter("date");
     87         //封装
     88         HomeCost homeCost = new HomeCost(id,name,money,date);
     89         //执行删除操作,返回1,修改成功,反之失败
     90         if(homeCostService.update(homeCost) == 1) {
     91             response.sendRedirect(request.getContextPath()+"/manager/homeCostServlet?action=list");
     92         }else {
     93             request.setAttribute("msg", "修改失败,联系管理员");
     94             request.setAttribute("homeCost", homeCost);
     95             request.getRequestDispatcher("/cost_edit.jsp").forward(request, response);
     96         }
     97     }
     98     //查询全部消费记录
     99     protected void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    100         List<HomeCost> homeCost = homeCostService.list();
    101         request.setAttribute("homeCost", homeCost);
    102         request.getRequestDispatcher("/manager.jsp").forward(request, response);
    103         
    104     }
    105     //通过id查询该条消费记录
    106     private void getHomeCostById(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    107         int id  = WebUtils.parseInt(request.getParameter("id"), 0);
    108         HomeCost homeCost = homeCostService.getHomeCostById(id);
    109         request.setAttribute("homeCost", homeCost);
    110         request.getRequestDispatcher("/cost_edit.jsp").forward(request, response);
    111     }
    112     //通过关键词查询
    113     protected void query(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    114         String keyword=request.getParameter("keyword");
    115         List<HomeCost> homeCost = homeCostService.query(keyword);
    116         request.setAttribute("homeCost", homeCost);
    117         request.getRequestDispatcher("/query.jsp").forward(request, response);
    118         
    119     }
    120 
    121 
    122 }
    HomeCostServlet.java

    6.工具类

     1 package com.wang.utils;
     2 
     3 import java.math.BigDecimal;
     4 
     5 public class WebUtils {
     6     
     7     //该类为工具类,封装常用的函数,catch类型转换异常,保障程序健壮性
     8     
     9     
    10     /**
    11      * String转BigDecimal发生异常返回默认值
    12      * @param str  字符串
    13      * @param defaultValue 默认值
    14      * @return BigDecimal值
    15      */
    16     public static BigDecimal bigdecimal(String str,BigDecimal defaultValue) {
    17         try {
    18             return new BigDecimal(str);
    19         } catch (Exception e) {
    20             //e.printStackTrace();
    21         }
    22         return defaultValue;
    23     }
    24     
    25     /**
    26      * 字符串转int
    27      * @param string 被转换的字符串
    28      * @param defaultValue 默认值
    29      * @return int
    30      */
    31     public static int parseInt(String string,int defaultValue){
    32         try {
    33             return Integer.parseInt(string);
    34         } catch (NumberFormatException e) {
    35             //e.printStackTrace();
    36         }
    37         return defaultValue;
    38     }
    39     
    40 
    41 }
    WebUtils.java

    最终创建Web动态工程如下图:

    **************************************************************************************************

    注:需额外导入部分jar包,css样式,js文件,如下:

    附下载链接(永久链):

    链接:https://pan.baidu.com/s/1XA99yVkFGCEeY0-9_5RAxg
    提取码:jg0n
    复制这段内容后打开百度网盘手机App,操作更方便哦

    完整项目下载地址:

    链接:https://pan.baidu.com/s/1AoVdFsq4eGvPehyFjVqIMw
    提取码:5gvo

  • 相关阅读:
    NOIP模拟 1
    wlan
    IS-IS IGP
    linux 基础 软件的安装 *****
    第五部分 linux 软件安装RPM SRPM与YUM
    第四部分 linux使用者管理
    添加rpmforge源 centos 7
    x86 保护模式 十 分页管理机制
    X86保护模式 八操作系统类指令
    poj2230 Watchcow【欧拉回路】【输出路径】(遍历所有边的两个方向)
  • 原文地址:https://www.cnblogs.com/mawangwang/p/10438578.html
Copyright © 2020-2023  润新知