SMBMS 超市订单管理系统

SMBMS

超市订单管理系统

学完JavaWeb后必须熟悉练习的一个小项目:如有需要源码的同学可以联系我或在下方评论,这边文章的目的在于帮助你了解项目开发的大致过程.

1.项目搭建准备工作

Tomcat 3.6.1

MySQL 5.7.1

IDEA

2.登录功能实现

通过用户名和密码获取用户登录

3.登录功能优化

3.1注销功能

思路:移除Session,返回登录页

package com.ljl.servlet.user;

import com.ljl.util.Constants;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LogoutServlet extends HttpServlet {
     

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
     
        //移除Session 注销优化
        req.getSession().removeAttribute(Constants.USER_SESSION);
        //退出后重定向到登录界面
        resp.sendRedirect(req.getContextPath()+"/login.jsp");
    }

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

注册XML


    <servlet>
        <servlet-name>LogoutServletservlet-name>
        <servlet-class>com.ljl.servlet.user.LogoutServletservlet-class>
    servlet>
    <servlet-mapping>
        <servlet-name>LogoutServletservlet-name>
        <url-pattern>/jsp/logout.dourl-pattern>
    servlet-mapping>

3.2登陆拦截优化(只有登录后才能进入后台页面)

编写过滤器,并注册

public class SysFilter implements Filter {
     
    public void init(FilterConfig filterConfig) throws ServletException {
     

    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
     
//        强转才能获取Session
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        //获取Session
        Object attribute = request.getSession().getAttribute(Constants.USER_SESSION);
        //判断Session是否为空 即未登录或者已注销
        if (attribute == null) {
     
//            错误访问就重定向跳转错误页面
            response.sendRedirect("/smbms/error.jsp");
        } else {
     

//       继续过滤
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }
    public void destroy() {
     

    }
}

    <filter>
        <filter-name>SysFilterfilter-name>
        <filter-class>com.ljl.filter.SysFilterfilter-class>
    filter>
    <filter-mapping>
        <filter-name>SysFilterfilter-name>

