j超市订单管理系统SMBMS
登录功能实现
注意:本项目考察对数据库的增删改查的运用,这里只完成了用户管理功能,也是 前端-service-servlet-dao-数据库 最复杂的一块,其他功能较为相似。
编写前端页面设置首页
<!--这是欢迎界面--><welcome-file-list><welcome-file>login.jsp</welcome-file></welcome-file-list>
编写dao层登录用户登录的接口
public interface UserDao {//得到要登录的用户public User getLoginUser(Connection connection, String userCode) throws SQLException;}
编写dao接口的实现类
public class UerDaoImpl implements UserDao{@Overridepublic User getLoginUser(Connection connection, String userCode) throws SQLException {PreparedStatement pstm = null;ResultSet rs = null;User user = null;if (connection != null) {String sql = "select * from smbms_user where userCode=?";Object[] params = {userCode};rs = BaseDao.execute(connection,pstm,rs,sql,params);if (rs.next()){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"));}BaseDao.closeResource(null,pstm,rs);}return user;}}
业务层接口
public interface UserService {//用户登录public User login(String userCode,String password);}
业务层实现类
public class UserServiceImpl implements UserService{//业务层都会调用dao层,所以我们要引入Dao层private UserDao userDao;public UserServiceImpl(){userDao = new UerDaoImpl();}@Overridepublic User login(String userCode, String password) {Connection connection =null;User user = null;try {connection = BaseDao.getConnection();//通过业务层调用对应的具体的数据库操作user = userDao.getLoginUser(connection,userCode);} catch (SQLException e) {e.printStackTrace();}finally {BaseDao.closeResource(connection,null,null);}return user;}}
编写Servlet
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {System.out.println("进入LoginServlet-start...");//获取用户名和密码String userCode = req.getParameter("userCode");String userPassword = req.getParameter("userPassword");//和数据库中的用户名和密码对比,调用业务层UserServiceImpl userService = new UserServiceImpl();User user = userService.login(userCode, userPassword);//这里已经把登录的人给查出来了if (user!=null){//将用户的信息放到Session中req.getSession().setAttribute(Constants.USER_SESSION,user);//跳转到主页 29。46resp.sendRedirect("jsp/frame.jsp");}else{//无法登录//转发回登录页面,顺带提示他,用户名或者密码错误req.setAttribute("error","用户名或者密码不正确");req.getRequestDispatcher("login.jsp").forward(req,resp);}}
注册Servlet
<!--Servlet--><servlet><servlet-name>LoginServlet</servlet-name><servlet-class>com.vekzjj.servlet.user.LoginServlet</servlet-class></servlet><servlet-mapping><servlet-name>LoginServlet</servlet-name><url-pattern>/login.do</url-pattern></servlet-mapping>
测试访问,确保以上功能能够成功
登录功能优化
注销功能:
思路:移除Session,返回登陆页面
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//移除用户的Constants.USER_SESSIONreq.getSession().removeAttribute(Constants.USER_SESSION);resp.sendRedirect(req.getContextPath()+"/login.jsp");//返回登录的页面}
<servlet><servlet-name>LogoutServlet</servlet-name><servlet-class>com.vekzjj.servlet.user.LogoutServlet</servlet-class></servlet><servlet-mapping><servlet-name>LogoutServlet</servlet-name><url-pattern>/jsp/logout.do</url-pattern></servlet-mapping>
登录拦截优化
编写一个过滤器本注册
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {HttpServletRequest request = (HttpServletRequest) servletRequest;HttpServletResponse response = (HttpServletResponse) servletResponse;//从Session中获取用户User user = (User) request.getSession().getAttribute(Constants.USER_SESSION);if (user==null){//说明已经被移除被注销了,或者未登录response.sendRedirect("/smbms/error.jsp");}else {filterChain.doFilter(servletRequest,servletResponse);}}
<!-- //用户登录过滤器--><filter><filter-name>SysFilter</filter-name><filter-class>com.vekzjj.filter.SysFilter</filter-class></filter><filter-mapping><filter-name>SysFilter</filter-name><url-pattern>/jsp/*</url-pattern></filter-mapping>
密码修改
导入前端素材<li><a href="${pageContext.request.contextPath }/jsp/pwdmodify.jsp">密码修改</a></li><!--密码修改-->
UserDao接口
//修改当前用户密码public int updatePwd(Connection connection,int id,int password) throws SQLException;
UserDao 实现类
@Overridepublic int updatePwd(Connection connection, int id, int password) throws SQLException {//修改当前用户密码PreparedStatement pstm= null;int execute = 0;if (connection!=null){String sql = "update smbms_user set userPassword = ? where id = ?";Object params[] = {password,id};execute = BaseDao.execute(connection, sql, params, pstm);BaseDao.closeResource(null,pstm,null);}return execute;}
<servlet><servlet-name>UserServlet</servlet-name><servlet-class>com.vekzjj.servlet.user.UserServlet</servlet-class></servlet><servlet-mapping><servlet-name>UserServlet</servlet-name><url-pattern>/jsp/user.do</url-pattern></servlet-mapping>
UserService层
//修改当前用户密码public boolean updatePwd(int id, int pwd) throws SQLException;
UserService实现类
public boolean updatePwd(int id, int pwd){Connection connection = null;boolean flag = false;connection = BaseDao.getConnection();//修改密码try {if (userDao.updatePwd(connection,id,pwd) > 0){flag = true;}} catch (SQLException e) {e.printStackTrace();}finally {BaseDao.closeResource(connection,null,null);}return flag;}
实现复用,需要提取出方法
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {String method = req.getParameter("method");if (method != null && method.equals("savepwd")){this.updatePwd(req,resp);}}
public void updatePwd(HttpServletRequest req, HttpServletResponse resp){//从Session里面拿ID;Object o = req.getSession().getAttribute(Constants.USER_SESSION);boolean flag = false;try {String newpassword = req.getParameter("newpassword");if (o != null && newpassword != null){UserService userService = new UserServiceImpl();flag = userService.updatePwd(((User) o).getId(), newpassword);if (flag){req.setAttribute("MESSAGE","修改密码成功,请退出,使用新密码登录");//密码修改成功,移除当前Sessionreq.getSession().removeAttribute(Constants.USER_SESSION);}else {req.setAttribute("MESSAGE","密码修改失败");}}else {req.setAttribute("MESSAGE","新密码有问题");}} catch (SQLException throwables) {throwables.printStackTrace();}try {req.getRequestDispatcher("pwdmodify.jsp").forward(req,resp);} catch (ServletException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}
优化密码修改使用Ajax
阿里巴巴的fastjson
<!-- /artifact/com.alibaba/fastjson --><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.79</version></dependency>
//验证旧密码,session中有用户的旧密码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失效了,或者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 {resp.setContentType("application/json");PrintWriter writer = resp.getWriter();//JSONArray阿里巴巴的工具类,转换格式的writer.write(JSONArray.toJSONString(resultMap));writer.flush();writer.close();} catch (IOException e) {e.printStackTrace();}}
用户管理实现
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-oU4RlQfd-1648634539460)(C:\Users\周俊杰\Desktop\新建文本文档 (2)]\image-0327164420424.png)
导入分页的工具类导入用户列表页面
userlist.jsp
rollpage.jsp
1、获取用户数量
UserDao//根据用户名或者角色查询用户总数public int getUserCount(Connection connection,String username,int userRole);
UserDaolmpl
public int getUserCount(Connection connection, String username, int userRole) {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 u,smbms_role r where u.userRole = r.id");ArrayList<Object> list = new ArrayList<>();//存放我们的参数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[] params = list.toArray();System.out.println("userDaoImpl->getUserCount"+ sql.toString());try {rs = BaseDao.execute(connection, pstm, rs, sql.toString(), params);if (rs.next()){count = rs.getInt("count");//从结果集中获取数量}} catch (SQLException e) {e.printStackTrace();}finally {BaseDao.closeResource(null,pstm,rs);}}return count;}
UserService
//查询记录数public int getUserCount(String username,int userRole);
UserServiceImpl
public int getUserCount(String username, int userRole) {Connection connection = null;int count = 0;connection = BaseDao.getConnection();count = userDao.getUserCount(connection, username, userRole);BaseDao.closeResource(connection,null,null);return count;}
2、获取用户列表
1.userdao
//通过条件查询 userListpublic List<User> getUserList(Connection connection,String userName,int userRole,int currentPageNo,int pageSize) throws SQLException;
2.userdaolmpl
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(connection, pstm, rs, sql.toString(), params);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);}BaseDao.closeResource(null, pstm, rs);}return userList;}
3.userService
//根据条件查询用户列表public 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) {// TODO Auto-generated method stubConnection 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 (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}finally{BaseDao.closeResource(connection, null, null);}return userList;}
3、获取角色操作
RoleDao
//获取角色列表public List<Role> getRoleList(Connection connection) throws SQLException;
RoleDaoImpl
public class RoleDaoImpl implements RoleDao{//获取角色列表@Overridepublic List<Role> getRoleList(Connection connection) throws SQLException {ResultSet resultSet = null;PreparedStatement pstm = null;ArrayList<Role> roleList = new ArrayList<>();if (connection != null){String sql = "select * from smbms_role";Object[] params = {};resultSet = BaseDao.execute(connection, pstm, resultSet, sql, params);while (resultSet.next()){Role _role = new Role();int id = resultSet.getInt("id");String roleCode = resultSet.getString("roleCode");String roleName = resultSet.getString("roleName");_role.setRoleCode(roleCode);_role.setId(id);_role.setRoleName(roleName);roleList.add(_role);}BaseDao.closeResource(null,pstm,resultSet);}return roleList;}}
RoleService
public interface RoleService {//获取角色列表public List<Role> getRoleList();}
RoleServiceImpl
public class RoleServiceImpl implements RoleService{//引入Daoprivate RoleDao roleDao;public RoleServiceImpl() {roleDao = new RoleDaoImpl();}@Overridepublic List<Role> getRoleList() {List<Role> roleList = null;Connection connection = null;try {connection = BaseDao.getConnection();roleList = roleDao.getRoleList(connection);} catch (SQLException e) {e.printStackTrace();}finally {BaseDao.closeResource(connection,null,null);}return roleList;}}
4、用户显示的Servlet
获取用户前端的数据(查询)判断请求是否需要执行(看参数的值判断)为了实现分页,需要计算当前页面和总页面的大小用户列表展示返回前端
public void query(HttpServletRequest req, HttpServletResponse resp) throws IOException {//查询用户列表//从前端获取数据String queryUserName = req.getParameter("queryname");String UserRole = req.getParameter("queryUserRole");String pageIndex = req.getParameter("pageIndex");int queryUserRole = 0;//获取用户列表UserServiceImpl userService = new UserServiceImpl();List<User> userList = null;//第一次走这个请求,一定是第一页,页面大小固定int pageSize = 5;//可以写道配置文件中int currentPageNo = 1;if (queryUserName==null){queryUserName = "";}if (UserRole!=null && !UserRole.equals("")){queryUserRole = Integer.parseInt(UserRole);//给查询出来的赋值 0,1,2,3}if (pageIndex != null){//解析页面try {currentPageNo = Integer.parseInt(pageIndex);}catch (Exception e){resp.sendRedirect("error.jsp");}}//获取用户的总数(分页:上一页,下一页的情况)31.04int totalCount = userService.getUserCount(queryUserName, queryUserRole);//总页数支持PageSupport pageSupport = new PageSupport();pageSupport.setCurrentPageNo(currentPageNo);pageSupport.setPageSize(pageSize);pageSupport.setTotalPageCount(totalCount);int totalPageCount = ((int) (totalCount/pageSize))+1;//控制首页和尾页,当前是第一页就不能往前,是最后一页就不能往后了if (currentPageNo < 1){currentPageNo = 1;//如果页面小于1了 就强制显示第一页}else if (currentPageNo > totalPageCount){currentPageNo = totalPageCount;//当页面大于了最后一页}//获取用户列表展示userList = userService.getUserList(queryUserName, queryUserRole, currentPageNo, pageSize);req.setAttribute("userList",userList);//角色列表RoleServiceImpl roleService = new RoleServiceImpl();List<Role> 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();//37.16}}