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

<!--LogoutServlet-->
    <servlet>
        <servlet-name>LogoutServlet</servlet-name>
        <servlet-class>com.ljl.servlet.user.LogoutServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>LogoutServlet</servlet-name>
        <url-pattern>/jsp/logout.do</url-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>SysFilter</filter-name>
        <filter-class>com.ljl.filter.SysFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>SysFilter</filter-name>
<!--        过滤访问jsp包下的所有页面-->
        <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

<!-- UpdatePwdServlet   -->
<servlet>
    <servlet-name>UpdatePwdServlet</servlet-name>
    <servlet-class>com.ljl.servlet.user.UpdatePwdServlet</servlet-class>
</servlet>
    <servlet-mapping>
        <servlet-name>UpdatePwdServlet</servlet-name>
        <url-pattern>/jsp/user.do</url-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"%>
        <div class="right">
            <div class="location">
                <strong>你现在所在的位置是:</strong>
                <span>用户管理页面</span>
            </div>
            <div class="search">
                  <form method="get" action="${pageContext.request.contextPath }/jsp/user.do">
               <input name="method" value="query" class="input-text" type="hidden">
                <span>用户名:</span>
                <input name="queryname" class="input-text"    type="text" value="${queryUserName }">
                
                <span>用户角色:</span>
                <select name="queryUserRole">
                  <c:if test="${roleList != null }">
                     <option value="0">--请选择--</option>
                     <c:forEach var="role" items="${roleList}">
                            <option <c:if test="${role.id == queryUserRole }">selected="selected"</c:if>
                            value="${role.id}">${role.roleName}</option>
                     </c:forEach>
                  </c:if>
                 </select>
                
                <input type="hidden" name="pageIndex" value="1"/>
                <input    value="查 询" type="submit" id="searchbutton">
                <a href="${pageContext.request.contextPath}/jsp/useradd.jsp" >添加用户</a>
            </form>
            </div>
            <!--用户-->
            <table class="providerTable" cellpadding="0" cellspacing="0">
                <tr class="firstTr">
                    <th width="10%">用户编码</th>
                    <th width="20%">用户名称</th>
                    <th width="10%">性别</th>
                    <th width="10%">年龄</th>
                    <th width="10%">电话</th>
                    <th width="10%">用户角色</th>
                    <th width="30%">操作</th>
                </tr>
                   <c:forEach var="user" items="${userList }" varStatus="status">
               <tr>
                  <td>
                  <span>${user.userCode }</span>
                  </td>
                  <td>
                  <span>${user.userName }</span>
                  </td>
                  <td>
                     <span>
                        <c:if test="${user.gender==1}">男</c:if>
                        <c:if test="${user.gender==2}">女</c:if>
                     </span>
                  </td>
                  <td>
                  <span>${user.age}</span>
                  </td>
                  <td>
                  <span>${user.phone}</span>
                  </td>
                  <td>
                     <span>${user.userRoleName}</span>
                  </td>
                  <td>
                  <span><a class="viewUser" href="javascript:;" userid=${user.id } username=${user.userName }><img src="${pageContext.request.contextPath }/images/read.png" alt="查看" title="查看"/></a></span>
                  <span><a class="modifyUser" href="javascript:;" userid=${user.id } username=${user.userName }><img src="${pageContext.request.contextPath }/images/xiugai.png" alt="修改" title="修改"/></a></span>
                  <span><a class="deleteUser" href="javascript:;" userid=${user.id } username=${user.userName }><img src="${pageContext.request.contextPath }/images/schu.png" alt="删除" title="删除"/></a></span>
                  </td>
               </tr>
            </c:forEach>
         </table>
         <input type="hidden" id="totalPageCount" value="${totalPageCount}"/>
         <c:import url="rollpage.jsp">
              <c:param name="totalCount" value="${totalCount}"/>
              <c:param name="currentPageNo" value="${currentPageNo}"/>
              <c:param name="totalPageCount" value="${totalPageCount}"/>
           </c:import>
        </div>
    </section>

<!--点击删除按钮后弹出的页面-->
<div class="zhezhao"></div>
<div class="remove" id="removeUse">
    <div class="removerChid">
        <h2>提示</h2>
        <div class="removeMain">
            <p>你确定要删除该用户吗?</p>
            <a href="#" id="yes">确定</a>
            <a href="#" id="no">取消</a>
        </div>
    </div>
</div>

<%@include file="/jsp/common/foot.jsp" %>
<script type="text/javascript" src="${pageContext.request.contextPath }/js/userlist.js"></script>

3.分页列表

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
   
</script>
</head>
<body>
      <div class="page-bar">
         <ul class="page-num-ul clearfix">
            <li>共${param.totalCount }条记录&nbsp;&nbsp; ${param.currentPageNo }/${param.totalPageCount }页</li>
            <c:if test="${param.currentPageNo > 1}">
               <a href="javascript:page_nav(document.forms[0],1);">首页</a>
               <a href="javascript:page_nav(document.forms[0],${param.currentPageNo-1});">上一页</a>
            </c:if>
            <c:if test="${param.currentPageNo < param.totalPageCount }">
               <a href="javascript:page_nav(document.forms[0],${param.currentPageNo+1 });">下一页</a>
               <a href="javascript:page_nav(document.forms[0],${param.totalPageCount });">最后一页</a>
            </c:if>
            &nbsp;&nbsp;
         </ul>
       <span class="page-go-form"><label>跳转至</label>
        <input type="text" name="inputPage" id="inputPage" class="page-key" />页
        <button type="button" class="page-btn" onClick='jump_to(document.forms[0],document.getElementById("inputPage").value)'>GO</button>
      </span>
      </div> 
</body>
<script type="text/javascript" src="${pageContext.request.contextPath }/js/rollpage.js"></script>
</html>

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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值