1. 项目准备阶段

  1. 分析需求,模块功能分配
  2. 不用java框架怎么开发 不用框架写一个web项目_不用java框架怎么开发

  3. 搭建一个maven web项目,配置Tomcat,测试项目能否成功跑起来
  4. 导入项目中会遇到的jar包,pom.xml中配置,(jsp,servlet,mysql驱动,jstl,starand...)
  5. 创建项目包结构
  6. 不用java框架怎么开发 不用框架写一个web项目_javaweb_02

  7. 编写实体类--->数据库对应,ORM映射:表-类映射
  8. 编写基础公共类和配置文件
    6.1 数据库配置文件-->db.properties
    6.2 编写数据库公共类-->Basedao
  • 获取数据库的连接
  • 编写查询公共方法
  • 编写增删改公共方法
  • 释放资源

6.3 编写字符编码过滤器并注册-->CharacterEncodingFilter implements Filter

  1. webapp下导入静态资源

2. 登录注销模块

2.1 登录功能实现

2.1.1 流程图

不用java框架怎么开发 不用框架写一个web项目_List_03

2.1.2 代码思路

思想:接口与实现类分离

dao层专注于数据库的操作,写SQL的地方,这地方是查询语句

编写dao层登录用户登录的接口,实现类实现,调用Basedao编写的公共方法,返回User对象

关闭资源时,connection暂时不用关,业务层关(事务)

//得到登录的用户
public User getLoginUser(Connection connection, String userCode) throws SQLException;

service层一般会有事务处理,调用dao层,关闭connection

//用户登录(账户,密码)
public User login(String userCode, String password);

Servlet:控制层,调用业务层,处理页面请求及响应(req,resp)

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("LoginServlet--start-----------");

        //System.out.println(Charset.defaultCharset());  GBK
        //获取用户名和密码,页面中获取req,去login.jsp中找
        String userCode = req.getParameter("userCode");
        String userPassword = req.getParameter("userPassword");

        //和数据库中密码对比,调用业务层
        UserServiceImpl userService = new UserServiceImpl();
        User user = userService.login(userCode, userPassword);

        //密码匹配,登录成功,将用户信息放入Session
        if (user != null && user.getUserPassword().equals(userPassword)) {
            req.getSession().setAttribute(Constants.USER_SESSION,user);
            //跳转到主页
            resp.sendRedirect("jsp/frame.jsp");
        }
        else {
            //转发登录页面,顺带提示密码错误
            req.setAttribute("error", "用户名或者密码错误");
            req.getRequestDispatcher("login.jsp").forward(req,resp);
        }
    }

最后注册Servlet

2.2 登录功能优化(注销)

  1. 移除Session,注册
//移除用户session
req.getSession().removeAttribute(Constants.USER_SESSION);
resp.sendRedirect("/smbms/login.jsp");   //返回登录页面
  1. 编写过滤器,注册
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

        //过滤器,从session中获取用户
        User user = (User) request.getSession().getAttribute(Constants.USER_SESSION);

        if (user==null) {
            response.sendRedirect("/smbms/error.jsp");
        } else {
            filterChain.doFilter(req,resp);
        }
    }

2.3 密码修改

2.3.1 思路

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

不用java框架怎么开发 不用框架写一个web项目_sql_04

2.3.2 代码编写

  1. dao-->写sql(update
//修改密码
public int updatePwd(Connection connection,int id, String pwd) throws SQLException;
  1. service-->调用dao
//根据用户ID修改密码
public boolean updatePwd(int id, String pwd);
  1. servlet:从Session里面拿ID-->req.getParameter("newpassword")-->userService.updatePwd()
public void updatePwd(HttpServletRequest req,HttpServletResponse resp)

2.4 密码修改优化

验证旧密码,使用Ajax,session中有用户的密码

3. 用户管理模块

不用java框架怎么开发 不用框架写一个web项目_狂神学习笔记_05


用户模块所需要的功能:UserDao接口

public interface UserDao {
    //得到登录的用户
    public User getLoginUser(Connection connection, String userCode) throws SQLException;

    //修改密码
    public int updatePwd(Connection connection,int id, String pwd) throws SQLException;

    //根据用户名或者角色查询用户数
    public int getUserCount(Connection connection, String userName, int userRole) throws SQLException;

    //通过条件查询-userList
    public List<User> getUserList(Connection connection, String userName, int userRole, int currentPageNo, int pageSize) throws SQLException;

    //添加用户信息
    public int addUser(Connection connection, User user) throws SQLException;

    //通过userID删除对象
    public int deleteUserById(Connection connection, Integer delId)throws Exception;

    //修改用户名信息
    public int modify(Connection connection, User user) throws SQLException;

    //通过userId获取user
    public User getUserById(Connection connection, String id) throws Exception;
}

3.1 获取用户数量

  1. daoImpl
//根据用户名或者角色查询用户数
@Override
public int getUserCount(Connection connection, String userName, int userRole) throws SQLException {
    PreparedStatement pstm = null;
    ResultSet rs = null;
    int count = 0;
    ArrayList<Object> list = new ArrayList<Object>();

    if (connection != null) {
        StringBuffer sql = new StringBuffer();
        sql.append("select count(1) as count from smbms_user u, smbms_role r where u.userRole = r.id");

        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
        }
        Object[] params = list.toArray();  //转换成数组
        System.out.println("UserDaoImp->getUserCount:" + sql.toString());//调试

        rs = Basedao.execute(pstm,connection,sql.toString(),params, rs);
        if (rs.next()) {
            count = rs.getInt("count");//从结果集中获取数量
        }
        //关闭资源
        Basedao.closeResource(pstm, null, rs);
    }
    return count;
}
  1. serviceImpl
