smbms項(xiàng)目(二)

根據(jù)用戶id查詢用戶信息(用戶管理的查看操作)

1. UserDao

    //通過(guò)用戶id查看用戶
    public User getUser(Connection connection,int id) throws SQLException;

2. UserDaoImpl

//通過(guò)用戶id查看用戶
    public User getUser(Connection connection,int id) throws SQLException {
        PreparedStatement pstm = null;
        ResultSet rs = null;
        User user = new User();
        if(connection != null) {
            String sql = "select * from smbms_user u,smbms_role r where u.userRole = r.id and u.id = ?";
            Object[] params = {id};

            rs = BaseDao.execute(connection, pstm, rs, sql, params);
            System.out.println(sql + "---- ?=" + id);
            if(rs.next()) {
                user.setId(rs.getInt("id"));
                user.setUserName(rs.getString("userName"));
                user.setUserRoleName(rs.getString("roleName"));
                user.setUserRole(rs.getInt("userRole"));
                user.setUserCode(rs.getString("userCode"));
                user.setUserPassword(rs.getString("userPassword"));
                user.setPhone(rs.getString("phone"));
                user.setGender(rs.getInt("gender"));
                user.setBirthday(rs.getDate("birthday"));
                user.setAddress(rs.getString("address"));
                user.setCreatedBy(rs.getInt("createdBy"));
                user.setCreationDate(rs.getTimestamp("creationDate"));
                user.setModifyBy(rs.getInt("modifyBy"));
                user.setModifyDate(rs.getTimestamp("modifyDate"));
                user.setIdPicPath(rs.getString("idPicPath"));
                user.setWorkPicPath(rs.getString("workPicPath"));
            }
            //關(guān)閉資源
            BaseDao.closeResource(null,pstm,rs);
        }
        return user;
    }

3. UserService

    //根據(jù)用戶id查詢?cè)撚脩粜畔?    public User getUser(int id);

4. UserServiceImpl

//根據(jù)用戶id查詢?cè)撚脩粜畔?    public User getUser(int id) {
        Connection connection = null;
        User user = null;

        try {
            connection = BaseDao.getConnection();
            user = userDao.getUser(connection, id);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            BaseDao.closeResource(connection,null,null);
        }

        return user;
    }

    @Test
    public void test() {//測(cè)試
        UserServiceImpl userService = new UserServiceImpl();
        User user = userService.getUser(50);
        System.out.println(user.getUserName() + user.getId() + user.getUserRoleName());
    }

5. Servlet

