栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

smbms(超市管理系统)源码 + 分析

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

smbms(超市管理系统)源码 + 分析

在项目开始之前,我们首先要对项目的整体架构分析一下,该项目一共分为四个模块,登录注销、用户管理、订单管理、供应商管理,其中用户管理、订单管理以及供应商管理都是需要对数据库进行crud的。项目的整体架构图如下:

1.前期准备 1.项目架构

2.Maven配置

项目的架构分析完成之后,我们首先就需要进行一些前期准备,创建项目。首先创建一个Maven项目:

在Maven项目创建完毕之后,我们需要对配置文件进行修改

对web.xml的修改如下:




对pom.xml进行配置,导入相关的依赖如下:




  4.0.0

    org.example
    smbms
    1.0-SNAPSHOT
    war
    
        
            junit
            junit
            4.12
        
        
            org.apache.tomcat
            tomcat-servlet-api
            10.0.16
        


        
            com.alibaba
            fastjson
            1.2.79
        
        
            mysql
            mysql-connector-java
            8.0.25
        
        
            org.apache.tomcat
            tomcat-jsp-api
            10.0.16
        
        
            org.glassfish.web
            jakarta.servlet.jsp.jstl
            2.0.0
        


  

3.Tomcat配置

将Maven配置完成后,我们需要对Tomcat进行配置:



Tomcat配置完成之后,我们需要连接数据库

4.连接数据库

5.编写实体类

实体类中的四个类是与数据库当中的四个表相对应的。

public class Bill {
    private Integer id;   //id
    private String billCode; //账单编码
    private String productName; //商品名称
    private String productDesc; //商品描述
    private String productUnit; //商品单位
    private BigDecimal productCount; //商品数量
    private BigDecimal totalPrice; //总金额
    private Integer isPayment; //是否支付
    private Integer providerId; //供应商ID
    private Integer createdBy; //创建者
    private Date creationDate; //创建时间
    private Integer modifyBy; //更新者
    private Date modifyDate;//更新时间

    private String providerName;//供应商名称


    public String getProviderName() {
        return providerName;
    }
    public void setProviderName(String providerName) {
        this.providerName = providerName;
    }
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getBillCode() {
        return billCode;
    }
    public void setBillCode(String billCode) {
        this.billCode = billCode;
    }
    public String getProductName() {
        return productName;
    }
    public void setProductName(String productName) {
        this.productName = productName;
    }
    public String getProductDesc() {
        return productDesc;
    }
    public void setProductDesc(String productDesc) {
        this.productDesc = productDesc;
    }
    public String getProductUnit() {
        return productUnit;
    }
    public void setProductUnit(String productUnit) {
        this.productUnit = productUnit;
    }
    public BigDecimal getProductCount() {
        return productCount;
    }
    public void setProductCount(BigDecimal productCount) {
        this.productCount = productCount;
    }
    public BigDecimal getTotalPrice() {
        return totalPrice;
    }
    public void setTotalPrice(BigDecimal totalPrice) {
        this.totalPrice = totalPrice;
    }
    public Integer getIsPayment() {
        return isPayment;
    }
    public void setIsPayment(Integer isPayment) {
        this.isPayment = isPayment;
    }

    public Integer getProviderId() {
        return providerId;
    }
    public void setProviderId(Integer providerId) {
        this.providerId = providerId;
    }
    public Integer getCreatedBy() {
        return createdBy;
    }
    public void setCreatedBy(Integer createdBy) {
        this.createdBy = createdBy;
    }
    public Date getCreationDate() {
        return creationDate;
    }
    public void setCreationDate(Date creationDate) {
        this.creationDate = creationDate;
    }
    public Integer getModifyBy() {
        return modifyBy;
    }
    public void setModifyBy(Integer modifyBy) {
        this.modifyBy = modifyBy;
    }
    public Date getModifyDate() {
        return modifyDate;
    }
    public void setModifyDate(Date modifyDate) {
        this.modifyDate = modifyDate;
    }
}


public class Provider {
    private Integer id;   //id
    private String proCode; //供应商编码
    private String proName; //供应商名称
    private String proDesc; //供应商描述
    private String proContact; //供应商联系人
    private String proPhone; //供应商电话
    private String proAddress; //供应商地址
    private String proFax; //供应商传真
    private Integer createdBy; //创建者
    private Date creationDate; //创建时间
    private Integer modifyBy; //更新者
    private Date modifyDate;//更新时间
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getProCode() {
        return proCode;
    }
    public void setProCode(String proCode) {
        this.proCode = proCode;
    }
    public String getProName() {
        return proName;
    }
    public void setProName(String proName) {
        this.proname = proName;
    }
    public String getProDesc() {
        return proDesc;
    }
    public void setProDesc(String proDesc) {
        this.proDesc = proDesc;
    }
    public String getProContact() {
        return proContact;
    }
    public void setProContact(String proContact) {
        this.proContact = proContact;
    }
    public String getProPhone() {
        return proPhone;
    }
    public void setProPhone(String proPhone) {
        this.proPhone = proPhone;
    }
    public String getProAddress() {
        return proAddress;
    }
    public void setProAddress(String proAddress) {
        this.proAddress = proAddress;
    }
    public String getProFax() {
        return proFax;
    }
    public void setProFax(String proFax) {
        this.proFax = proFax;
    }
    public Integer getCreatedBy() {
        return createdBy;
    }
    public void setCreatedBy(Integer createdBy) {
        this.createdBy = createdBy;
    }
    public Date getCreationDate() {
        return creationDate;
    }
    public void setCreationDate(Date creationDate) {
        this.creationDate = creationDate;
    }
    public Integer getModifyBy() {
        return modifyBy;
    }
    public void setModifyBy(Integer modifyBy) {
        this.modifyBy = modifyBy;
    }
    public Date getModifyDate() {
        return modifyDate;
    }
    public void setModifyDate(Date modifyDate) {
        this.modifyDate = modifyDate;
    }


}

public class Role {
    private Integer id;             //id
    private String roleCode;        //角色编码
    private String roleName;        //角色名称
    private Integer createdBy;      //创建者
    private Date creationDate;      //创建时间
    private Integer modifyBy;       //更新者
    private Date modifyDate;        //更新时间


    public long getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getRoleCode() {
        return roleCode;
    }

    public void setRoleCode(String roleCode) {
        this.roleCode = roleCode;
    }

    public String getRoleName() {
        return roleName;
    }

    public void setRoleName(String roleName) {
        this.roleName = roleName;
    }

    public Integer getCreatedBy() {
        return createdBy;
    }

    public void setCreatedBy(Integer createdBy) {
        this.createdBy = createdBy;
    }

    public Date getCreationDate() {
        return creationDate;
    }

    public void setCreationDate(Date creationDate) {
        this.creationDate = creationDate;
    }

    public Integer getModifyBy() {
        return modifyBy;
    }

    public void setModifyBy(Integer modifyBy) {
        this.modifyBy = modifyBy;
    }

    public Date getModifyDate() {
        return modifyDate;
    }

    public void setModifyDate(Date modifyDate) {
        this.modifyDate = modifyDate;
    }


}