//查询用户总数
@Override
public int getUserCount(String userNmae, int userRole) {
    Connection connection = null;
    int count = 0;

    try {
        connection = Basedao.getConnection();
        count = userDao.getUserCount(connection, userNmae, userRole);
    } catch (SQLException throwables) {
        throwables.printStackTrace();
    } finally {
        Basedao.closeResource(null, connection, null);
    }
    return count;
}

3.2 获取用户列表

  1. UserDaoImpl
//通过条件查询-userList
public List<User> getUserList(Connection connection, String userName, int userRole, int currentPageNo, int pageSize) throws SQLException {
    PreparedStatement pstm = null;
    ResultSet rs = null;
    List<User> userList = new ArrayList<User>();
    if(connection != null){
        StringBuffer sql = new StringBuffer();
        sql.append("select u.*,r.roleName as userRoleName from smbms_user u,smbms_role r where u.userRole = r.id");
        List<Object> list = new ArrayList<Object>();
        if(!StringUtils.isNullOrEmpty(userName)){
            sql.append(" and u.userName like ?");
            list.add("%"+userName+"%");
        }
        if(userRole > 0){
            sql.append(" and u.userRole = ?");
            list.add(userRole);
        }
        sql.append(" order by creationDate DESC limit ?,?");
        currentPageNo = (currentPageNo-1)*pageSize;
        list.add(currentPageNo);
        list.add(pageSize);

        Object[] params = list.toArray();
        System.out.println("sql ----> " + sql.toString());
        rs = Basedao.execute(pstm, connection, sql.toString(), params, rs);
        while (rs.next()) {
            User user = new User();
            user.setId(rs.getInt("id"));
            user.setUserCode(rs.getString("userCode"));
            user.setUserName(rs.getString("userName"));
            user.setGender(rs.getInt("gender"));
            user.setBirthday(rs.getDate("birthday"));
            user.setPhone(rs.getString("phone"));
            user.setUserRole(rs.getInt("userRole"));
            user.setUserRoleName(rs.getString("userRoleName"));
            userList.add(user);
        }
        //关闭资源,connection暂时不用关,业务层关
        Basedao.closeResource(pstm, null,rs);
    }
    return userList;
}
  1. UserServiceImpl
//根据条件查询用户列表
@Override
public List<User> getUserList(String userName, int userRole, int currentPageNo, int pageSize) {
    Connection connection = null;
    List<User> userList = null;
    System.out.println("queryUserName ---- > " + userName);
    System.out.println("queryUserRole ---- > " + userRole);
    System.out.println("currentPageNo ---- > " + currentPageNo);
    System.out.println("pageSize ---- > " + pageSize);
    try {
        connection = Basedao.getConnection();
        userList = userDao.getUserList(connection, userName,userRole,currentPageNo,pageSize);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }finally{
        Basedao.closeResource(null, connection, null);
    }
    return userList;
}

3.3 获取角色操作

为了 职责统一,可以把角色的操作单独放在一个包,和pojo相对应

  1. RoleDaoImpl
//获取角色列表
@Override
public List<Role> getRoleList(Connection connection) throws SQLException {
    ResultSet rs = null;
    PreparedStatement pstm = null;
    List<Role> list = new ArrayList<Role>();

    if (connection != null) {
        String sql = "select * from smbms_role";
        pstm = connection.prepareStatement(sql);
        Object[] params = {};
        rs = Basedao.execute(pstm, connection, sql, params, rs);

        while (rs.next()) {
            Role role = new Role();
            role.setId(rs.getInt("id"));
            role.setRoleCode(rs.getString("roleCode"));
            role.setRoleName(rs.getString("roleName"));
            list.add(role);
        }
        Basedao.closeResource(pstm, null, rs);
    }
    return list;
}
  1. RoleServiceImpl
public class RoleServiceImpl implements RoleService{