        <url-pattern>/jsp/*url-pattern>
    filter-mapping>

4.密码修改

1.写项目,建议从底层向上写

dao–>service–>servlet–>jsp 架构清楚

2.UserDao接口

//修改密码功能实现
public int updatePwd(Connection connection,int id ,String pwd);

3.UserDao实现

public int updatePwd(Connection connection, int id, String pwd) {
     
   PreparedStatement preparedStatement=null;
   int execute =0;
    //非空判断很重要
    if(connection!=null){
     

        try {
     
            String sql="update smbms_user set userPassword= ? where id= ? ;";
            //按照sql?查询顺序传参  易错点  改这个BUG花了两天  最后Debug找到了错误点
            Object [] params ={
     pwd,id};

            execute = BaseDao.execute(connection, preparedStatement, sql, params);
            System.out.println(execute);
        } catch (SQLException e) {
     
            e.printStackTrace();
        }finally {
     
            BaseDao.closeResource(null,preparedStatement,null);
        }
    }
    return execute;
}

4.UserService接口

//修改密码
public boolean updatePwd(String pwd ,int id) ;

5.UserService实现

public boolean updatePwd( String pwd ,int id) {
     

    Connection connection=null;
    boolean flag = false;
    try {
     
        connection = BaseDao.getConnection();
        if (userDao.updatePwd(connection, id, pwd)>0){
     
            flag=true;
        }
    } catch (ClassNotFoundException e) {
     
        e.printStackTrace();
    } catch (SQLException e) {
     
        e.printStackTrace();
    }finally{
     
        BaseDao.closeResource(connection,null,null);
    }
    return flag;

}

6.UpPwdServlet实现

 public void updatePwd(HttpServletRequest req, HttpServletResponse resp) {
     

        //获取Session信息
        Object o = req.getSession().getAttribute(Constants.USER_SESSION);

        //获取前端输入的新密码
        String newpassword = req.getParameter("newpassword");
        boolean flag = false;
        if (o != null && newpassword != null) {
     

            UserService userService = new UserServiceImpl();

            try {
     
                flag = userService.updatePwd(((User) o).getId(), newpassword);
            } catch (SQLException e) {
     
                e.printStackTrace();
            }


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

7.注册xml


<servlet>
    <servlet-name>UpdatePwdServletservlet-name>
    <servlet-class>com.ljl.servlet.user.UpdatePwdServletservlet-class>
servlet>
    <servlet-mapping>
        <servlet-name>UpdatePwdServletservlet-name>
        <url-pattern>/jsp/user.dourl-pattern>
    servlet-mapping>

8.ajax验证旧密码(实现Servlet复用)

oldpassword.on("blur",function(){
     
   $.ajax({
     
      type:"GET",
      url:path+"/jsp/user.do",
      data:{
     method:"pwdmodify",oldpassword:oldpassword.val()},
      dataType:"json",
      success:function(data){
     
         if(data.result == "true"){
     //旧密码正确
            validateTip(oldpassword.next(),{
     "color":"green"},imgYes,true);
         }else if(data.result == "false"){
     //旧密码输入不正确
            validateTip(oldpassword.next(),{
     "color":"red"},imgNo + " 原密码输入不正确",false);
         }else if(data.result == "sessionerror"){
     //当前用户session过期,请重新登录
            validateTip(oldpassword.next(),{
     "color":"red"},imgNo + " 当前用户session过期,请重新登录",false);
         }else if(data.result == "error"){
     //旧密码输入为空
            validateTip(oldpassword.next(),{
     "color":"red"},imgNo + " 请输入旧密码",false);
         }
      },
      error:function(data){
     
         //请求出错
         validateTip(oldpassword.next(),{
     "color":"red"},imgNo + " 请求错误",false);
      }
   });
 //    验证旧密码
    public void pwdModify(HttpServletRequest req, HttpServletResponse resp) {
     
        //从Session中获取ID
        Object o = req.getSession().getAttribute(Constants.USER_SESSION);
//      获取前端输入的旧密码
        String oldpassword = req.getParameter("oldpassword");

//        万能Map  结果集存储数据
        Map<String, String> resultMap = new HashMap<String, String>();

        if (o == null) {
     
//           用户Session失效时返回结果
            resultMap.put("result", "sessionerror");
        } else if (StringUtils.isNullOrEmpty(oldpassword)) {
     
//           用户输入密码为空时
            resultMap.put("result", "error");
        } else {
     
//            获取旧密码
            String userPassword = ((User) o).getUserPassword();

            if (oldpassword.equals(userPassword)) {
     //  用户密码输入正确
                resultMap.put("result", "true");
            } else {
     //用户密码输入错误
                resultMap.put("result", "false");
            }
        }

        try {
     
            //设置响应的格式以json传回前端
            resp.setContentType("application/json");
            PrintWriter writer = resp.getWriter();
//           阿里巴巴工具类将结果集转换成json字符串
            writer.write(JSONArray.toJSONString(resultMap));
            writer.flush();
            writer.close();
        } catch (IOException e) {
     
            e.printStackTrace();
        }



    }

5.用户管理实现

5.1资源准备

1.导入分页的工具类

package com.ljl.util;

public class PageSupport {
     
   //当前页码-来自于用户输入
   private int currentPageNo = 1;
   
   //总数量(表)
   private int totalCount = 0;
   
   //页面容量
   private int pageSize = 0;
   
   //总页数-totalCount/pageSize(+1)
   private int totalPageCount = 1;

   public int getCurrentPageNo() {
     
      return currentPageNo;
   }

   public void setCurrentPageNo(int currentPageNo) {
     
      if(currentPageNo > 0){
     
         this.currentPageNo = currentPageNo;
      }
   }

   public int getTotalCount() {
     
      return totalCount;
   }

   public void setTotalCount(int totalCount) {
     
      if(totalCount > 0){
     
         this.totalCount = totalCount;
         //设置总页数
         this.setTotalPageCountByRs();
      }
   }
   public int getPageSize() {
     
      return pageSize;
   }

   public void setPageSize(int pageSize) {
     
      if(pageSize > 0){
     
         this.pageSize = pageSize;
      }
   }

   public int getTotalPageCount() {
     
      return totalPageCount;
   }

   public void setTotalPageCount(int totalPageCount) {
     
      this.totalPageCount = totalPageCount;
   }
   
   public void setTotalPageCountByRs(){
     
      if(this.totalCount % this.pageSize == 0){
     
         this.totalPageCount = this.totalCount / this.pageSize;
      }else if(this.totalCount % this.pageSize > 0){
     
         this.totalPageCount = this.totalCount / this.pageSize + 1;
      }else{
     
         this.totalPageCount = 0;
      }
   }
   
}

2.用户列表页面导入

<%@ page language="java" contentType="text/html; charset=UTF-8"
   pageEncoding="UTF-8"%>
<%@include file="/jsp/common/head.jsp"%>
        
你现在所在的位置是: 用户管理页面
用户编码 用户名称 性别 年龄 电话 用户角色 操作
${user.userCode } ${user.userName } ${user.age} ${user.phone} ${user.userRoleName} 查看 修改 删除

提示

你确定要删除该用户吗?

确定 取消
<%@include file="/jsp/common/foot.jsp" %>

3.分页列表

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>




Insert title here



      

5.2获取用户数量

1.UserDao

//通过用户名或者角色查询用户总数功能
int getUserNums(Connection connection,String userName,int userRole)throws SQLException;

2.UserDaoImpl

//通过用户名或者角色查询用户总数功能
    public int getUserNums(Connection connection, String userName, int userRole) throws SQLException {
     
        PreparedStatement pstm = null;
        ResultSet rs = null;
        int count =0;
        if (connection!=null) {
     
            //连表查询 拼接字符串
            StringBuffer sql = new StringBuffer();
            sql.append("select count(1) as count from smbms_user as u,smbms_role as r where u.userRole=r.id");

            //存储参数
            ArrayList<Object> list = new ArrayList<Object>();

            if (!StringUtils.isNullOrEmpty(userName)) {
     //用户名不为空 即当需要通过用户名查询总数时
                sql.append(" and u.userName like ?");
                //模糊查询的参数
                list.add("%" + userName + "%");//index=0

            }
            if (userRole > 0) {
     //角色不为空 即当需要通过角色查询总数时
                sql.append(" and u.userRole = ?");
                list.add(userRole); //index=1

            }
//         list转换成数组
            Object[] objects = list.toArray();

//            输出最后的完整sql语句
            System.out.println("UserDaoImpl-->getUserNums():"+sql.toString());
//       调用工具类的查询方法
            rs = BaseDao.execute(connection, pstm, rs, sql.toString(), objects);
            //获取查询后总数
            if (rs.next()) {
     
                count = rs.getInt("count");
            }
//            关闭资源
            BaseDao.closeResource(null,pstm,rs);
        }
        return count;
    }

3.UserService

//   通过用户名或者角色查询用户数量
  int getUserNums(String userName,int userRole);

4.UserServiceImpl

public int getUserNums(String userName, int userRole) {
     
    Connection connection =null;
    int count = 0;
    try {
     
        connection= BaseDao.getConnection();

         count = userDao.getUserNums(connection, userName, userRole);
    } catch (ClassNotFoundException e) {
     
        e.printStackTrace();
    } catch (SQLException e) {
     
        e.printStackTrace();
    }finally {
     
        BaseDao.closeResource(connection,null,null);
    }
    return count;
}

5.单元测试 检测查询是否出错

@Test
public void test(){
     
    UserServiceImpl userService = new UserServiceImpl();
    int count = userService.getUserNums("赵", 2);
    System.out.println(count);
}

5.3获取用户列表

1.UserDao

//通过条件查询获取用户列表
List<User> getUserList(Connection connection,String userName,int userRole,int currentPageNo,int pageSize)throws SQLException;

2.UserDaoImpl

public List<User> getUserList(Connection connection, String userName, int userRole, int currentPageNo, int pageSize) throws SQLException {
     
         PreparedStatement pstm = null;
         ResultSet rs = null;

         StringBuffer sql =new StringBuffer();

        List<User> userList = new ArrayList<User>();
      if (connection!=null) {
     
          ArrayList<Object> list = new ArrayList<Object>();
          sql.append("select u.*,r.roleName from smbms_user as u ,smbms_role as r where u.userRole=r.id;");

          if (!StringUtils.isNullOrEmpty(userName)) {
     
              sql.append(" and u.userName like ?");
              list.add("%" + userName + "%");
          }

          if (userRole > 0) {
     
              sql.append(" and r.userRole = ?");
         list.add(userRole);
          }
//          数据库中分页使用limit
          sql.append(" order by creationDate DESC limit ?,? ");

          currentPageNo =(currentPageNo-1)*pageSize;
          list.add(currentPageNo);

          list.add(pageSize);

          Object[] params = list.toArray();
          System.out.println("UserDaoImpl-->sql:"+sql);

          rs = BaseDao.execute(connection, pstm, rs, sql.toString(), params);

          if (rs.next()){
       //取值存放在list中
              User _user =new User();
              _user.setId(rs.getInt("id"));
              _user.setUserCode(rs.getString("userCode"));
              _user.setUserName(rs.getString("userName"));
              _user.setUserPassword(rs.getString("userPassword"));
              _user.setGender(rs.getInt("gender"));
              _user.setBirthday(rs.getDate("birthday"));
              _user.setPhone(rs.getString("phone"));
              _user.setAddress(rs.getString("address"));
              _user.setUserRole(rs.getInt("userRole"));
              _user.setCreatedBy(rs.getInt("createdBy"));
              _user.setCreationDate(rs.getTimestamp("creationDate"));
              _user.setModifyBy(rs.getInt("modifyBy"));
              _user.setModifyDate(rs.getTimestamp("modifyDate"));
              _user.setUserRoleName(rs.getString("roleName"));
              userList.add(_user);
          }
          BaseDao.closeResource(null,pstm,rs);

      }
      return userList;
    }

3.UserService

//根据条件获取用户列表
List<User> getUserList(String queryUserName,int queryUserRole,int currentPageNo,int pageSize);

4.UserServiceImpl

public List<User> getUserList(String queryUserName, int queryUserRole, int currentPageNo, int pageSize) {
     
    Connection connection =null;
    List<User> userList =null;

    System.out.println("queryUserName:"+queryUserName);
    System.out.println("queryUserRole:"+queryUserRole);
    System.out.println("currentPageNo:"+currentPageNo);
    System.out.println("pageSize:"+pageSize);
    try {
     
        connection =BaseDao.getConnection();
        userList = userDao.getUserList(connection, queryUserName, queryUserRole, currentPageNo, pageSize);

    } catch (ClassNotFoundException e) {
     
        e.printStackTrace();
    } catch (SQLException e) {
     
        e.printStackTrace();
    }finally {
     
        BaseDao.closeResource(connection,null,null);
    }
    return userList;
}

5.4获取角色列表

1.RoleDao

//    获取角色列表
    List<Role> getRoleList(Connection connection) throws SQLException;

2.RoleDaoImpl

public class RoleDaoImpl implements RoleDao {
     
    public List<Role> getRoleList(Connection connection) throws SQLException {
     
        PreparedStatement pstm = null;
        ResultSet rs = null;
        List<Role> roleList = new ArrayList<Role>();
        if (connection!=null){
     
            String sql ="select r.* from smbms_role as r  ;";
            Object [] params ={
     };

            rs = BaseDao.execute(connection, pstm, rs, sql, params);

            while (rs.next()){
     
              Role _role = new Role();
             _role.setId(rs.getInt("id"));
             _role.setRoleName(rs.getString("roleName"));
             _role.setRoleCode(rs.getString("roleCode"));
             roleList.add(_role);

            }

        }
        return roleList;
    }

3.RoleService

//    获取角色列表
    List<Role> getRoleList();

4.RoleServiceImpl

public class RoleServiceImpl implements RoleService {
     
    RoleDao roleDao =null;
    public RoleServiceImpl(){
     
        roleDao =new RoleDaoImpl();
    }
    public List<Role> getRoleList() {
     
        Connection connection =null;
        List<Role> roleList =null;

        try {
     
            connection = BaseDao.getConnection();
            roleList = roleDao.getRoleList(connection);
        } catch (ClassNotFoundException e) {
     
            e.printStackTrace();
        } catch (SQLException e) {
     
            e.printStackTrace();
        }finally {
     
            BaseDao.closeResource(connection,null,null);
        }
return roleList;

    }

5.单元测试

//    测试
    @Test
    public void test(){
     
        RoleServiceImpl roleService = new RoleServiceImpl();
        List<Role> roleList  = roleService.getRoleList();
        for (Role role : roleList) {
     
            System.out.println(role.getRoleName());
        }


    }

6.UserServlet

1.获取用户前端传入的数据(查询)

2.判断请求是否需要执行,看参数的值判断一些非法输入

3.为了实现分页,计算出总页面和当前页面,页面的大小…

4.用户列表展示

5.返回前端

//   用户管理 (重点,难点)
    public void query(HttpServletRequest req, HttpServletResponse resp){
     
        //获取前端传入的参数
        String queryName = req.getParameter("queryname");
        String temp = req.getParameter("queryUserRole");
        String pageIndex = req.getParameter("pageIndex");
        int queryUserRole =0;
        //        手动传输设置参数
        int currePageNum =1;
        int pageSize =5;


        if (temp!=null&&!temp.equals("")){
     
            queryUserRole=Integer.parseInt(temp);
        }
        if(queryName==null){
     
         queryName="";
        }
        if (pageIndex!=null){
     
             currePageNum = Integer.parseInt(pageIndex);
        }


        UserServiceImpl userService = new UserServiceImpl();
//        获取总用户数量
        int userNums = userService.getUserNums(queryName, queryUserRole);
//       获取总页数
        int totalPageCount =(int)Math.ceil((double)userNums/pageSize);
        System.out.println((double) userNums/pageSize);
        System.out.println(totalPageCount);
//        分页支持
        PageSupport pageSupport =new PageSupport();
        pageSupport.setCurrentPageNo(currePageNum);
//        pageSupport.setTotalCount(userNums);
        pageSupport.setPageSize(pageSize);
//        pageSupport.setTotalPageCount(totalPageCount);
        pageSupport.setTotalCount(userNums);

        if (currePageNum<1){
     
            currePageNum=1;
        }
        if (currePageNum>totalPageCount){
     
            currePageNum=totalPageCount;
        }
//    获取用户列表
        List<User> userList = userService.getUserList(queryName,queryUserRole, currePageNum, pageSize);
        req.setAttribute("userList",userList);

        RoleServiceImpl roleService = new RoleServiceImpl();
//        获取角色列表
        List<Role> roleList = roleService.getRoleList();
        req.setAttribute("roleList",roleList);
//         获取总页数


//        用户列表展示
        req.setAttribute("queryname",queryName);
        req.setAttribute("queryUserRole",queryUserRole);
//        req.setAttribute("inputPage",inputPage);


        req.setAttribute("totalCount",userNums);
        req.setAttribute("currentPageNo",currePageNum);
     req.setAttribute("totalPageCount",totalPageCount);

 //5.返回前端
        try {
     
            req.getRequestDispatcher("userlist.jsp").forward(req,resp);
        } catch (ServletException e) {
     
            e.printStackTrace();
        } catch (IOException e) {
     
            e.printStackTrace();
        }

    }

5.5添加用户实现

1.UserDao

//通过用户对象添加用户
int addUser(Connection connection,User user) throws SQLException;

2.UserDaoImpl

//  通过用户对象添加用户
    public int addUser(Connection connection, User user) throws SQLException {
     
        PreparedStatement pstm=null;
        int execute =0;
        if (connection!=null){
     
            String sql="insert into smbms_user(userCode,userName,userPassword,gender,birthday,phone,address,userRole)values(?,?,?,?,?,?,?,?);";

            Object [] params ={
     user.getUserCode(),user.getUserName(),user.getUserPassword(),user.getGender(),user.getBirthday(),user.getPhone(),user.getAddress(),user.getUserRole()};

            execute = BaseDao.execute(connection, pstm, sql, params);

            BaseDao.closeResource(null,pstm,null);
            System.out.println("UserDaoImpl-->addUser()-->sql:"+sql);
        }
        return execute;
    }

3.UserService

//根据用户信息添加用户
boolean addUser(User user);

  //查询登录用户名是否已经存在
    User selectUserCodeExist(String userCode,String passWord);

4.UserServiceImpl

  public boolean addUser(User user) {
     
        Connection connection =null;
        boolean flag = false;
        try {
     
            connection= BaseDao.getConnection();
//            手动开启事务(关闭事务自动提交)   ACID原则
            connection.setAutoCommit(false);
            int i = userDao.addUser(connection, user);
            System.out.println(i);
//           提交事务
            connection.commit();
            if (i>0){
     
                flag=true;
                System.out.println("add success");
            }else{
     
                System.out.println("add failed");
            }
        } catch (ClassNotFoundException e) {
     
            e.printStackTrace();
        } catch (SQLException e) {
     
            try {
     
//                设置事务回滚  防止数据出错
                connection.rollback();
                System.out.println("rollback");
            } catch (SQLException ex) {
     
                ex.printStackTrace();
            }
            e.printStackTrace();
        }finally {
     
            BaseDao.closeResource(connection,null,null);
        }
return flag;
    }

    public User selectUserCodeExist(String userCode,String passWord) {
     
        Connection connection =null;
        User user =null;
        try {
     
            connection=BaseDao.getConnection();
            user = userDao.getLoginUser(connection, userCode, passWord);
        } catch (ClassNotFoundException e) {
     
            e.printStackTrace();
        } catch (SQLException e) {
     
            e.printStackTrace();
        }finally {
     
            BaseDao.closeResource(connection,null,null);
        }
        return user;
    }

5.UserServlet

//    添加用户界面需要获取角色列表
    private void getrolelist(HttpServletRequest req, HttpServletResponse resp) throws IOException {
     

        List<Role> roleList =null;
                RoleServiceImpl roleService = new RoleServiceImpl();
        roleList = roleService.getRoleList();
        resp.setContentType("application/json");
        PrintWriter writer = resp.getWriter();
//        将roleList转换成JSON字符串输出到前端
        writer.write(JSONArray.toJSONString(roleList));
        writer.flush();
        writer.close();
    }
//    添加用户时验证用户名是否已经存在或为空
    private void ucexist(HttpServletRequest req, HttpServletResponse resp) throws IOException {
     
        String userCode = req.getParameter("userCode");
        Object attribute = req.getSession().getAttribute(Constants.USER_SESSION);
        HashMap<Object, Object> resultMap = new HashMap<Object, Object>();

        if (StringUtils.isNullOrEmpty(userCode)){
     
            resultMap.put("userCode","exist");
        }else{
     
            UserService userService = new UserServiceImpl();
            User user = userService.selectUserCodeExist(userCode, ((User)attribute).getUserPassword());

            if (user!=null){
     
           resultMap.put("userCode","exist");
            }else{
     
                resultMap.put("userCode","notExist");
            }
        }
//       将resultMap转换成JSON字符串输出到前端
        resp.setContentType("application/json");
        PrintWriter writer = resp.getWriter();
        writer.write(JSONArray.toJSONString(resultMap));
        writer.flush();
        writer.close();

    }



    //    添加用户
    public void addUser(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
     
       User user =new User();
        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 phone = req.getParameter("phone");
        String address = req.getParameter("address");
        String userRole = req.getParameter("userRole");


        user.setUserCode(userCode);
        user.setUserName(userName);
        user.setUserPassword(userPassword);
        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.setCreatedBy(((User)req.getSession().getAttribute(Constants.USER_SESSION)).getId());
        UserService userService = new UserServiceImpl();

        if(userService.addUser(user)){
     
           resp.sendRedirect(req.getContextPath()+"/jsp/user.do?method=query");
        }else{
     
            req.getRequestDispatcher("useradd.jsp").forward(req,resp);
        }

    }
    }

tips:

UserServiceImpl 类提交事务之前完成对数据库的操作 当时粗心将操作方法放在了事务提交之后 导致bug

           connection.setAutoCommit(false);
            int i = userDao.addUser(connection, user);
            System.out.println(i);
//           提交事务
            connection.commit();

5.6删除用户实现

1.UserDao

//通过被删除用户的id删除这个用户
int delUserById(Connection connection,int delId) throws SQLException;

2.UserDaoImpl

//  通过用户ID删除用户
    public int delUserById(Connection connection, int delId) throws SQLException {
     
        int execute =0;
        PreparedStatement pstm =null;
        if (connection!=null){
     
            String sql="delete from smbms_user where id=?";
          Object [] params ={
     delId};

            execute = BaseDao.execute(connection, pstm, sql, params);
            System.out.println("delUserById-->sql:"+sql);
          BaseDao.closeResource(null,pstm,null);

        }
    return execute;
    }

3.UserService

//根据ID删除本用户
boolean delUserById(int delId);

4.UserServiceImpl

public boolean delUserById(int delId) {
     
    Connection connection=null;
    boolean flag = false;
    try {
     
        connection = BaseDao.getConnection();
        connection.setAutoCommit(false);
        int i = userDao.delUserById(connection, delId);
        connection.commit();
        if (i>0){
     
            flag=true;
        }

    } catch (ClassNotFoundException e) {
     
        e.printStackTrace();
    } catch (SQLException e) {
     
        e.printStackTrace();
        try {
     
            connection.rollback();
        } catch (SQLException ex) {
     
            ex.printStackTrace();
        }
    }finally {
     
        BaseDao.closeResource(connection,null,null);
    }
  return flag;
}

5.UserServlet

 //删除用户
    public void delUserById(HttpServletRequest req, HttpServletResponse resp) throws IOException {
     
        String temp = req.getParameter("uid");
        int delId =0;
        if (!StringUtils.isNullOrEmpty(temp)){
     
            delId=Integer.valueOf(temp);
        }else {
     
            delId=0;
        }
        HashMap<Object, Object> resultMap = new HashMap<Object, Object>();
        if (delId<=0){
     
            resultMap.put("delResult","notexist");
        }
        UserService userService = new UserServiceImpl();
        boolean b = userService.delUserById(delId);
        if (b){
     
            resultMap.put("delResult","true");
        }else {
     
            resultMap.put("delResult","false");
        }
        resp.setContentType("application/json");
        PrintWriter writer = resp.getWriter();
        writer.write(JSONArray.toJSONString(resultMap));
        writer.flush();
        writer.close();
    }
}

你可能感兴趣的:(java,web,app)