public class User {
    private Integer id;     //id
    private String userCode;    //用户编码
    private String userName;     //用户名称
    private String userPassword;    //用户密码
    private Integer gender;        //性别
    private Date birthday;      //出生日期
    private String phone;       //电话
    private String address;     //地址
    private Integer userRole;   //用户角色
    private Integer createdBy;  //创建者
    private Date creationDate;  //创建时间
    private Integer modifyBy;   //更新者
    private Date modifyDate;    //更新时间

    private Integer age;    //年龄
    private String userRoleName;    //用户角色名称

    public Integer getAge(){
        Date date = new Date();
        Integer age = date.getYear() - birthday.getYear();
        return age;
    }


    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUserCode() {
        return userCode;
    }

    public void setUserCode(String userCode) {
        this.userCode = userCode;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getUserPassword() {
        return userPassword;
    }

    public void setUserPassword(String userPassword) {
        this.userPassword = userPassword;
    }

    public Integer getGender() {
        return gender;
    }

    public void setGender(Integer gender) {
        this.gender = gender;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public Integer getUserRole() {
        return userRole;
    }

    public void setUserRole(Integer userRole) {
        this.userRole = userRole;
    }

    public Integer getCreatedBy() {
        return createdBy;
    }

    public void setCreatedBy(Integer createdBy) {
        this.createdBy = createdBy;
    }

    public Date getCreationDate() {
        return creationDate;
    }

    public void setCreationDate(Date creationDate) {
        this.creationDate = creationDate;
    }

    public Integer getModifyBy() {
        return modifyBy;
    }

    public void setModifyBy(Integer modifyBy) {
        this.modifyBy = modifyBy;
    }

    public Date getModifyDate() {
        return modifyDate;
    }

    public void setModifyDate(Date modifyDate) {
        this.modifyDate = modifyDate;
    }


    public void setAge(Integer age) {
        this.age = age;
    }

    public String getUserRoleName() {
        return userRoleName;
    }

    public void setUserRoleName(String userRoleName) {
        this.userRoleName = userRoleName;
    }

    public User(){

    }

    public void setUserName(Object userName) {
    }
}

6.编写公共类

因为我们每一个模块都会涉及到对数据库的crud,以及对数据库的资源的连接和关闭。是一个有着大量重复性的操作,所以我们需要编写一个公共类来实现这些操作,这样在编写每一个模块的时候就可以直接调用。

public class baseDao {
    private static String url;
    private static String driver;
    private static String username;
    private static String password;
	//静态代码块,类加载的时候就初始化了
    static {
        //通过类加载器读取响应的资源
        Properties properties = new Properties();
        InputStream is = baseDao.class.getClassLoader().getResourceAsStream("database.properties");

        try {
            properties.load(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
        url = properties.getProperty("url");
        driver = properties.getProperty("driver");
        username = properties.getProperty("username");
        password = properties.getProperty("password");
    }
    //获得数据库的链接
    public static Connection getConnection() {
        Connection connection = null;
        try {
            Class.forName(driver);
            connection = DriverManager.getConnection(url, username, password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return connection;
    }
    
    //执行sql查询语句
    public static ResultSet execute(Connection connection, String sql, Object[] params, ResultSet resultSet, PreparedStatement preparedStatement) throws SQLException {
        preparedStatement = connection.prepareStatement(sql);
        for (int i = 0; i < params.length; i++) {
            preparedStatement.setObject(i + 1, params[i]);
        }
        resultSet = preparedStatement.executeQuery();
        return resultSet;
    }


    //对数据库进行crud
    public static int execute(Connection connection, String sql, Object[] params, PreparedStatement preparedStatement) throws SQLException {
        preparedStatement = connection.prepareStatement(sql);
        for (int i = 0; i < params.length; i++) {
            preparedStatement.setObject(i + 1, params[i]);
        }
        int updateRows = preparedStatement.executeUpdate();
        System.out.println(updateRows);
        return updateRows;
    }

    //关闭数据库资源
    public static boolean close(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet) {
        boolean flag = true;
        if (resultSet != null) {
            try {
                resultSet.close();
                resultSet = null;
            } catch (SQLException e) {
                e.printStackTrace();
                flag = false;
            }
        }
        if (preparedStatement != null) {
            try {
                preparedStatement.close();
                preparedStatement = null;
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (connection != null) {
            try {
                connection.close();
                connection = null;
            } catch (SQLException e) {
                e.printStackTrace();
                flag = false;
            }
        }
        return flag;
    }
}

xmldriver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/smbms?useSSL=true&useUnicode=true&characterEncoding=utf-8
username=root
password=123456
7.编写字符编码过滤器
public class CharacterEncodingFilter implements Filter {
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        servletRequest.setCharacterEncoding("utf-8");
        servletResponse.setCharacterEncoding("utf-8");

        filterChain.doFilter(servletRequest, servletResponse);
    }

    public void destroy() {
    }
}

编写了过滤器之后,我们还需要到web.xml中去注册才能实现过滤功能


    filter
    com.zhou.filter.CharacterEncodingFilter



    filter
    
    public User getLoginUser(String userCode, String password);
    
    public User getLoginUser(String userCode);

    
    public boolean updatePwd(int id,String pwd);

    
    public int getUserNums(String username,int userRole);

    
    public List getUserList(String username,int userRole,int currentPageNo,int pageSize);

    
    public boolean add(User user);

    
    public boolean modify(User user);

    
    public User getUserById(String id);

    
    public boolean delUser(int id);

}

package com.zhou.service.user;

import com.zhou.dao.baseDao;
import com.zhou.dao.user.UserDao;
import com.zhou.dao.user.UserDaoImp;
import com.zhou.polo.User;

import java.awt.*;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public class UserServiceImp implements UserService{
    private UserDao userdao;
    public UserServiceImp(){
        userdao = new UserDaoImp();
    }
    public User getLoginUser(String userCode, String password) {
        Connection connection = null;
        User user = null;
        try {
            //获取与数据库的连接
            connection = baseDao.getConnection();
            //获取用户
            user = userdao.getLoginUser(connection,userCode,password);
        } catch (SQLException e) {
            e.printStackTrace();
        }finally{
            //关闭连接
            baseDao.close(connection,null,null);
        }
        return user;
    }

    @Override
    public User getLoginUser(String userCode) {
        Connection connection = null;
        User user = null;
        try {
            //获取与数据库的连接
            connection = baseDao.getConnection();
            //获取用户
            user = userdao.getLoginUser(connection,userCode);
        } catch (SQLException e) {
            e.printStackTrace();
        }finally{
            //关闭连接
            baseDao.close(connection,null,null);
        }
        return user;
    }

    public boolean updatePwd(int id, String pwd) {
        Connection connection = null;
        boolean flag = false;
        try {
            connection = baseDao.getConnection();
            flag = userdao.updatePwd(connection,id,pwd);
        } catch (SQLException e) {
            e.printStackTrace();
        }finally{
            baseDao.close(connection,null,null);
        }
        return flag;
    }

    @Override
    public int getUserNums(String username, int userRole) {
        Connection connection = null;
        int count = 0;
        connection = baseDao.getConnection();
        if(connection != null){
            try {
                count = userdao.getUserNums(connection,username,userRole);
            } catch (SQLException e) {
                e.printStackTrace();
            }finally{
                baseDao.close(connection,null,null);
            }
        }
        return count;
    }

    @Override
    public List getUserList(String username, int userRole, int currentPageNo, int pageSize) {
        Connection connection = null;
        List userList = null;
        connection = baseDao.getConnection();
        if(connection != null){
            try {
                userList = userdao.getUserList(connection,username,userRole,currentPageNo,pageSize);
            } catch (SQLException e) {
                e.printStackTrace();
            }finally{
                baseDao.close(connection,null,null);
            }
        }
        return userList;
    }

    @Override
    public boolean add(User user) {
        boolean flag = false;
        Connection connection = null;
        try {

            connection = baseDao.getConnection();
            //开启jdbc的事务管理,同时设置自动提交为false
            System.out.println("1");
            connection.setAutoCommit(false);
            System.out.println("2");
            flag = userdao.add(connection,user);
            System.out.println("3");
            connection.commit();
            System.out.println("4");
            if(flag){
                System.out.println("add success!");
            }else{
                System.out.println("add failed!");
            }
        } catch (SQLException e) {
            System.out.println("rollback------------");
            try {
                connection.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
        } finally {
            baseDao.close(connection,null,null);
        }
        return flag;
    }

    @Override
    public boolean modify(User user) {
        boolean flag = false;
        Connection connection = null;
        if(user != null){
            connection = baseDao.getConnection();
            try {
                flag = userdao.modify(connection, user);
            } catch (SQLException e) {
                e.printStackTrace();
            }finally{
                baseDao.close(connection,null,null);
            }
        }
        return flag;
    }

    @Override
    public User getUserById(String id) {
        User user = null;
        Connection connection = null;
        connection = baseDao.getConnection();
        if(connection != null){
            try {
                user = userdao.getUserById(connection, id);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        baseDao.close(connection,null,null);
        return user;
    }

    @Override
    public boolean delUser(int id) {
        boolean flag = false;
        Connection connection = baseDao.getConnection();
        if(connection != null){
            try {
                flag = userdao.delUser(connection, id);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        baseDao.close(connection,null,null);

        return flag;
    }

}

servlet
package com.zhou.servlet.user;

import com.alibaba.fastjson.JSONArray;
import com.mysql.cj.util.StringUtils;
import com.zhou.polo.Role;
import com.zhou.polo.User;
import com.zhou.service.role.RoleServiceImpl;
import com.zhou.service.user.UserService;
import com.zhou.service.user.UserServiceImp;
import com.zhou.util.Constants;
import com.zhou.util.PageSupport;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


public class UserServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获得前端的method信息实现对应的功能
        String method = req.getParameter("method");
        System.out.println("Usermethod --> " + method);
        if(method != null && method.equals("savepwd")){
            this.updatePwd(req,resp);
        }else if(method != null && method.equals("pwdmodify")){
            this.pwdModify(req,resp);
        }else if(method != null && method.equals("query")){
            this.query(req,resp);
        }else if(method != null && method.equals("add")){
            this.add(req,resp);
        }else if(method != null && method.equals("getrolelist")){
            this.getRoleList(req,resp);
        }else if(method != null && method.equals("modifyexe")){
            this.modify(req,resp);
        }else if(method != null && method.equals("modify")){
            this.getUserById(req,resp,"usermodify.jsp");
        }else if(method != null && method.equals("view")){
            this.getUserById(req,resp,"userview.jsp");
        }else if(method != null && method.equals("deluser")){
            this.delUser(req,resp);
        }else if(method != null && method.equals("ucexist")){
            this.isUserCodeExist(req,resp);
        }
    }

    public void isUserCodeExist(HttpServletRequest req, HttpServletResponse resp) {
        String userCode = req.getParameter("userCode");
        Map resultMap = new HashMap<>();
        if(StringUtils.isNullOrEmpty(userCode)){
            resultMap.put("userCode","exist");
        }else{
            UserService userService = new UserServiceImp();
            User user = userService.getLoginUser(userCode);
            if(user != null){
                resultMap.put("userCode","exist");
            }else{
                resultMap.put("userCode","notexist");
            }
        }
        //将resultMap转换成json对象输出
        resp.setContentType("application/json");
        try {
            PrintWriter writer = resp.getWriter();
            writer.write(JSONArray.toJSONString(resultMap));
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void delUser(HttpServletRequest req, HttpServletResponse resp){
        String id = req.getParameter("uid");
        int delId;
        if(!StringUtils.isNullOrEmpty(id)){
            delId = Integer.parseInt(id);
        }else{
            delId = 0;
        }
        Map resultMap = new HashMap<>();
        if(delId <= 0){
            resultMap.put("delResult","notexist");
        }else {
            UserService userService = new UserServiceImp();
            if(userService.delUser(delId)){
                resultMap.put("delResult","true");
            }else{
                resultMap.put("delResult","false");
            }
        }
        //把resultMap转换成json对象输出
        resp.setContentType("application/json");
        PrintWriter writer = null;
        try {
            writer = resp.getWriter();
            writer.write(JSONArray.toJSONString(resultMap));
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public void modify(HttpServletRequest req, HttpServletResponse resp){
        String id = req.getParameter("uid");
        String userName = req.getParameter("userName");
        String gender = req.getParameter("gender");
        String birthday = req.getParameter("birthday");
        String phone = req.getParameter("phone");
        String address = req.getParameter("address");
        String userRole = req.getParameter("userRole");

        User user = new User();
        user.setId(Integer.valueOf(id));
        user.setUserName(userName);
        user.setGender(Integer.valueOf(gender));
        try {
            user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        user.setPhone(phone);
        user.setAddress(address);
        user.setUserRole(Integer.valueOf(userRole));
        user.setCreationDate(new Date());
        user.setModifyBy(((User)req.getSession().getAttribute(Constants.USER_SESSION)).getId());

        UserService userService = new UserServiceImp();
        if(userService.modify(user)){
            try {
                resp.sendRedirect(req.getContextPath() + "/jsp/user.do?method=query");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{
            try {
                req.getRequestDispatcher("usermodify.jsp").forward(req,resp);
            } catch (ServletException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    //获取用户id
    public void getUserById(HttpServletRequest req, HttpServletResponse resp,String url){
        String  id = req.getParameter("uid");
        if(!StringUtils.isNullOrEmpty(id)){
            UserService userService = new UserServiceImp();
            User user = userService.getUserById(id);
            req.setAttribute("user",user);
            try {
                req.getRequestDispatcher(url).forward(req,resp);
            } catch (ServletException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    public void getRoleList(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        List roleList = null;
        RoleServiceImpl roleService = new RoleServiceImpl();
        roleList = roleService.getRoleList();
        //把RoleList转换成json对象输出
        resp.setContentType("application/json");
        PrintWriter writer = resp.getWriter();
        writer.write(JSONArray.toJSONString(roleList));
        writer.flush();
        writer.close();
    }

    //修改密码
    public void updatePwd(HttpServletRequest req, HttpServletResponse resp){
        //从Session中拿Id
        Object id = req.getSession().getAttribute(Constants.USER_SESSION);
        String npwd = req.getParameter("newpassword");
        boolean flag = false;
        if(id != null && !StringUtils.isNullOrEmpty(npwd)){
            UserService userService = new UserServiceImp();
            flag = userService.updatePwd(((User)id).getId(), npwd);
            if(flag){
                req.setAttribute("message","密码修改成功,请退出,使用新密码登录");
                //密码修改成功,移除Session
                req.getSession().removeAttribute(Constants.USER_SESSION);
            }else{
                req.setAttribute("message","密码修改失败");
            }
        }else{
            req.setAttribute("message","新密码有问题");
        }
        try {
            req.getRequestDispatcher("pwdmodify.jsp").forward(req,resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void pwdModify(HttpServletRequest req, HttpServletResponse resp){
        //从Session里面拿Id
        Object o = req.getSession().getAttribute(Constants.USER_SESSION);
        String oldpassword = req.getParameter("oldpassword");

        Map resultMap = new HashMap<>();

        if(o != null){  // Session失效
            resultMap.put("result","sessionerror");
        }if(StringUtils.isNullOrEmpty(oldpassword)){
            resultMap.put("result","error");
        }else{
            String userpassword = ((User)o).getUserPassword();      //获取Session中用户的密码
            if(userpassword.equals(oldpassword)){
                resultMap.put("result","true");
            }else{
                resultMap.put("result","false");
            }
        }

        try {
            resp.setContentType("application/json");
            PrintWriter writer = resp.getWriter();
            writer.write(JSONArray.toJSONString(resultMap));
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    //查询对应的用户信息
    public void query(HttpServletRequest req, HttpServletResponse resp){
        //从前端获取数据
        String queryUserName = req.getParameter("queryUserName");
        String temp = req.getParameter("queryUserRole");
        String pageIndex = req.getParameter("pageIndex");
        int queryUserRole = 0;

        //获取用户列表
        UserServiceImp userServiceImp = new UserServiceImp();

        //第一次走请求肯定是第一页,页面大小固定
        int pageSize = 5;   //可以把属性写到配置文件当中,方便修改
        int currentPageNo = 1;

        if(queryUserName == null){
            queryUserName = "";
        }
        if(temp != null && !temp.equals("")){
            queryUserRole = Integer.parseInt(temp);     //给查询赋值1,2,3
        }
        if(pageIndex != null){
            currentPageNo = Integer.parseInt(pageIndex);
        }

        //获取用户的总数
        int totalCount = userServiceImp.getUserNums(queryUserName,queryUserRole);
        //总页数
        PageSupport pageSupport = new PageSupport();
        pageSupport.setCurrentPageNo(currentPageNo);        //设置当前页数
        pageSupport.setPageSize(pageSize);                  //设置页数记录数
        pageSupport.setTotalCount(totalCount);              //设置所有记录数目

        int totalPageCount = ((int) (totalCount / pageSize)) + 1;
        //控制尾页和首页
        if(currentPageNo < 1){
            currentPageNo = 1;
        }else if (currentPageNo > totalPageCount){    //控制尾页
            currentPageNo = totalPageCount;
        }

        //获取用户列表显示
        List userList = userServiceImp.getUserList(queryUserName,queryUserRole,currentPageNo,pageSize);
        req.setAttribute("userList",userList);

        RoleServiceImpl roleService = new RoleServiceImpl();
        List roleList = roleService.getRoleList();
        req.setAttribute("roleList",roleList);
        req.setAttribute("totalCount",totalCount);
        req.setAttribute("currentPageNo",currentPageNo);
        req.setAttribute("queryUserName",queryUserName);
        req.setAttribute("queryUserRole",queryUserRole);
        req.setAttribute("totalPageCount",totalPageCount);
        //返回前端
        try {
            req.getRequestDispatcher("userlist.jsp").forward(req,resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    //用户添加
    public void add(HttpServletRequest req, HttpServletResponse resp){
        String userCode = req.getParameter("userCode");
        String userName = req.getParameter("userName");
        String userPassword = req.getParameter("userPassword");
        String gender = req.getParameter("gender");
        String birthday = req.getParameter("birthday");
        String userRole = req.getParameter("userRole");
        String address = req.getParameter("address");
        String phone = req.getParameter("phone");

        boolean flag = false;
        User user = new User();
        user.setUserCode(userCode);
        user.setUserName(userName);
        user.setUserPassword(userPassword);
        user.setGender(Integer.parseInt(gender));
        try {
            user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        user.setUserRole(Integer.parseInt(userRole));
        user.setAddress(address);
        user.setPhone(phone);
        user.setCreationDate(new Date());
        user.setCreatedBy(((User)(req.getSession().getAttribute(Constants.USER_SESSION))).getId());

        UserServiceImp userServiceImp = new UserServiceImp();
        flag = userServiceImp.add(user);
        if(flag){
            try {
                resp.sendRedirect(req.getContextPath() + "/jsp/user.do?method=query");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{
            try {
                req.getRequestDispatcher("useradd.jsp").forward(req,resp);
            } catch (ServletException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
4.供应商管理

与用户管理的功能一样,因此直接展示代码

dao
package com.zhou.dao.provider;

import com.zhou.polo.Provider;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;


public interface ProviderDao {
    
    public List getProviderList(Connection connection,String providerCode,String providerName) throws SQLException;

    
    public boolean add(Connection connection,Provider provider) throws SQLException;
    
    public boolean delProvider(Connection connection,int id ) throws SQLException;
    
    public Provider getProviderById(Connection connection,String id) throws SQLException;

    
    public boolean modify(Connection connection,Provider provider) throws SQLException;
}

package com.zhou.dao.provider;

import com.mysql.cj.util.StringUtils;
import com.zhou.dao.baseDao;
import com.zhou.polo.Provider;

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


public class ProviderDaoImpl implements ProviderDao{

    @Override
    public List getProviderList(Connection connection, String providerCode, String providerName) throws SQLException {
        List providerList = null;
        ResultSet rs = null;
        PreparedStatement pstm = null;
        if(connection != null){
            StringBuffer sql = new StringBuffer();
            providerList = new ArrayList<>();
            List list = new ArrayList<>();
            sql.append("select * from smbms_provider where 1=1");
            if(!StringUtils.isNullOrEmpty(providerCode)){
                sql.append(" and proCode like ?");
                list.add("%" + providerCode + "%");
            }
            if(!StringUtils.isNullOrEmpty(providerName)){
                sql.append(" and proname like ?");
                list.add("%" + providerName + "%");
            }
            Object[] params = list.toArray();
            rs = baseDao.execute(connection,sql.toString(),params,rs,pstm);
            while(rs.next()){
                Provider provider = new Provider();
                provider.setId(rs.getInt("id"));
                provider.setProCode(rs.getString("proCode"));
                provider.setProName(rs.getString("proName"));
                provider.setProDesc(rs.getString("proDesc"));
                provider.setProContact(rs.getString("proContact"));
                provider.setProPhone(rs.getString("proPhone"));
                provider.setProAddress(rs.getString("proAddress"));
                provider.setProFax(rs.getString("proFax"));
                provider.setCreatedBy(rs.getInt("createdBy"));
                provider.setCreationDate(rs.getTimestamp("creationDate"));
                provider.setModifyDate(rs.getTimestamp("modifyDate"));
                provider.setModifyBy(rs.getInt("modifyBy"));
                providerList.add(provider);
            }
            baseDao.close(connection,pstm,rs);
        }
        return providerList;
    }

    @Override
    public boolean add(Connection connection, Provider provider) throws SQLException {
        boolean flag = false;
        PreparedStatement pstm = null;
        if(connection != null){
            String sql = "insert into smbms_provider(id,proCode,proName,proDesc,proContact,proPhone,proAddress,proFax," +
                    "createdBy,creationDate,modifyDate,modifyBy)" + "values(?,?,?,?,?,?,?,?,?,?,?,?)";
            Object[] params = {provider.getId(),provider.getProCode(),provider.getProName(),provider.getProDesc(),
                    provider.getProContact(),provider.getProPhone(),provider.getProAddress(),provider.getProFax(),
                    provider.getCreatedBy(),provider.getCreationDate(),provider.getModifyDate(),provider.getModifyBy()};
            int execute = baseDao.execute(connection, sql, params, pstm);
            if(execute > 0){
                flag = true;
            }
            baseDao.close(connection,pstm,null);
        }
        return flag;
    }

    @Override
    public boolean delProvider(Connection connection, int id ) throws SQLException {
        boolean flag = false;
        PreparedStatement pstm = null;
        if(connection != null){
            String sql = "delete from smbms_provider where id = ?";
            Object[] params = {id};
            int execute = baseDao.execute(connection, sql, params, pstm);
            if(execute > 0){
                flag = true;
            }
            baseDao.close(connection,pstm,null);
        }

        return flag;
    }

    @Override
    public Provider getProviderById(Connection connection, String id) throws SQLException {
        Provider provider = null;
        PreparedStatement pstm = null;
        ResultSet rs = null;
        if(connection != null){
            String sql = "select * from smbms_provider where id = ?";
            Object[] params = {id};
            rs = baseDao.execute(connection, sql, params, rs,pstm);
            if(rs.next()){
                provider = new Provider();
                provider.setId(rs.getInt("id"));
                provider.setProCode(rs.getString("proCode"));
                provider.setProName(rs.getString("proName"));
                provider.setProDesc(rs.getString("proDesc"));
                provider.setProContact(rs.getString("proContact"));
                provider.setProPhone(rs.getString("proPhone"));
                provider.setProAddress(rs.getString("proAddress"));
                provider.setProFax(rs.getString("proFax"));
                provider.setCreatedBy(rs.getInt("createdBy"));
                provider.setCreationDate(rs.getTimestamp("creationDate"));
                provider.setModifyDate(rs.getTimestamp("modifyDate"));
                provider.setModifyBy(rs.getInt("modifyBy"));
            }
        }
        baseDao.close(connection,pstm,null);
        return provider;
    }

    @Override
    public boolean modify(Connection connection, Provider provider) throws SQLException {
        boolean flag = false;
        PreparedStatement pstm = null;
        if(connection != null){
            String sql = "update smbms_provider p set p.proCode = ?,p.proname= ?," +
                    "p.proContact = ?,p.proPhone = ? ,p.proAddress = ?,p.proFax = ?," +
                    "p.proDesc = ? where id = ?";
            Object[] params = {provider.getProCode(),provider.getProName(),provider.getProContact(),provider.getProPhone(),
                provider.getProAddress(),provider.getProFax(),provider.getProDesc(),provider.getId()};
            int execute = baseDao.execute(connection, sql, params, pstm);
            if(execute > 0){
                flag = true;
            }
        }
        baseDao.close(connection,pstm,null);
        return flag;
    }
}
 
service 
package com.zhou.service.provider;

import com.zhou.polo.Bill;
import com.zhou.polo.Provider;

import java.sql.SQLException;
import java.util.List;

public interface ProviderService {

    
    public List getProviderList(String providerCode,String providerName);

    
    public boolean add(Provider provider);

    
    public int delProvider(int id);
    
    public Provider getProviderById(String id);

    
    public boolean modify(Provider provider);


}

package com.zhou.service.provider;

import com.zhou.dao.baseDao;
import com.zhou.dao.bill.BillDao;
import com.zhou.dao.bill.BillDaoImpl;
import com.zhou.dao.provider.ProviderDao;
import com.zhou.dao.provider.ProviderDaoImpl;
import com.zhou.polo.Provider;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public class ProviderServiceImpl implements ProviderService {
    private ProviderDao providerDao;
    private BillDao billDao;
    public ProviderServiceImpl(){
        providerDao = new ProviderDaoImpl();
        billDao = new BillDaoImpl();
    }
    @Override
    public List getProviderList(String providerCode, String providerName) {
        List providerList = null;
        Connection connection = null;
        try {
            connection = baseDao.getConnection();
            providerList = providerDao.getProviderList(connection,providerCode,providerName);
        } catch (SQLException e) {
            e.printStackTrace();
        }finally{
            baseDao.close(connection,null,null);

        }
        return providerList;
    }

    @Override
    public boolean add(Provider provider) {
        boolean flag = false;
        Connection connection = null;
        try {
            connection = baseDao.getConnection();
            connection.setAutoCommit(false);
            flag = providerDao.add(connection,provider);
            if(flag){
                connection.commit();
            }
        } catch (SQLException e) {
            try {
                connection.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
        }finally{
            baseDao.close(connection,null,null);
        }
        return flag;
    }

    
    @Override
    public int delProvider(int id) {
        int billCount = -1;
        Connection connection = null;
        try {
            connection = baseDao.getConnection();
            connection.setAutoCommit(false);
            billCount = billDao.getBillCountByProviderId(connection,id);
            if(billCount == 0){
                providerDao.delProvider(connection,id);
            }
            connection.commit();
        } catch (SQLException e) {
            billCount = -1;
            try {
                connection.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
        } finally {
            baseDao.close(connection,null,null);
        }
        return billCount;
    }

    @Override
    public Provider getProviderById(String id) {
        Provider provider = null;
        Connection connection = null;
        try {
            connection = baseDao.getConnection();
            provider = providerDao.getProviderById(connection,id);
        } catch (SQLException e) {
            e.printStackTrace();
        }finally{
            baseDao.close(connection,null,null);
        }
        return provider;
    }

    @Override
    public boolean modify(Provider provider) {
        boolean flag = false;
        Connection connection = null;
        try {
            connection = baseDao.getConnection();
            flag = providerDao.modify(connection,provider);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return flag;
    }


}

servlet
package com.zhou.servlet.provider;

import com.alibaba.fastjson.JSONArray;
import com.mysql.cj.util.StringUtils;
import com.mysql.cj.xdevapi.JsonArray;
import com.oracle.wls.shaded.org.apache.xalan.xsltc.compiler.util.ResultTreeType;
import com.zhou.polo.Provider;
import com.zhou.polo.User;
import com.zhou.service.provider.ProviderService;
import com.zhou.service.provider.ProviderServiceImpl;
import com.zhou.util.Constants;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.PortUnreachableException;
import java.sql.Connection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class ProviderServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        System.out.println("Providermethod --> " + method);
        if(method != null && method.equals("query")){
            this.query(req,resp);
        }else if(method != null && method.equals("add")){
            this.add(req,resp);
        } else if (method != null && method.equals("delprovider")) {
            this.del(req,resp);
        }else if(method != null && method.equals("view")){
            this.getProviderById(req,resp,"providerview.jsp");
        }else if(method != null && method.equals("modify")){
            this.getProviderById(req,resp,"providermodify.jsp");
        }else if(method != null && method.equals("modifysave")){
            this.modify(req,resp);
        }
    }
    public void modify(HttpServletRequest req, HttpServletResponse resp){
        String id = req.getParameter("proid");
        String proCode = req.getParameter("proCode");
        String proname = req.getParameter("proName");
        String proContact = req.getParameter("proContact");
        String proPhone = req.getParameter("proPhone");
        String proFax = req.getParameter("proFax");
        String proAddress = req.getParameter("proAddress");
        String proDesc = req.getParameter("proDesc");
        Provider provider = new Provider();
        provider.setId(Integer.valueOf(id));
        provider.setProCode(proCode);
        provider.setProName(proName);
        provider.setProContact(proContact);
        provider.setProPhone(proPhone);
        provider.setProFax(proFax);
        provider.setProAddress(proAddress);
        provider.setProDesc(proDesc);
        provider.setModifyDate(new Date());
        provider.setModifyBy(((User)req.getSession().getAttribute(Constants.USER_SESSION)).getId());

        ProviderService providerService = new ProviderServiceImpl();
        if(providerService.modify(provider)){
            try {
                resp.sendRedirect(req.getContextPath() + "/jsp/provider.do?method=query");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{
            try {
                req.getRequestDispatcher("providermodidy.jsp").forward(req,resp);
            } catch (ServletException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    public void getProviderById(HttpServletRequest req, HttpServletResponse resp,String url){
        String id = req.getParameter("proid");
        if(!StringUtils.isNullOrEmpty(id)){
            ProviderService providerService = new ProviderServiceImpl();
            Provider provider = null;
            provider = providerService.getProviderById(id);
            req.setAttribute("provider",provider);
            try {
                req.getRequestDispatcher(url).forward(req,resp);
            } catch (ServletException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void del(HttpServletRequest req, HttpServletResponse resp) {
        String id = req.getParameter("proid");
        Map resultMap = new HashMap<>();
        if(!StringUtils.isNullOrEmpty(id)){
            ProviderService providerService = new ProviderServiceImpl();
            int flag = providerService.delProvider(Integer.parseInt(id));
            if(flag == 0){//删除成功
                resultMap.put("delResult","true");
            }else if(flag == -1){
                resultMap.put("delResult","false");
            }else if(flag == 1){
                resultMap.put("delResult",String.valueOf(flag));//有相订单,不能删除返回订单数
            }
        }else{
            resultMap.put("delResult","notexist");
        }
        resp.setContentType("application/json");
        PrintWriter writer = null;
        try {
            writer = resp.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }
        writer.write(JSONArray.toJSONString(resultMap));
        writer.flush();
        writer.close();
    }

    private void add(HttpServletRequest req, HttpServletResponse resp) {
        String proCode = req.getParameter("proCode");
        String proname = req.getParameter("proName");
        String proContact = req.getParameter("proContact");
        String proPhone = req.getParameter("proPhone");
        String proAddress = req.getParameter("proAddress");
        String proFax = req.getParameter("proFax");
        String proDesc = req.getParameter("proDesc");
        Provider provider = new Provider();
        provider.setProCode(proCode);
        provider.setProName(proName);
        provider.setProAddress(proAddress);
        provider.setProContact(proContact);
        provider.setProPhone(proPhone);
        provider.setProDesc(proDesc);
        provider.setProFax(proFax);
        provider.setCreationDate(new Date());

        ProviderService providerService = new ProviderServiceImpl();
        boolean flag = false;
        flag = providerService.add(provider);
        if(flag){
            try {
                resp.sendRedirect(req.getContextPath() + "/jsp/providerlist.jsp");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{
            try {
                req.getRequestDispatcher("provideradd.jsp").forward(req,resp);
            } catch (ServletException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    public void query(HttpServletRequest req, HttpServletResponse resp){
        String queryProCode = req.getParameter("queryProCode");
        String queryProname = req.getParameter("queryProName");
        List providerList = null;
        if(StringUtils.isNullOrEmpty(queryProName)){
            queryProName="";
        }
        if(StringUtils.isNullOrEmpty(queryProCode)){
            queryProCode="";
        }
        ProviderService providerService = new ProviderServiceImpl();
        providerList = providerService.getProviderList(queryProCode, queryProName);
        req.setAttribute("providerList",providerList);
        req.setAttribute("queryProCode",queryProCode);
        req.setAttribute("queryProName",queryProName);
        try {
            req.getRequestDispatcher("providerlist.jsp").forward(req,resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

效果

5.订单管理

订单管理跟之前也没有太大的出入,直接展示代码

dao
package com.zhou.dao.bill;

import com.mysql.cj.conf.ConnectionPropertiesTransform;
import com.zhou.polo.Bill;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public interface BillDao {
    
    public List getBillList(Connection connection,Bill bill) throws SQLException;

    
    public int getBillCountByProviderId(Connection connection,int providerId) throws SQLException;

    
    public Bill getBillById(Connection connection ,String id) throws SQLException;

    
    public boolean add(Connection connection,Bill bill) throws SQLException;

    
    public boolean del(Connection connection,String id) throws SQLException;


    
    public boolean modify(Connection connection,Bill bill) throws SQLException;
}
package com.zhou.dao.bill;


import com.mysql.cj.conf.ConnectionPropertiesTransform;
import com.mysql.cj.util.StringUtils;
import com.sun.xml.internal.ws.wsdl.ActionbasedOperationSignature;
import com.zhou.dao.baseDao;
import com.zhou.polo.Bill;
import sun.util.locale.provider.ResourceBundlebasedAdapter;

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


public class BillDaoImpl implements BillDao {
    @Override
    public List getBillList(Connection connection,Bill bill) throws SQLException {
        List billList = null;
        PreparedStatement  pstm = null;
        ResultSet rs = null;
        if (connection != null) {
            billList = new ArrayList<>();
            List list = new ArrayList<>();
            StringBuffer sql = new StringBuffer();
            sql.append("select b.*,p.proname as ProviderName from smbms_bill b,smbms_provider p where b.providerId = p.id");
            if(!StringUtils.isNullOrEmpty(bill.getProductName())){
                sql.append(" and ProviderName like ?");
                list.add("%" + bill.getProductName() + "%");
            }
            if(bill.getProviderId() > 0){
                sql.append(" and providerId = ?");
                list.add(bill.getProviderId());
            }
            if(bill.getIsPayment() > 0 ){
                sql.append(" and isPayment = ?");
                list.add(bill.getIsPayment());
            }

            rs = baseDao.execute(connection,sql.toString(),list.toArray(),rs,pstm);
            while(rs.next()){
                Bill _bill = new Bill();
                _bill.setId(rs.getInt("id"));
                _bill.setBillCode(rs.getString("billCode"));
                _bill.setProductName(rs.getString("productName"));
                _bill.setProductUnit(rs.getString("productUnit"));
                _bill.setProductDesc(rs.getString("productDesc"));
                _bill.setProductCount(rs.getBigDecimal("productCount"));
                _bill.setTotalPrice(rs.getBigDecimal("totalPrice"));
                _bill.setIsPayment(Integer.valueOf(rs.getString("isPayment")));
                _bill.setProviderName(rs.getString("providerName"));
                _bill.setCreatedBy(Integer.valueOf(rs.getString("createdBy")));
                _bill.setCreationDate(rs.getTimestamp("creationDate"));
                _bill.setModifyBy(rs.getInt("modifyBy"));
                _bill.setModifyDate(rs.getTimestamp("modifyDate"));
                _bill.setProviderId(rs.getInt("providerId"));
                billList.add(_bill);
            }
            baseDao.close(connection,pstm,rs);
        }
        return billList;
    }

    @Override
    public int getBillCountByProviderId(Connection connection, int providerId) throws SQLException {
        int count = 0;
        PreparedStatement pstm = null;
        ResultSet rs = null;
        if(connection != null){
            String sql = "select count(1) as billCount from smbms_bill where providerId = ?";
            Object[] params = {providerId};
            rs = baseDao.execute(connection,sql,params,rs,pstm);
            if(rs.next()){
                count = rs.getInt("billCount");
            }
        }
        baseDao.close(connection,pstm,null);
        return count;
    }

    @Override
    public Bill getBillById(Connection connection, String id)throws SQLException {
        Bill bill = null;
        PreparedStatement pstm = null;
        ResultSet rs = null;
        if(connection != null){
            String sql = "select b.*,p.proname as providerName from smbms_bill b,smbms_provider p where b.id = ? ";
            Object[] params = {id};
            rs = baseDao.execute(connection, sql, params, rs, pstm);
            if(rs.next()){
                bill = new Bill();
                bill.setId(rs.getInt("id"));
                bill.setBillCode(rs.getString("billCode"));
                bill.setProductName(rs.getString("productName"));
                bill.setProductUnit(rs.getString("productUnit"));
                bill.setProductDesc(rs.getString("productDesc"));
                bill.setProductCount(rs.getBigDecimal("productCount"));
                bill.setTotalPrice(rs.getBigDecimal("totalPrice"));
                bill.setProviderName(rs.getString("providerName"));
                bill.setIsPayment(Integer.valueOf(rs.getString("isPayment")));
                bill.setCreatedBy(Integer.valueOf(rs.getString("createdBy")));
                bill.setCreationDate(rs.getTimestamp("creationDate"));
                bill.setModifyBy(rs.getInt("modifyBy"));
                bill.setModifyDate(rs.getTimestamp("modifyDate"));
                bill.setProviderId(rs.getInt("providerId"));
            }
        }
        baseDao.close(connection,pstm,rs);
        return bill;
    }

    @Override
    public boolean add(Connection connection, Bill bill) throws SQLException {
        boolean flag = false;
        PreparedStatement pstm = null;
        if(connection != null){
            String sql = "insert into smbms_bill(id,billCode,productName,productDesc,productUnit,productCount," +
                    "totalPrice,isPayment,createdBy,creationDate,modifyBy,modifyDate,providerId) values(?,?,?,?,?,?,?,?,?,?,?,?)";
            Object[] params = {bill.getId(),bill.getBillCode(),bill.getProductName(),bill.getProductDesc(),bill.getProductUnit(),
                            bill.getProductCount(),bill.getTotalPrice(),bill.getIsPayment(),bill.getCreatedBy(),bill.getCreationDate(),
                            bill.getModifyBy(),bill.getModifyDate(), bill.getProviderId()};
            int execute = baseDao.execute(connection, sql, params, pstm);
            if(execute > 0){
                flag = true;
            }
        }
        baseDao.close(connection,pstm,null);
        return flag;
    }

    @Override
    public boolean del(Connection connection, String id) throws SQLException {
        boolean flag = false;
        PreparedStatement pstm = null;
        if(connection != null){
            String sql = "delete from smbms_bill where id = ?";
            Object[] params = {id};
            int execute = baseDao.execute(connection, sql, params, pstm);
            if(execute > 0) {
                flag = true;
            }
        }
        baseDao.close(connection,pstm,null);
        return flag;
    }

    @Override
    public boolean modify(Connection connection, Bill bill) throws SQLException {
        boolean flag = false;
        PreparedStatement pstm = null;
        if(connection != null){
            //update加上where,如果不加上where就会更改所有的记录
            String sql = "update smbms_bill set billCode = ?,productName = ?,productUnit = ?,productCount = ?,totalPrice = ?," +
                    "providerId = ?,isPayment = ? where id = ?";
            //参数顺序不能出错,数量要一致
            Object[] params = {bill.getBillCode(),bill.getProductName(),bill.getProductUnit(),bill.getProductCount(),bill.getTotalPrice(),
                    bill.getProviderId(), bill.getIsPayment(),bill.getId()};
            int execute = baseDao.execute(connection, sql, params, pstm);
            if(execute > 0){
                flag = true;
            }
        }
        baseDao.close(connection,pstm,null);
        return flag;
    }
}
 
service 
package com.zhou.service.Bill;

import com.zhou.polo.Bill;

import java.util.List;

public interface BillService {
    
    public List getBillList(Bill bill);

    

    public Bill getBillById(String id);

    
    public boolean add(Bill bill);


    
    public boolean del(String id);


    
    public boolean modify(Bill bill);
}
package com.zhou.service.Bill;

import com.zhou.dao.baseDao;
import com.zhou.dao.bill.BillDao;
import com.zhou.dao.bill.BillDaoImpl;
import com.zhou.polo.Bill;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public class BillServiceImpl implements BillService {
    private BillDao billDao;
    public BillServiceImpl(){
        billDao = new BillDaoImpl();
    }
    @Override
    public List getBillList(Bill bill) {
        List billList = null;
        Connection connection = null;
        connection = baseDao.getConnection();
        try {
            billList = billDao.getBillList(connection,bill);
        } catch (SQLException e) {
            e.printStackTrace();
        }finally{
            baseDao.close(connection,null,null);
        }
        return billList;
    }
    @Override
    public Bill getBillById(String id) {
        Bill bill = null;
        Connection connection = null;
        try {
            connection = baseDao.getConnection();
            bill = billDao.getBillById(connection,id);
        } catch (SQLException e) {
            e.printStackTrace();
        }finally{
            baseDao.close(connection,null,null);
        }
        return bill;
    }

    @Override
    public boolean add(Bill bill) {
        boolean flag = false;
        Connection conncetion = null;
        try {
            conncetion = baseDao.getConnection();
            billDao.add(conncetion,bill);
        } catch (SQLException e) {
            e.printStackTrace();
        }finally{
            baseDao.close(conncetion,null,null);
        }
        return flag;
    }

    @Override
    public boolean del(String id) {
        boolean flag = false;
        Connection connection  = null;
        try {
            connection = baseDao.getConnection();
            flag = billDao.del(connection,id);
        } catch (SQLException e) {
            e.printStackTrace();
        }finally{
            baseDao.close(connection,null,null);

        }
        return flag;
    }

    @Override
    public boolean modify(Bill bill) {
        boolean flag = false;
        Connection connection = null;
        try {
            connection = baseDao.getConnection();
            flag = billDao.modify(connection,bill);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            baseDao.close(connection,null,null);
        }
        return flag;
    }
}
servlet
package com.zhou.servlet.bill;

import com.alibaba.fastjson.JSONArray;
import com.mysql.cj.util.StringUtils;
import com.zhou.polo.Bill;
import com.zhou.polo.Provider;
import com.zhou.polo.User;
import com.zhou.service.Bill.BillService;
import com.zhou.service.Bill.BillServiceImpl;
import com.zhou.service.provider.ProviderService;
import com.zhou.service.provider.ProviderServiceImpl;
import com.zhou.util.Constants;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.hamcrest.core.Is;

import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.*;

public class BillServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        System.out.println("billmethod--> " + method);
        if(method != null && method.equals("query")){
            this.query(req,resp);
        }else if(method != null && method.equals("add")) {
            this.add(req,resp);
        }else if(method != null && method.equals("view")){
            this.getBillById(req,resp,"billview.jsp");
        }else if(method != null && method.equals("modify")){
            this.getBillById(req,resp,"billmodify.jsp");
        }else if(method != null && method.equals("delbill")){
            this.delBill(req,resp);
        }else if(method != null && method.equals("modifysave")){
            this.modify(req,resp);
        }else if(method != null && method.equals("getproviderlist")){
            this.getProviderList(req,resp);
        }
    }

    public void add(HttpServletRequest req, HttpServletResponse resp){
        String billCode = req.getParameter("billCode");
        String productName = req.getParameter("productName");
        String productUnit = req.getParameter("productUnit");
        String productCount = req.getParameter("productCount");
        String totalPrice = req.getParameter("totalPrice");
        String providerId = req.getParameter("providerId");
        String isPayment = req.getParameter("isPayment");
        Bill bill = new Bill();
        bill.setBillCode(billCode);
        bill.setProductName(productName);
        bill.setProductUnit(productUnit);
        bill.setProductCount(new BigDecimal(productCount).setScale(2,BigDecimal.ROUND_DOWN));
        bill.setTotalPrice(new BigDecimal(totalPrice).setScale(2,BigDecimal.ROUND_DOWN));
        bill.setProviderId(Integer.valueOf(providerId));
        bill.setIsPayment(Integer.valueOf(isPayment));
        bill.setCreatedBy(((User)req.getSession().getAttribute(Constants.USER_SESSION)).getId());
        bill.setCreationDate(new Date());


        BillService billService = new BillServiceImpl();
        if(billService.add(bill)){
            try {
                resp.sendRedirect(req.getContextPath() + "/jsp/bill.do?method=query");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{
            try {
                req.getRequestDispatcher("billadd.jsp").forward(req,resp);
            } catch (ServletException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    public void query(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("---------query start---------");
        List providerList = null;
        List billList = null;
        ProviderService providerService = new ProviderServiceImpl();
        BillService billService = new BillServiceImpl();
        providerList = providerService.getProviderList("","");
        //将信息发送到前端
        req.setAttribute("providerList",providerList);

        String queryProductName = req.getParameter("queryProductName");
        String queryProviderId = req.getParameter("queryProviderId");
        String queryIsPayment = req.getParameter("queryIsPayment");
        Bill bill = new Bill();

        if(StringUtils.isNullOrEmpty(queryProductName)){
            queryProductName = "";
        }
        if(StringUtils.isNullOrEmpty(queryIsPayment)){
            bill.setIsPayment(0);
        }else{
            bill.setIsPayment(Integer.valueOf(queryIsPayment));
        }

        if(StringUtils.isNullOrEmpty(queryProviderId)){
            bill.setProviderId(0);
        }else{
            bill.setProviderId(Integer.valueOf(queryProviderId));
        }
        billList = billService.getBillList(bill);
        req.setAttribute("billList",billList);
        req.setAttribute("queryProductName",queryProductName);
        req.setAttribute("queryProviderId",queryProviderId);
        req.setAttribute("queryIsPayment",queryIsPayment);
        try {
            req.getRequestDispatcher("billlist.jsp").forward(req,resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("---------query end---------");
    }

    public void getProviderList(HttpServletRequest req, HttpServletResponse resp){
        List providerList = new ArrayList<>();
        ProviderService providerService = new ProviderServiceImpl();
        providerList = providerService.getProviderList("","");
        //把providerList对象转换成json对象输出
        resp.setContentType("application/json");

        PrintWriter writer = null;
        try {
            writer = resp.getWriter();
            writer.write(JSONArray.toJSONString(providerList.toArray()));
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void getBillById(HttpServletRequest req, HttpServletResponse resp,String url){
        String id = req.getParameter("billid");
        Bill bill = null;
        if(!StringUtils.isNullOrEmpty(id)){
            BillService billService = new BillServiceImpl();
            bill = billService.getBillById(id);
            req.setAttribute("bill",bill);
            try {
                req.getRequestDispatcher(url).forward(req,resp);
            } catch (ServletException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void delBill(HttpServletRequest req, HttpServletResponse resp){
        String id = req.getParameter("billid");
        Map resultMap = new HashMap<>();
        if(StringUtils.isNullOrEmpty(id)){
            resultMap.put("delResult","notexist");
        }else{
            BillService billService = new BillServiceImpl();
            if(billService.del(id)){
                resultMap.put("delResult","true");
            }else{
                resultMap.put("delResult","false");
            }
        }
        resp.setContentType("application/json");
        PrintWriter writer = null;
        try {
            writer = resp.getWriter();
            writer.write(JSONArray.toJSONString(resultMap));
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    public void modify(HttpServletRequest req, HttpServletResponse resp){
        String id = req.getParameter("id");
        String billCode = req.getParameter("billCode");
        String productName = req.getParameter("productName");
        String productUnit = req.getParameter("productUnit");
        String productCount = req.getParameter("productCount");
        String totalPrice = req.getParameter("totalPrice");
        String providerId = req.getParameter("providerId");
        String isPayment = req.getParameter("isPayment");
        Bill bill = new Bill();
        bill.setId(Integer.valueOf(id));
        bill.setBillCode(billCode);
        bill.setProductName(productName);
        bill.setProductUnit(productUnit);
        bill.setProductCount(new BigDecimal(productCount).setScale(2,BigDecimal.ROUND_DOWN));
        bill.setTotalPrice(new BigDecimal(totalPrice).setScale(2,BigDecimal.ROUND_DOWN));
        bill.setProviderId(Integer.valueOf(providerId));
        bill.setIsPayment(Integer.valueOf(isPayment));
        bill.setModifyBy(((User)(req.getSession().getAttribute(Constants.USER_SESSION))).getId());
        bill.setModifyDate(new Date());

        BillService billService = new BillServiceImpl();
        if(billService.modify(bill)){
            try {
                resp.sendRedirect(req.getContextPath() + "/jsp/bill.do?method=query");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{
            try {
                req.getRequestDispatcher("billmodify.jsp").forward(req,resp);
            } catch (ServletException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
效果

6.总结

在花费了几天的时间之后,终于是自己动手将所有的代码都敲完了,期间出现了很多问题,也找错找了很长时间,幸运的是我最后还是找到了错误

在动手写相关的函数之前要先看jsp和js文件,与文件内部的方法相对应,不然很容易出现404在servlet写完之后一定要去web.xml注册相关的映射,否则servlet接收不到请求在sql语句中尽量使用PreparedStatement,可以避免SQL注入问题,除此之外,参数的个数以及顺序都要正确,否则sql语句会执行失败在涉及到多表查询的时候,sql语句一定要将所有涉及到的表加上,否则就会出现页面某一项没有数据的情况尽量不要将要序列化的数据定义成long类型,否则在转换成json数据的时候就会出错在导入依赖的时候,尽量让依赖的版本号相同出现错误的时候可以在代码中加上输出语句一层一层的排查错误,也可以看控制台的报错提示,还可以在浏览器控制台中或者网络等地方查看错误。进行模糊查询的时候,可以使用一个StringBuffer动态存储sql语句,list动态存储参数。如果要返回json数据,那么可以使用 Map

转载请注明:文章转载自 www.mshxw.com
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号