    //业务层都会调用dao层,引入dao层;无参构造直接调用
    private RoleDao roleDao;
    public RoleServiceImpl() {
        roleDao = new RoleDaoImpl();
    }

    //获得角色列表
    @Override
    public List<Role> getRoleList() {
        Connection connection = null;
        List<Role> roleList = null;

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

3.4 用户显示的Servlet(重点+难点)

  1. 获取用户前端的数据
  2. 判断请求是否需要执行,看参数的值判断
  3. 为了实现分页,需要就算出当前页面和分页面,页面大小
  4. 用户列表展示
  5. 返回前端
//通过条件查询-userList(重点+难点)
public void query(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    //查询用户列表

    //从前端获取数据
    String queryUserName = req.getParameter("queryname");//用户姓名
    String temp = req.getParameter("queryUserRole");     //用户role
    String pageIndex = req.getParameter("pageIndex");    //页标
    int queryUserRole = 0; //默认用户role为0

    //获取用户列表
    UserServiceImpl userService = new UserServiceImpl();
    RoleServiceImpl roleService = new RoleServiceImpl();
    List<User> userList = null;
    List<Role> roleList = null;

    //第一次走这个请求,一定是第一页,页面大小固定
    int pageSize = Constants.PAGE_SIZE;   //可以写到配置文件中,方便修改
    int currentPageNo = 1;

    //三个if,判断前段请求的参数
    if (queryUserName == null){
        queryUserName = "";
    }
    if (temp != null && !temp.equals("")) {
        queryUserRole = Integer.parseInt(temp);//给查询赋值 0,1,2
    }
    if (pageIndex != null) {
        try {
            currentPageNo = Integer.parseInt(pageIndex);
        } catch (NumberFormatException e) {
            resp.sendRedirect("error.jsp");
        }
    }

    //获取用户总数
    int totalCount = userService.getUserCount(queryUserName, queryUserRole);

    //总页数支持,设置参数
    PageSupport pageSupport = new PageSupport();
    pageSupport.setCurrentPageNo(currentPageNo);
    pageSupport.setPageSize(pageSize);
    pageSupport.setTotalCount(totalCount);

    //控制首页尾页
    int totalPageCount = pageSupport.getTotalPageCount();
    if (currentPageNo < 1) {
        currentPageNo = 1;
    } else if (currentPageNo > totalPageCount) {
        currentPageNo = totalPageCount;
    }

    //用户列表展示
    userList = userService.getUserList(queryUserName, queryUserRole, currentPageNo, pageSize);
    req.setAttribute("userList",userList);

    //角色列表
    roleList = roleService.getRoleList();
    req.setAttribute("roleList", roleList); //用户列表
    req.setAttribute("totalCount", totalCount); //用户总数总数
    req.setAttribute("currentPageNo", currentPageNo);   //当前页
    req.setAttribute("totalPageCount",totalPageCount);   //页面总数
    req.setAttribute("queryUserName",queryUserName);
    req.setAttribute("queryUserRole",queryUserRole);

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

3.5 添加用户

  1. UserDaoImpl
//添加用户信息
@Override
public int addUser(Connection connection, User user) throws SQLException {
    PreparedStatement pstm = null;
    int updateRows = 0;
    if (connection != null) {
        String sql = "insert into smbms_user (userCode,userName,userPassword,userRole,gender,birthday,phone,address,creationDate,createdBy) values(?,?,?,?,?,?,?,?,?,?)";
        Object[] params = {user.getUserCode(), user.getUserName(), user.getUserPassword(), user.getUserRole(), user.getGender(), user.getBirthday(), user.getPhone(), user.getAddress(), user.getCreationDate(), user.getCreatedBy()};
        updateRows = Basedao.update(pstm,connection,sql,params);
        Basedao.closeResource(pstm, null,null);
    }
    return updateRows;
}
  1. UserServiceImpl(事务处理)
//添加用户信息
@Override
public boolean addUser(User user) {
    Connection connection = null;
    boolean flag = false;
    int updateRows = 0;

    try {
        connection = Basedao.getConnection();
        connection.setAutoCommit(false);   //开启事务
        updateRows = userDao.addUser(connection, user);
        connection.commit();
        if (updateRows > 0) {
            flag = true;
            System.out.println("添加成功");
        } else {
            System.out.println("添加失败");
        }
    } catch (SQLException throwables) {
        throwables.printStackTrace();
        try {
            connection.rollback();//添加失败,数据回滚
        } catch (SQLException e) {
            e.printStackTrace();
        } finally{
            Basedao.closeResource(null, connection, null);
        }
    }
    return flag;
}
  1. UserServlet
//添加用户信息
public void addUser(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
    UserService userService = null;
    User user = null;

    //获取前端信息
    String userCode = req.getParameter("userCode");
    String userName = req.getParameter("userName");
    String userPassword = req.getParameter("userPassword");
    //String ruserPassword = req.getParameter("ruserPassword");
    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 = new User();
    user.setUserCode(userCode);
    user.setUserName(userName);
    user.setUserPassword(userPassword);
    user.setAddress(address);
    try {
        user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));
    } catch (ParseException e) {
        e.printStackTrace();
    }
    user.setGender(Integer.valueOf(gender));
    user.setPhone(phone);
    user.setUserRole(Integer.valueOf(userRole));
    user.setCreationDate(new Date());
    user.setCreatedBy(((User) req.getSession().getAttribute(Constants.USER_SESSION)).getId());

    userService = new UserServiceImpl();
    if (userService.addUser(user)) { //添加用户成功
        resp.sendRedirect(req.getContextPath() + "/jsp/user.do?method=query");
    } else {
        req.getRequestDispatcher("useradd.jsp").forward(req, resp);
    }
}

3.6 删除用户