//根據(jù)用戶id查詢?cè)撚脩粜畔?    public void getUser(HttpServletRequest req, HttpServletResponse resp) {
        //獲得前端數(shù)據(jù)
        String tempid = req.getParameter("uid");
        if(tempid != null) {//字符不為空
            int id = Integer.parseInt(tempid);
            //業(yè)務(wù)層處理事務(wù)
            UserServiceImpl userService = new UserServiceImpl();
            User user = userService.getUser(id);
            System.out.println(user.getId());
            //返回前端
            req.setAttribute("user",user);
            try {
                req.getRequestDispatcher("/jsp/userview.jsp").forward(req,resp);
            } catch (ServletException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

6. xml

    <servlet-mapping>
        <servlet-name>UserServlet</servlet-name>
        <url-pattern>/user/view</url-pattern>
    </servlet-mapping>

根據(jù)用戶id修改用戶信息(用戶管理的修改操作)

  • 修改頁(yè)面的跳轉(zhuǎn)

1. servlet

//根據(jù)用戶id查詢?cè)撚脩粜畔?    public User getUser(HttpServletRequest req, HttpServletResponse resp) {
        //獲得前端數(shù)據(jù)征讲,用戶的id
        String tempid = req.getParameter("uid");
        User user = null;
        if(tempid != null) {//字符不為空
            int id = Integer.parseInt(tempid);
            //業(yè)務(wù)層處理事務(wù)
            UserServiceImpl userService = new UserServiceImpl();
            user = userService.getUser(id);
            System.out.println(user.getId());
        }
        return user;
    }

//根據(jù)用戶id得到用戶信息并且返回到usermodify頁(yè)面
    public void getUserForModify(HttpServletRequest req, HttpServletResponse resp) {
        User user = this.getUser(req, resp);
        //返回前端
        req.setAttribute("user",user);
        try {
            req.getRequestDispatcher("/jsp/usermodify.jsp").forward(req,resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

2. xml

    <servlet-mapping>
        <servlet-name>UserServlet</servlet-name>
        <url-pattern>/user/usermodify</url-pattern>
    </servlet-mapping>
  • 得到角色列表

1. servlet

   //獲得角色列表嗜桌,提供角色選擇
   public void getRoleList(HttpServletRequest req, HttpServletResponse resp) {
       RoleServiceImpl roleService = new RoleServiceImpl();
       List<Role> roleList = roleService.getRoleList();
       //給頁(yè)面返回一個(gè)json對(duì)象的數(shù)據(jù)
       resp.setContentType("application/json");
       try {
           PrintWriter writer = resp.getWriter();
           /*
           JSONArray,工具類肥隆,轉(zhuǎn)換格式闺属,將List轉(zhuǎn)換為json
            */
           writer.write(JSONArray.toJSONString(roleList));
           writer.flush();
           writer.close();
       } catch (IOException e) {
           e.printStackTrace();
       }

   }

2. xml

    <servlet-mapping>
        <servlet-name>UserServlet</servlet-name>
        <url-pattern>/user/getrolelist.html</url-pattern>
    </servlet-mapping>
  • 提交更改用戶信息门岔,表單提交

1. UserDao

    //通過(guò)用戶User更改用戶信息臭增,在user中保存好要修改的內(nèi)容
    public int updateUser(Connection connection,User user) throws SQLException;

2. UserDaoImpl

    //通過(guò)用戶user更改用戶信息渣淳,user中保存好要修改的內(nèi)容讲衫,必須存入了被改用戶的id
    public int updateUser(Connection connection,User user) throws SQLException {
        PreparedStatement pstm = null;
        int count = 0;
        if(connection != null) {
            StringBuffer sql = new StringBuffer();//利用追加給sql賦予真實(shí)語(yǔ)句
            ArrayList<Object> list = new ArrayList<Object>();
            sql.append("update smbms_user set");
            int flag = 0;
            if(user.getUserName() != null) {
                if(flag > 0) {
                    sql.append(",");
                } else {
                    flag = 1;
                }
                sql.append(" userName = ?");
                list.add(user.getUserName());
            }
            if(user.getGender() != null) {
                if(flag > 0) {
                    sql.append(",");
                } else {
                    flag = 1;
                }
                sql.append(" gender = ?");
                list.add(user.getGender());
            }
            if(user.getPhone() != null) {
                if(flag > 0) {
                    sql.append(",");
                } else {
                    flag = 1;
                }
                sql.append(" phone = ?");
                list.add(user.getPhone());
            }
            if(user.getAddress() != null) {
                if(flag > 0) {
                    sql.append(",");
                } else {
                    flag = 1;
                }
                sql.append(" address = ?");
                list.add(user.getAddress());
            }
            if(user.getBirthday() != null) {
                if(flag > 0) {
                    sql.append(",");
                } else {
                    flag = 1;
                }
                sql.append(" birthday = ?");
                list.add(user.getBirthday());
            }
            if(user.getUserRole() != null) {
                if(flag > 0) {
                    sql.append(",");
                } else {
                    flag = 1;
                }
                sql.append(" userRole = ?");
                list.add(user.getUserRole());
            }
            if(user.getModifyBy() != null) {
                if(flag > 0) {
                    sql.append(",");
                } else {
                    flag = 1;
                }
                sql.append(" modifyBy = ?");
                list.add(user.getModifyBy());

            }
            if(user.getModifyDate() != null) {
                if(flag > 0) {
                    sql.append(",");
                } else {
                    flag = 1;
                }
                sql.append(" modifyDate = ?");
                list.add(user.getModifyDate());
            }
            if(user.getId() != null) {//id不能為空,否則不進(jìn)行更改3鹎帷京痢!
                sql.append(" where id = ?");
                list.add(user.getId());

                Object[] params = list.toArray();
                //執(zhí)行更改語(yǔ)句
                count = BaseDao.execute(connection, pstm, sql.toString(), params);
            }

            System.out.println("UserDaoImpl.updateUser.sql: " + sql);
            System.out.println(list.toString());
        }
        //關(guān)閉資源
        BaseDao.closeResource(null,pstm,null);
        return count;
    }

3. UserService

    //根據(jù)用戶提交的User更改該user對(duì)應(yīng)的數(shù)據(jù)中的數(shù)據(jù)
    public boolean updateUser(User user);

4. UserServiceImpl

    //根據(jù)用戶提交的User更改該user對(duì)應(yīng)的數(shù)據(jù)中的數(shù)據(jù)
    public boolean updateUser(User user) {
        //取當(dāng)前(北京)時(shí)間
        Date nowdate = new Date();
        //轉(zhuǎn)換時(shí)間格式
        SimpleDateFormat simpleDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //設(shè)置更改時(shí)間,但是存入數(shù)據(jù)庫(kù)會(huì)少了8小時(shí)篷店?
        user.setModifyDate(Timestamp.valueOf(simpleDate.format(nowdate)));

        Connection connection = null;
        boolean flag = false;
        UserDaoImpl userDao = new UserDaoImpl();
        try {
            connection = BaseDao.getConnection();
            if((userDao.updateUser(connection,user)) > 0) {
                flag = true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {//關(guān)閉資源
            BaseDao.closeResource(connection,null,null);
        }
        return flag;
    }

    @Test
    public void test() {//測(cè)試
        UserServiceImpl userService = new UserServiceImpl();
        User user = new User();
        user.setUserName("李四仁");
//        user.setId(50);
        user.setGender(1);
//        user.setPhone("15815891956");
        user.setAddress("廣東宏遠(yuǎn)");
        user.setModifyBy(1);
        //取當(dāng)前時(shí)間
        Date nowdate = new Date();
        //轉(zhuǎn)換時(shí)間格式
        SimpleDateFormat simpleDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        user.setModifyDate(Timestamp.valueOf(simpleDate.format(nowdate)));

        System.out.println(userService.updateUser(user));
    }

5. Servlet

//更改用戶信息
    public void updateUser(HttpServletRequest req, HttpServletResponse resp) {
        User user = new User();
        //獲得前端數(shù)據(jù)
        String id = req.getParameter("id");
        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");
        //獲得當(dāng)前Session的id祭椰,是執(zhí)行修改操作的用戶
        Object o = req.getSession().getAttribute(Constants.USER_SESSION);
        if(o != null) {
            user.setModifyBy(((User)o).getId());
            System.out.println(((User)o).getId());
        }
        //被修改用戶的id
        System.out.println("id = " + id);
        user.setId(Integer.parseInt(id));
        //被修改用戶的名字
        System.out.println("userName = " + userName);
        user.setUserName(userName);
        //被修改用戶的性別
        System.out.println("gender = " + gender);
        user.setGender(Integer.parseInt(gender));
        //被修改用戶的出生日期
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date d=simpleDateFormat.parse(birthday);
            System.out.println("src_birthday = " + birthday + "change_birthday = " + simpleDateFormat.format(d));
            user.setBirthday(d);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        //被修改用戶的電話
        System.out.println("phone = " + phone);
        user.setPhone(phone);
        //被修改用戶的地址
        System.out.println("address = " + address);
        user.setAddress(address);
        //被修改用戶的角色
        System.out.println("userRole = " + userRole);
        user.setUserRole(Integer.parseInt(userRole));
        //調(diào)業(yè)務(wù)層執(zhí)行方法
        UserServiceImpl userService = new UserServiceImpl();
        userService.updateUser(user);
        try {
            req.getRequestDispatcher("/user/userlist.html?method=query").forward(req,resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

6. xml

    <servlet-mapping>
        <servlet-name>UserServlet</servlet-name>
        <url-pattern>/user/usermodifysave.html</url-pattern>
    </servlet-mapping>

添加用戶

  • 獲得用戶全部角色

和上面所用的方法一樣

  • 獲得全部用戶的userCode并判斷用戶想要新建用戶的userCode是否能使用

1. UserDao

    //獲得所有用戶的userCode
    public List<String> getAllUserCode(Connection connection) throws SQLException;

2. UserDaoImpl

//獲得所有用戶的userCode
    public List<String> getAllUserCode(Connection connection) throws SQLException {
        //準(zhǔn)備資源
        PreparedStatement pstm = null;
        ResultSet rs = null;
        ArrayList<String> list = new ArrayList<String>();
        if(connection != null) {
            String sql = "select userCode from smbms_user";//查詢語(yǔ)句
            Object[] params = {};//為空,沒(méi)有占位的需求
            rs = BaseDao.execute(connection,pstm,rs,sql,params);
            while(rs.next()) {
                list.add(rs.getString("userCode"));
            }
            //關(guān)閉資源
            BaseDao.closeResource(null,pstm,rs);
            System.out.println("UserDaoImpl.getUserId.sql:" + sql);
            System.out.println(list.toString());
        }
        return list;
    }

3. UserService

    //獲得所有用戶的userCode
    public List<String> getAllUserCode();

4. UserServiceImpl

    //獲得所有用戶的userCode
    public List<String> getAllUserCode() {
        Connection connection = null;
        List<String> list = null;
        try {
            connection = BaseDao.getConnection();
            list = userDao.getAllUserCode(connection);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            BaseDao.closeResource(connection,null,null);
        }
        return list;
    }

    @Test
    public void test() {//測(cè)試
        UserServiceImpl userService = new UserServiceImpl();
        System.out.println(userService.getAllUserCode().toString());
    }

5. UserServlet

//獲得全部用戶的userCode并判斷是否新建userCode是否已經(jīng)在數(shù)據(jù)庫(kù)中存在
    public void getAllUseruserCode(HttpServletRequest req, HttpServletResponse resp) {
        UserServiceImpl userService = new UserServiceImpl();
        List<String> list = userService.getAllUserCode();
        boolean flag = false;
        String tempid = req.getParameter("userCode");
        if(tempid != null) {
            System.out.println("tempid = " + tempid);
            for (int i = 0; i < list.size() && !flag; i++) {
                flag = tempid.equals(list.get(i));
            }
        }
        System.out.println("是否存在同名:flag = " + flag);
        //給頁(yè)面返回json對(duì)象的數(shù)據(jù)
        Map<String,String> map = new HashMap<String, String>();
        if(flag) {
            map.put("userCode","exist");
        } else {
            map.put("userCode","noexist");
        }

        try {
            resp.setContentType("application/json");
            PrintWriter writer = resp.getWriter();
            /*
            JSONArray,工具類疲陕,轉(zhuǎn)換格式方淤,將map轉(zhuǎn)換為json
             */
            writer.write(JSONArray.toJSONString(map));
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

6. xml

    <servlet-mapping>
        <servlet-name>UserServlet</servlet-name>
        <url-pattern>/user/ucexist.html</url-pattern>
    </servlet-mapping>
  • 提交新用戶信息,存儲(chǔ)在數(shù)據(jù)庫(kù)

1. UserDao

    //添加新用戶
    public int addUser(Connection connection,User user) throws SQLException;

    //獲得所有用戶中最大的id
    public Integer getAllUserMaxId(Connection connection) throws SQLException;

2. UserDaoImpl

//獲得所有用戶中最大的id
    public Integer getAllUserMaxId(Connection connection) throws SQLException {
        //準(zhǔn)備資源
        PreparedStatement pstm = null;
        ResultSet rs = null;
        Integer maxId = null;
        if(connection != null) {
            String sql = "select max(id) as maxId from smbms_user";//查詢語(yǔ)句
            Object[] params = {};//為空蹄殃,沒(méi)有占位的需求
            rs = BaseDao.execute(connection,pstm,rs,sql,params);
            if (rs.next()) {
                maxId = rs.getInt("maxId");
            }
            //關(guān)閉資源
            BaseDao.closeResource(null,pstm,rs);
            System.out.println("UserDaoImpl.getUserId.sql:" + sql);
            System.out.println(maxId);
        }
        return maxId;
    }

    //添加新用戶
    public int addUser(Connection connection,User user) throws SQLException {
        int count = 0;
        PreparedStatement pstm = null;
        String sql = "insert into smbms_user (id, userCode, userName, userPassword, gender, birthday, phone, address, userRole, createdBy, creationDate, idPicPath, workPicPath) value (?,?,?,?,?,?,?,?,?,?,?,?,?)";
        ArrayList<Object> list = new ArrayList<Object>();
        if(connection != null && user.getId() != null) {
            //用戶id
            list.add(user.getId());
            //用戶userCode
            if(user.getUserCode() != null) {
                list.add(user.getUserCode());
            } else {
                list.add(null);
            }
            //用戶userName
            if(user.getUserName() != null) {
                list.add(user.getUserName());
            } else {
                list.add(null);
            }
            //用戶userPassword
            if(user.getUserPassword() != null) {
                list.add(user.getUserPassword());
            } else {
                list.add(null);
            }
            //用戶gender
            if(user.getGender() != null) {
                list.add(user.getGender());
            } else {
                list.add(null);
            }
            //用戶birthday
            if(user.getBirthday() != null) {
                list.add(user.getBirthday());
            } else {
                list.add(null);
            }
            //用戶userphone
            if(user.getPhone() != null) {
                list.add(user.getPhone());
            } else {
                list.add(null);
            }
            //用戶userAdress
            if(user.getAddress() != null) {
                list.add(user.getAddress());
            } else {
                list.add(null);
            }
            //用戶userRole
            if(user.getUserRole() != null) {
                list.add(user.getUserRole());
            } else {
                list.add(null);
            }
            //用戶userCreatedby
            if(user.getCreatedBy() != null) {
                list.add(user.getCreatedBy());
            } else {
                list.add(null);
            }
            //用戶userCreationDate
            if(user.getCreationDate() != null) {
                list.add(user.getCreationDate());
            } else {
                list.add(null);
            }
            //用戶userIdPicPath
            if(user.getIdPicPath() != null) {
                list.add(user.getIdPicPath());
            } else {
                list.add(null);
            }
            //用戶userworkPicPath
            if(user.getWorkPicPath() != null) {
                list.add(user.getWorkPicPath());
            } else {
                list.add(null);
            }
            System.out.println("UserDaoImpl.addUser.sql-->:" + sql);
            System.out.println(list.toString());
            Object[] params = list.toArray();

            count = BaseDao.execute(connection,pstm,sql,params);
            BaseDao.closeResource(null,pstm,null);
        }
        return count;
    }

3. UserService

    //獲得所有用戶中最大的id
    public Integer getAllUserMaxId();

    //添加新用戶
    public boolean addUser(User user);

4. UserServiceImpl

//獲得所有用戶中最大的Id
    public Integer getAllUserMaxId() {
        Connection connection = null;
        Integer maxId = null;
        try {
            connection = BaseDao.getConnection();
            maxId = userDao.getAllUserMaxId(connection);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            BaseDao.closeResource(connection,null,null);
        }
        return maxId;
    }

    //添加新用戶
    public boolean addUser(User user) {
        int flag = 0;
        Connection connection = null;
        if(user != null) {
            //獲得最大的id
            Integer allUserId = this.getAllUserMaxId();
            //給用戶設(shè)置 id 且比最大的id大 1
            user.setId(allUserId + 1);
            //取當(dāng)前(北京)時(shí)間
            Date nowdate = new Date();
            //轉(zhuǎn)換時(shí)間格式
            SimpleDateFormat simpleDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            //設(shè)置創(chuàng)建用戶的時(shí)間携茂,但是存入數(shù)據(jù)庫(kù)會(huì)少了8小時(shí)?
            user.setCreationDate(Timestamp.valueOf(simpleDate.format(nowdate)));
            System.out.println("id =" + user.getId() + "...   date = " +nowdate.toString());
            try {
                connection = BaseDao.getConnection();
                flag = userDao.addUser(connection,user);
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                BaseDao.closeResource(connection,null,null);
            }
        }
        return flag > 0;
    }

    @Test
    public void test() {//測(cè)試
        UserServiceImpl userService = new UserServiceImpl();

        User user = new User();
        user.setUserCode("jimmy");
        user.setUserName("jimmyBatter");
        user.setUserPassword("1234567");
        user.setGender(1);
        //轉(zhuǎn)換時(shí)間格式
        SimpleDateFormat simpleDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //設(shè)置創(chuàng)建用戶的時(shí)間诅岩,但是存入數(shù)據(jù)庫(kù)會(huì)少了8小時(shí)讳苦?
        user.setBirthday(Timestamp.valueOf(simpleDate.format("2004-01-09")));
        user.setPhone("13812891022");
        user.setAddress("Maitland");
        user.setUserRole(3);
        user.setCreatedBy(1);

        boolean b = userService.addUser(user);
        System.out.println(b);
    }

5. UserServlet

  • 問(wèn)題分析:因?yàn)榍岸颂峤槐韱斡袑傩裕篹nctype="multipart/form-data"

  • enctype="multipart/form-data"時(shí)文本框參數(shù)獲取問(wèn)題的解決

  • 使用文件的方式讀取資源,新增一個(gè)AddUserServlet的類吩谦,處理該特殊請(qǐng)求

  • 前端頁(yè)面鸳谜,跳轉(zhuǎn)到添加用戶的是通過(guò)超鏈接實(shí)現(xiàn),所以放到doGet方法中式廷,表單提交(post)處理就使用post方法

  • 路徑問(wèn)題:this.getServletContext().getRealPath("/")獲得null咐扭,查找一番沒(méi)解決,便寫(xiě)死了項(xiàng)目在硬盤(pán)上的地址(沒(méi)有解決的bug)

public class AddUserServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("/jsp/useradd.jsp").forward(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("addUserServlet_method");

        //創(chuàng)建上傳文件的保存路徑,建議在WEB-INF路徑下,安全,用戶無(wú)法直接訪間上傳的文件;
//        String uploadPath = request.getSession().getServletContext().getRealPath("/statics/images");
        //只會(huì)寫(xiě)死滑废,上面的返回值是null
        String uploadPath = "D:\\javadownload\\ideaworkplace\\smbms\\smbms\\src\\main\\webapp\\statics\\images";
        File uploadFile = new File(uploadPath);
        if (!uploadFile.exists()){//判斷是否已經(jīng)有這個(gè)目錄蝗肪,沒(méi)有就返回false
            uploadFile.mkdir(); //創(chuàng)建這個(gè)月錄
        }

        // 緩存,臨時(shí)文件
        // 臨時(shí)路徑蠕趁,假如文件超過(guò)預(yù)期的大小薛闪,就將其放入臨時(shí)文件中,過(guò)幾天自動(dòng)刪除俺陋,或者提醒用戶轉(zhuǎn)存為永久
//        String tmpPath = this.getServletContext().getRealPath("/") + "/statics/tmp";
        //只會(huì)寫(xiě)死逛绵,上面的返回值是null
        String tmpPath = "D:\\javadownload\\ideaworkplace\\smbms\\smbms\\target\\smbms-1.0-SNAPSHOT\\statics\\images";
        File file = new File(tmpPath);
        if (!file.exists()) {//判斷是否已經(jīng)有這個(gè)目錄怀各,沒(méi)有就返回false
            file.mkdir();//創(chuàng)建臨時(shí)目錄
        }

        // 處理上傳的文件,一般都需要通過(guò)流來(lái)獲取,我們可以使用 request, getInputstream(),原生態(tài)的文件上傳流獲取,十分麻煩
        // 但是我們都建議使用 Apache的文件上傳組件來(lái)實(shí)現(xiàn), common-fileupload,它需要依賴于 commons-io組件;
        try {
            // 創(chuàng)建 DiskFileItemFactory對(duì)象,處理文件路徑或者大小限制
            DiskFileItemFactory factory = getDiskFileItemFactory(file);
            /*
             * //通過(guò)這個(gè)工廠設(shè)置一個(gè)緩沖區(qū),當(dāng)上傳的文件大于這個(gè)緩沖區(qū)的時(shí)候,將他放到臨時(shí)文件 factory.setSizeThreshold(1024 *
             * 1024); //緩存區(qū)大小為1M factory.setRepository (file);//臨時(shí)目錄的保存目錄,需要一個(gè)File
             */

            // 2术浪、獲取 ServletFileUpload
            ServletFileUpload upload = getServletFileUpload(factory);

            // 3、處理上傳文件
            // 把前端請(qǐng)求解析寿酌,封裝成FileItem對(duì)象胰苏,需要從ServletFileUpload對(duì)象中獲取
            // 將上傳的文件存入數(shù)據(jù)庫(kù)
            User user = uploadParseRequest(upload, request, uploadPath);
            System.out.println(user);

            //4、調(diào)業(yè)務(wù)層處理
            UserServiceImpl userService = new UserServiceImpl();
            System.out.println(userService.addUser(user));

            //5醇疼、 Servlet請(qǐng)求轉(zhuǎn)發(fā)消息
            request.getRequestDispatcher("/jsp/useradd.jsp").forward(request,response);

        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    public static DiskFileItemFactory getDiskFileItemFactory(File file) {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // 通過(guò)這個(gè)工廠設(shè)置一個(gè)緩沖區(qū),當(dāng)上傳的文件大于這個(gè)緩沖區(qū)的時(shí)候,將他放到臨時(shí)文件中;
        factory.setSizeThreshold(1024 * 1024);// 緩沖區(qū)大小為1M
        factory.setRepository(file);// 臨時(shí)目錄的保存目錄,需要一個(gè)file
        return factory;
    }

    public static ServletFileUpload getServletFileUpload(DiskFileItemFactory factory) {
        ServletFileUpload upload = new ServletFileUpload(factory);
        // 監(jiān)聽(tīng)長(zhǎng)傳進(jìn)度
        upload.setProgressListener(new ProgressListener() {

            // pBYtesRead:已讀取到的文件大小
            // pContextLength:文件大小
            public void update(long pBytesRead, long pContentLength, int pItems) {
                System.out.println("總大兴恫ⅰ:" + pContentLength + "已上傳:" + pBytesRead);
            }
        });

        // 處理亂碼問(wèn)題
        upload.setHeaderEncoding("UTF-8");
        // 設(shè)置單個(gè)文件的最大值
        upload.setFileSizeMax(1024 * 1024 * 10);
        // 設(shè)置總共能夠上傳文件的大小
        // 1024 = 1kb * 1024 = 1M * 10 = 10м

        return upload;
    }

    // 處理前端請(qǐng)求信息,得到一個(gè)用戶實(shí)例
    public static User uploadParseRequest(ServletFileUpload upload, HttpServletRequest request, String uploadPath)
            throws FileUploadException, IOException, ParseException {

        User user = new User();
        //獲得當(dāng)前Session的id秧荆,是執(zhí)行  添加新用戶  操作的用戶
        Object o = request.getSession().getAttribute(Constants.USER_SESSION);
        if(o != null) {
            user.setCreatedBy(((User)o).getId());
            System.out.println(user.getCreatedBy());
        }

        // 把前端請(qǐng)求解析倔毙,封裝成FileItem對(duì)象
        List<FileItem> fileItems = upload.parseRequest(request);
        for (FileItem fileItem : fileItems) {
            if (fileItem.isFormField()) {// 判斷上傳的文件是普通的表單還是帶文件的表單
                setMessage(user,fileItem);
            } else {// 判斷它是上傳的文件

                // ============處理文件==============

                // 拿到文件名
                String uploadFileName = fileItem.getName();
                System.out.println("上傳的文件名: " + uploadFileName);
                // 判斷文件名有效性
                if (uploadFileName.trim().equals("") || uploadFileName == null) {
                    continue;
                }

                // 獲得上傳的文件名/images/girl/paojie.png
                String fileName = uploadFileName.substring(uploadFileName.lastIndexOf("/") + 1);
                // 獲得文件的后綴名
                String fileExtName = uploadFileName.substring(uploadFileName.lastIndexOf(".") + 1);

                //注入用戶上傳的圖片名字,并獲得圖片文件名
                fileName = setMessage(user,fileName,fileItem);

                /*
                 * 如果文件后綴名fileExtName不是我們所需要的 就直按return.不處理,告訴用戶文件類型不對(duì)乙濒。
                 */

                System.out.println("文件信息[件名: " + fileName + " ---文件類型" + fileExtName + "]");

                // ================處理文件完畢==============

                // 存到哪? uploadPath
                // 文件真實(shí)存在的路徑realPath
                String realPath = uploadPath;

                // ==============存放地址完畢==============


                // 獲得文件上傳的流
                InputStream inputStream = fileItem.getInputStream();
                // 創(chuàng)建一個(gè)文件輸出流
                // realPath =真實(shí)的文件夾;
                // 差了一個(gè)文件;加上輸出文件的名+"/"+FileName
                FileOutputStream fos = new FileOutputStream(realPath + "/" + fileName);

                // 創(chuàng)建一個(gè)緩沖區(qū)
                byte[] buffer = new byte[1024 * 1024];
                // 判斷是否讀取完畢
                int len = 0;
                // 如果大于0說(shuō)明還存在數(shù)據(jù);
                while ((len = inputStream.read(buffer)) > 0) {
                    fos.write(buffer, 0, len);
                }
                // 關(guān)閉流
                fos.close();
                inputStream.close();

                fileItem.delete(); // 上傳成功,清除臨時(shí)文件
                //=============文件傳輸完成=============
            }
        }
        return user;
    }

    // 將文本信息注入到用戶實(shí)例對(duì)象中
    public static void setMessage(User user, FileItem fileItem) throws UnsupportedEncodingException, ParseException {
        //從前端請(qǐng)求解析文件中獲得數(shù)據(jù)
        // getFieldName指的是前端表單控件的name;
        String name = fileItem.getFieldName();
        String value = fileItem.getString();

        if("userCode".equals(name)) { //新用戶編碼
            value = fileItem.getString("UTF-8"); // 處理亂碼
            user.setUserCode(value);
        } else if("userName".equals(name)) { //新用戶名稱
            value = fileItem.getString("UTF-8"); // 處理亂碼
            user.setUserName(value);
        } else if("userPassword".equals(name)) { //新用戶密碼
            user.setUserPassword(value);
        } else if("gender".equals(name)) { //新用戶性別
            user.setGender(Integer.parseInt(value));
        } else if("birthday".equals(name)) { //新用戶生日
            SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
            Date d=simpleDateFormat.parse(value);
            user.setBirthday(d);
        } else if("phone".equals(name)) { //新用戶電話
            user.setPhone(value);
        } else if("address".equals(name)) { //新用戶地址
            value = fileItem.getString("UTF-8"); // 處理亂碼
            user.setAddress(value);
        } else if("userRole".equals(name)) { //新用戶角色
            user.setUserRole(Integer.parseInt(value));
        }
        System.out.println(name + ": " + value);
    }

    //注入用戶上傳的圖片名字陕赃,并返回
    public static String setMessage(User user, String fileName, FileItem fileItem) {
        //從前端請(qǐng)求解析文件中獲得數(shù)據(jù)
        // getFieldName指的是前端表單控件的name;
        String name = fileItem.getFieldName();
        fileName = user.getUserCode() + "_" + fileName;
        if("a_idPicPath".equals(name)) { //新用戶pic地址
            fileName = "_IdPicPath" + fileName;
            user.setIdPicPath(fileName);
        } else if("a_workPicPath".equals(name)) { //新用戶workpic地址
            fileName = "_WorkPicPath" + fileName;
            user.setWorkPicPath(fileName);
        }
        System.out.println(name + ": " + fileName);
        return fileName;
    }

}

6. xml

    <!--AddUserServlet-->
    <servlet>
        <servlet-name>AddUserServlet</servlet-name>
        <servlet-class>com.vigil.servlet.user.AddUserServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>AddUserServlet</servlet-name>
        <url-pattern>/user/useradd.html</url-pattern><!--跳轉(zhuǎn)到添加用戶的jsp頁(yè)面-->
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>AddUserServlet</servlet-name>
        <url-pattern>/user/addUser.html</url-pattern><!--提交添加請(qǐng)求-->
    </servlet-mapping>

7. bug

文件的路徑獲取失敗:

  • request.getSession().getServletContext().getRealPath("/statics/images");
  • this.getServletContext().getRealPath("/") + "/statics/tmp";

零颁股、 UserServlet里doGet()和doPost()方法

@Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if("savepwd".equals(method)) {//修改用戶密碼
            this.savepwd(req,resp);
        } else if("pwdmodify".equals(method)) {//驗(yàn)證舊密碼么库,Ajax異步請(qǐng)求,不用轉(zhuǎn)發(fā)
            this.pwdmodify(req,resp);
        } else if("query".equals(method)) {//用戶管理頁(yè)面的 查詢 點(diǎn)擊請(qǐng)求
            this.query(req, resp);
        } else if("view".equals(method)) {//用戶管理頁(yè)面下的 查看頁(yè)面 點(diǎn)擊請(qǐng)求
            this.getUserForView(req, resp);
        } else if("modify".equals(method)) {//用戶管理頁(yè)面下的 修改頁(yè)面 點(diǎn)擊請(qǐng)求
            this.getUserForModify(req, resp);
        } else if("getrolelist".equals(method)) {//修改用戶信息頁(yè)面下的 角色列表 的Ajax異步請(qǐng)求甘有,不用轉(zhuǎn)發(fā)
            this.getRoleList(req, resp);
        } else if("modifyexe".equals(method)) {//修改用戶信息的提交請(qǐng)求
            this.updateUser(req,resp);
        } else if("ucexist".equals(method)) {//獲得全部用戶的userCode诉儒,添加用戶頁(yè)面下的帳號(hào)編碼Ajax異步請(qǐng)求,不用轉(zhuǎn)發(fā)
            this.getAllUseruserCode(req, resp);
        } else if("add".equals(method)) {//添加新用戶的提交請(qǐng)求
            this.addUser(req, resp);
        } else if("deluser".equals(method)) {//用戶管理頁(yè)面的 刪除用戶 的Ajax異步請(qǐng)求亏掀,不用轉(zhuǎn)發(fā)
            this.deleteUser(req, resp);
        }  else {//跳轉(zhuǎn)到添加用戶頁(yè)面
            req.getRequestDispatcher("/jsp/useradd.jsp").forward(req,resp);
        }
    }

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

用戶管理頁(yè)面刪除用戶功能實(shí)現(xiàn)

1. UserDao

    //根據(jù)用戶id刪除該用戶
    public int deleteUser(Connection connection,int id) throws SQLException;

2. UserDaoImpl

//根據(jù)用戶id刪除該用戶
    public int deleteUser(Connection connection,int id) throws SQLException {
        int count = 0;
        PreparedStatement pstm = null;
        if(connection != null) {
            String sql = "delete from smbms_user where id = ?";
            Object[] params = {id};
            count = BaseDao.execute(connection,pstm,sql,params);
            BaseDao.closeResource(null,pstm,null);
            System.out.println("UserDaoImpl.delectUser.sql:--->" + sql + "?-->id = -->" + id);
        }
        return count;
    }

3. UserService

    //刪除用戶,根據(jù)用戶id
    public boolean deleteUser(int id);

4. UserServiceImpl

//刪除用戶,根據(jù)用戶id
    public boolean deleteUser(int id) {
        int count = 0;
        Connection connection = null;
        try {
            connection = BaseDao.getConnection();
            //調(diào)用dao層方法忱反,刪除用戶
            count = userDao.deleteUser(connection,id);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            BaseDao.closeResource(connection,null,null);
        }
        return count > 0;
    }



    @Test
    public void test2() {//測(cè)試添加新用戶、刪除用戶
        UserServiceImpl userService = new UserServiceImpl();

        //添加用戶
        User user = new User();
        user.setUserCode("jimmyTextDelete");
        user.setUserName("jimmyBatter");
        user.setUserPassword("1234567");
        user.setGender(1);

//        SimpleDateFormat simpleDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        user.setBirthday(Timestamp.valueOf(simpleDate.format(new String("2004-01-09"))));
        //設(shè)置用戶的生日滤愕,但是存入數(shù)據(jù)庫(kù)會(huì)少了8小時(shí)温算?
        try {
            //轉(zhuǎn)換時(shí)間格式
            SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
            user.setBirthday(simpleDateFormat.parse("2004-01-09"));
        } catch (ParseException e) {
            e.printStackTrace();
        }

        user.setPhone("13812891022");
        user.setAddress("Maitland");
        user.setUserRole(3);
        user.setCreatedBy(1);

        boolean b = userService.addUser(user);
        System.out.println(b);
//        //刪除用戶
//        System.out.println("delectUser---》" + userService.deleteUser(user.getId()));
    }

5. UserServlet

    //刪除用戶
    public void deleteUser(HttpServletRequest req, HttpServletResponse resp) {
        String uid = req.getParameter("uid");
        HashMap<String, String> map = new HashMap<String, String>();
        if(uid != null) {//id存在
            int id = Integer.parseInt(uid);
            //調(diào)用業(yè)務(wù)層處理
            System.out.println("delete user.id:  " + id);
            UserServiceImpl userService = new UserServiceImpl();
            boolean flag = userService.deleteUser(id);
            System.out.println("delete result-->>" + flag);

            if(flag) {//刪除成功
                map.put("delResult","true");
            } else {//刪除失敗
                map.put("delResult","false");
            }
        } else {//id不存在
            map.put("delResult","notexist");
        }
        resp.setContentType("application/jsp");
        try {
            PrintWriter writer = resp.getWriter();
            /*
            JSONArray,工具類,轉(zhuǎn)換格式该互,將map轉(zhuǎn)換為json
             */
            writer.write(JSONArray.toJSONString(map));
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

6. xml

    <servlet-mapping>
        <servlet-name>UserServlet</servlet-name>
        <url-pattern>/user/deluser.html</url-pattern>
    </servlet-mapping>
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末米者,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子宇智,更是在濱河造成了極大的恐慌蔓搞,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,734評(píng)論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件随橘,死亡現(xiàn)場(chǎng)離奇詭異喂分,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)机蔗,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,931評(píng)論 3 394
  • 文/潘曉璐 我一進(jìn)店門(mén)蒲祈,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)甘萧,“玉大人,你說(shuō)我怎么就攤上這事梆掸⊙锞恚” “怎么了?”我有些...
    開(kāi)封第一講書(shū)人閱讀 164,133評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵酸钦,是天一觀的道長(zhǎng)怪得。 經(jīng)常有香客問(wèn)我,道長(zhǎng)卑硫,這世上最難降的妖魔是什么徒恋? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,532評(píng)論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮欢伏,結(jié)果婚禮上入挣,老公的妹妹穿的比我還像新娘。我一直安慰自己硝拧,他們只是感情好径筏,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,585評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著河爹,像睡著了一般匠璧。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上咸这,一...
    開(kāi)封第一講書(shū)人閱讀 51,462評(píng)論 1 302
  • 那天夷恍,我揣著相機(jī)與錄音,去河邊找鬼媳维。 笑死酿雪,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的侄刽。 我是一名探鬼主播指黎,決...
    沈念sama閱讀 40,262評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼州丹!你這毒婦竟也來(lái)了醋安?” 一聲冷哼從身側(cè)響起鹏氧,我...
    開(kāi)封第一講書(shū)人閱讀 39,153評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤审胚,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后若皱,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體所计,經(jīng)...
    沈念sama閱讀 45,587評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡柠辞,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,792評(píng)論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了主胧。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片叭首。...
    茶點(diǎn)故事閱讀 39,919評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡习勤,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出焙格,到底是詐尸還是另有隱情图毕,我是刑警寧澤,帶...
    沈念sama閱讀 35,635評(píng)論 5 345
  • 正文 年R本政府宣布眷唉,位于F島的核電站吴旋,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏厢破。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,237評(píng)論 3 329
  • 文/蒙蒙 一治拿、第九天 我趴在偏房一處隱蔽的房頂上張望摩泪。 院中可真熱鬧,春花似錦劫谅、人聲如沸见坑。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,855評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)荞驴。三九已至,卻和暖如春贯城,著一層夾襖步出監(jiān)牢的瞬間熊楼,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 32,983評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工能犯, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留鲫骗,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,048評(píng)論 3 370
  • 正文 我出身青樓踩晶,卻偏偏與公主長(zhǎng)得像执泰,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子渡蜻,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,864評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容