  1. UserDaoImpl
//通过用户id删除用户
public int deleteUserById(Connection connection, Integer delId) throws SQLException {
    PreparedStatement pstm = null;
    int updateRows = 0;
    if (connection != null) {
        String sql = "delete from smbms_user where id=?";
        Object[] params = {delId};
        updateRows = Basedao.update(pstm,connection,sql,params);
        Basedao.closeResource(pstm, null,null);
    }
    return updateRows;
}
  1. UserServiceImpl
//通过id删除用户
public boolean deleteUserById(Integer delId) throws Exception {
    Connection connection = null;
    boolean flag = false;
    int updateRows = 0;
    try {
        connection = Basedao.getConnection();
        connection.setAutoCommit(false);   //开启事务
        updateRows = userDao.deleteUserById(connection, delId);
        connection.commit();
        if (updateRows > 0) {
            flag = true;
        } else {
            System.out.println("删除失败");
        }
    } catch (SQLException throwables) {
        throwables.printStackTrace();
        try {
            connection.rollback();//添加失败,数据回滚
        } catch (SQLException e) {
            e.printStackTrace();
        } finally{
            Basedao.closeResource(null, connection, null);
        }
    }
    return flag;
}
  1. UserServlet
//删除用户
private void delUser(HttpServletRequest request, HttpServletResponse response) throws Exception {
    String id = request.getParameter("uid");
    Integer delId = 0;
    try {
        delId = Integer.parseInt(id);
    } catch (Exception e) {
        delId = 0;
    }
    HashMap<String, String> resultMap = new HashMap<String, String>();
    if (delId <= 0) {
        resultMap.put("delResult", "notexist");
    } else {
        UserService userService = new UserServiceImpl();
        if (userService.deleteUserById(delId)) {
            resultMap.put("delResult", "true");
        } else {
            resultMap.put("delResult", "false");
        }
    }
}

3.7 修改用户

  1. UserDaoImpl
//修改用户信息
public int modify(Connection connection, User user) throws SQLException {
    int updateRows = 0;
    PreparedStatement pstm = null;
    if (connection != null) {
        String sql = "update smbms_user set userName=?,gender=?,birthday=?,phone=?,address=?,userRole=?,modifyBy=?,modifyDate=? where id =?";
        Object[] params = {user.getUserName(), user.getGender(), user.getBirthday(),
                user.getPhone(), user.getAddress(), user.getUserRole(), user.getModifyBy(),
                user.getModifyDate(), user.getId()};
        updateRows = Basedao.update(pstm,connection,sql,params);
        Basedao.closeResource(pstm, null,null);
    }
    return updateRows;
}
  1. UserServiceImpl
//修改用户
@Override
public boolean modify(User user) {
    // TODO Auto-generated method stub
    Connection connection = null;
    boolean flag = false;
    try {
        connection = Basedao.getConnection();
        if (userDao.modify(connection, user) > 0)
            flag = true;
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        Basedao.closeResource(null, connection, null);
    }
    return flag;
}
  1. UserServlet
//修改用户数据
private void modify(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    String id = request.getParameter("uid");
    String userName = request.getParameter("userName");
    String gender = request.getParameter("gender");
    String birthday = request.getParameter("birthday");
    String phone = request.getParameter("phone");
    String address = request.getParameter("address");
    String userRole = request.getParameter("userRole");

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

    UserService userService = new UserServiceImpl();
    if (userService.modify(user)) {
        response.sendRedirect(request.getContextPath() + "/jsp/user.do?method=query");
    } else {
        request.getRequestDispatcher("usermodify.jsp").forward(request, response);
    }
}

3.8 实现Userdao的其他接口

4. 供应商管理模块

  • 检索功能:条件查询+详细信息
  • 添加功能
  • 修改功能
  • 删除功能

5. 订单的增删查改

6. 源码和静态资源

我的GitHub

我的Gitee