
JavaWeb搭建超市管理系统
发布日期:2021-05-09 09:24:32
浏览次数:15
分类:博客文章
本文共 20945 字,大约阅读时间需要 69 分钟。
目录
SMBMS
准备工作
搭建一个Maven项目、
配置Tomcat
测试项目能否跑起来
导入项目所需的jar包(servlet,jsp,mysql,jstl,standard.....)
创建项目包结构
编写实体类(ORM映射:表---类映射)
编写基础公共类(数据库配置文件)
driver=com.mysql.jdbc.driverurl=jdbc:mysql://localhost:3306?useUnicode=true&characterEncoding=utf-8user=rootpassword=123456
编写操作数据库的公共类
//操作数据库的公共类public class BaseDao { private static String driver; private static String url; private static String username; private static String password; //静态代码块类加载的时候就初始化 static { Properties properties = new Properties(); //通过类加载器加载资源 InputStream is = BaseDao.class.getClassLoader().getResourceAsStream("db.properties"); try { properties.load(is); } catch (IOException e) { e.printStackTrace(); } driver=properties.getProperty("driver"); url=properties.getProperty("url"); username=properties.getProperty("username"); password=properties.getProperty("password"); } //获取数据库的连接 public static Connection getConnection(){ Connection connection = null; try { Class.forName("driver"); connection = DriverManager.getConnection("url", "username", "password"); } catch (Exception e) { e.printStackTrace(); } return connection; } //编写查询公共类 public static ResultSet execute(Connection connection,String sql,PreparedStatement ps,Object[] params,ResultSet resultSet) throws SQLException { //预编译的sql在后面直接执行就可以了 ps = connection.prepareStatement(sql); for (int i = 0; i < params.length; i++) { ps.setObject(i+1,params[i]); } resultSet = ps.executeQuery(); return resultSet; } //编写增删改公共方法 public static int execute(Connection connection,String sql,PreparedStatement ps,Object[] params) throws SQLException { ps = connection.prepareStatement(sql); for (int i = 0; i < params.length; i++) { ps.setObject(i+1,params[i]); } int updaterows = ps.executeUpdate(); return updaterows; } //释放连接 public static boolean close(Connection connection,PreparedStatement ps,ResultSet resultSet){ boolean flag=true; if (resultSet!=null){ try { resultSet.close(); //GC回收 resultSet = null; } catch (SQLException throwables) { throwables.printStackTrace(); flag = false; } } if (ps!=null){ try { ps.close(); //GC回收 ps = null; } catch (SQLException throwables) { throwables.printStackTrace(); flag = false; } } if (connection!=null){ try { connection.close(); //GC回收 connection = null; } catch (SQLException throwables) { throwables.printStackTrace(); flag = false; }java } return flag; }}
编写字符编码过滤器
public class CharacterEncodingFilter implements Filter { public void init(FilterConfig filterConfig) throws ServletException { } public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); response.setContentType("text/html"); filterChain.doFilter(request,response); } public void destroy() { }}
配置web.xml
CharacterEncodingFilter com.zr.filter.CharacterEncodingFilter CharacterEncodingFilter /* 导入静态资源
登录功能实现
编写前端
设置首页
login.jsp 编写dao层登录用户的接口
public interface UserDao { //得到登录的用户 public User getLoginUser(Connection connection,String userCode) throws SQLException;}
编写dao接口的实现类
public class UserDaoImpl implements UserDao{ public User getLoginUser(Connection connection, String userCode) throws SQLException { PreparedStatement ps = 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, ps, 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,ps,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 UserDaoImpl(); } public User login(String userCode, String password) { Connection connection = null; User user = null; connection = BaseDao.getConnection(); try { //通过业务层调用具体的业务操作 user = userDao.getLoginUser(connection,userCode); } catch (SQLException throwables) { throwables.printStackTrace(); }finally { BaseDao.closeResource(connection,null,null); } return user; } //单元测试 @Test public void Test(){ UserServiceImpl userService = new UserServiceImpl(); User admin = userService.login("admin", "1234567"); System.out.println(admin.getUserPassword()); }}
编写Servlet
public class LoginServlet extends HttpServlet { //Serclet控制层,调用业务层代码 @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("LoginServlet.start"); //获取用户名和密码 String username = req.getParameter("userCode"); String password = req.getParameter("userPassword"); //和数据库中的密码进行对比,调用业务层 UserServiceImpl userService = new UserServiceImpl(); User user = userService.login(username, password); //把登录的人查出来 if(user!=null){ //将用户的信息放到session中 req.getSession().setAttribute(Constants.USER_SESSION,user); //跳转到内部的首页 resp.sendRedirect("jsp/frame.jsp"); }else { //转发回登录页面,提示用户名或者密码错误 req.setAttribute("error","用户名或密码不正确!"); req.getRequestDispatcher("login.jsp").forward(req,resp); } } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); }}
注册Servlet
LoginServlet com.zr.servlet.user.LoginServlet LoginServlet /login.do 测试访问
登录功能优化
注销功能:移除session,返回登录页面
注销Servlet
public class LoginoutServlet 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); }}
web.xml
LoginoutServlet com.zr.servlet.user.LoginoutServlet LoginoutServlet /jsp/logout.do
登录拦截优化
编写过滤器
public class SysFilter implements Filter { public void init(FilterConfig filterConfig) throws ServletException { } public void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse respone = (HttpServletResponse) resp; //从Session中获取用户 User user = (User)request.getSession().getAttribute(Constants.USER_SESSION); if(user==null){ respone.sendRedirect(request.getContextPath()+"/error.jsp"); }else { filterChain.doFilter(req,resp); } } public void destroy() { }}
web.xml
SysFilter com.zr.filter.SysFilter SysFilter /jsp/*
密码修改
编写dao层接口
//修改当前用户的密码public int updatePwd(Connection connection,int id,String password) throws SQLException;
编写dao接口的实现类
//修改当前用户的密码public int updatePwd(Connection connection, int id, String password) throws SQLException { PreparedStatement ps = null; int count = 0; if (connection!=null){ String sql = "update smbms_user set userPassword = ? where id = ?"; Object[] param = {password,id}; count = BaseDao.execute(connection, ps, sql, param); BaseDao.closeResource(null,ps,null); } return count;}
业务层
//修改密码public boolean updatePwd(int id, String password);
业务层接口
public boolean updatePwd(int id, String password) { Connection connection = null; boolean flag = false; try { connection = BaseDao.getConnection(); //修改密码 if (userDao.updatePwd(connection, id, password)>0){ flag = true; } } catch (SQLException throwables) { throwables.printStackTrace(); }finally { BaseDao.closeResource(connection,null,null); } return flag;}
Servlet层
public class UserServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //获取Session(用Session获取当前用户的id) Object o = req.getSession().getAttribute(Constants.USER_SESSION); //获取前端输入的密码 String newPassword = req.getParameter("newpassword"); boolean flag = false; System.out.println("=============="); System.out.println(((User)o).getId()); System.out.println(((User)o).getUserPassword()); System.out.println(newPassword); if (o!=null && !StringUtils.isNullOrEmpty(newPassword)){ UserService userService = new UserServiceImpl(); flag = userService.updatePwd(((User) o).getId(), newPassword); if (flag){ req.setAttribute("message","密码修改成功,请重新登录!"); //密码修改成功,清除Session req.getSession().removeAttribute(Constants.USER_SESSION); } else { req.setAttribute("message","密码修改失败!"); } }else{ req.setAttribute("message","新密码格式错误!"); } req.getRequestDispatcher("pwdmodify.jsp").forward(req,resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); }}
web.xml
UserServlet com.zr.servlet.user.UserServlet UserServlet /jsp/user.do
密码验证Ajax
在Servlet层验证(将验证和修改密码提取成方法,在Servlet中调用)导入阿里巴巴fastjson的jar包
public class UserServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String method = req.getParameter("method"); if (method.equals("savepwd")&&method!=null){ this.updatePwd(req,resp); }else if (method.equals("pwdmodify")&&method!=null){ this.pwdModify(req,resp); } } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } //修改密码 public void updatePwd(HttpServletRequest req, HttpServletResponse resp){ //获取Session(用Session获取当前用户的id) Object o = req.getSession().getAttribute(Constants.USER_SESSION); //获取前端输入的密码 String newPassword = req.getParameter("newpassword"); boolean flag = false; System.out.println("=============="); System.out.println(((User)o).getId()); System.out.println(((User)o).getUserPassword()); System.out.println(newPassword); if (o!=null && !StringUtils.isNullOrEmpty(newPassword)){ UserService userService = new UserServiceImpl(); flag = userService.updatePwd(((User) o).getId(), newPassword); 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(); } } //验证旧密码 Session中有用户的密码 public void pwdModify(HttpServletRequest req, HttpServletResponse resp){ Object o = req.getSession().getAttribute(Constants.USER_SESSION); String oldpassword = req.getParameter("oldpassword"); System.out.println(oldpassword); System.out.println("+++++++++++++++++++"); //万能的Map:结果集 MapresultMap = new HashMap (); //Session失效 if (o==null){ resultMap.put("result","sessionerror"); }else if (StringUtils.isNullOrEmpty(oldpassword)){//输入的密码为空 resultMap.put("result","error"); }else { String userPassword = ((User) o).getUserPassword();//session中用户的密码 if (oldpassword.equals(userPassword)){ resultMap.put("result","true"); }else { resultMap.put("result","false"); } } try { resp.setContentType("aplication/json"); PrintWriter writer = resp.getWriter(); //格式转换 writer.write(JSONArray.toJSONString(resultMap)); writer.flush(); writer.close(); } catch (IOException e) { e.printStackTrace(); } }}
用户管理实现
导入分页的工具类,用户列表页面导入
用户数量
UserDao
//查询用户总数 public int getUserCount(Connection connection,String username,int userRole) throws SQLException;
UserDaoImpl、
//根据用户名或角色查询人数public int getUserCount(Connection connection, String username, int userRole) throws SQLException { PreparedStatement ps = 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
UserService
//查询用户的人数public int getCountUser(String username,int userRole);
UserServiceImpl
//用户总数public int getCountUser(String username, int userRole) { Connection connection = null; int count = 0; try { connection = BaseDao.getConnection(); count = userDao.getUserCount(connection, username, userRole); } catch (SQLException throwables) { throwables.printStackTrace(); }finally { BaseDao.closeResource(connection,null,null); } return count;}
用户列表
UserDao
//通过条件查询userList public List
getUserList(Connection connection,String username,int userRole,int currentPageNo,int pageSize) throws SQLException; UserDaoImpl
//通过条件查询userListpublic List
getUserList(Connection connection, String username, int userRole, int currentPageNo, int pageSize) throws SQLException { PreparedStatement ps = null; ResultSet rs = null; //返回的用户列表 ArrayList userList = new ArrayList (); 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 list = new ArrayList (); 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 u.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(null, ps, rs, sql.toString(), params); while (rs.next()){ User user2 = new User(); user2.setId(rs.getInt("id")); user2.setUserCode(rs.getString("userCode")); user2.setUserName(rs.getString("userName")); user2.setGender(rs.getInt("gender")); user2.setBirthday(rs.getDate("birthday")); user2.setPhone(rs.getString("phone")); user2.setUserRole(rs.getInt("userRole")); user2.setUserRoleName(rs.getString("userRoleName")); userList.add(user2); } BaseDao.closeResource(null,ps,rs); } return userList;} UserService
//通过条件查询userListpublic List
getUserList(String queryUsername,int queryUserRole,int currentPageNo,int pageSize); UserServiceImpl
//通过条件查询userListpublic List
getUserList(String queryUsername, int queryUserRole, int currentPageNo, int pageSize) { Connection connection = null; List userList = null; try { connection = BaseDao.getConnection(); userList = userDao.getUserList(connection, queryUsername, queryUserRole, currentPageNo, pageSize); } catch (SQLException throwables) { throwables.printStackTrace(); }finally { BaseDao.closeResource(connection,null,null); } return userList;}
角色列表
RoleDao
public interface RoleDao { //获取角色列表 public List
getRoleList(Connection connection) throws SQLException;} RoleDaoImpl
public class RoleDaoImpl implements RoleDao{ //获取角色列表 public List
getRoleList(Connection connection) throws SQLException { PreparedStatement ps = null; ResultSet rs = null; List roleList = new ArrayList (); if (connection!=null){ String sql = "select * from smbms_role"; Object[] params = {}; rs = BaseDao.execute(connection, ps, rs, sql, params); while (rs.next()){ Role role = new Role(); role.setId(rs.getInt("id")); role.setRoleCode(rs.getString("roleCode")); role.setRoleName(rs.getString("roleName")); roleList.add(role); } BaseDao.closeResource(null,ps,rs); } return roleList; }} RoleService
public interface RoleService { //获取角色列表 public List
getRoleList() ;} RoleServiceImpl
public class RoleServiceImpl implements RoleService{ private RoleDao roleDao; public RoleServiceImpl(){ roleDao = new RoleDaoImpl(); } public List
getRoleList() { Connection connection = null; List roleList = null; try { connection = BaseDao.getConnection(); roleList = roleDao.getRoleList(connection); } catch (SQLException throwables) { throwables.printStackTrace(); }finally { BaseDao.closeResource(connection,null,null); } return roleList; }}
发表评论
最新留言
路过,博主的博客真漂亮。。
[***.116.15.85]2025年05月05日 22时22分21秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
CentOS 7更换yum源
2023-01-26
CentOS 7 安装 postgreSQL 9.4
2023-01-26
centos 7安装docker
2023-01-26
CentOS 7 巨大变动之 systemd 取代 SysV的Init
2023-01-26
Centos 7 快速安装FTP服务
2023-01-26
centos 7 静态IP,指定DNS
2023-01-26
centos 7如何使用firewalld 添加策略
2023-01-26
CentOS 7升级Python到3.5后yum出错
2023-01-26
centos 7.3 启动mysql_centos7.3 搭建MySQL
2023-01-26
Centos 7.5 docker 容器怎么设置开机自启
2023-01-26
Centos 7.5 SSH改别的端口连接不上,只有默认端口才行(未解决)
2023-01-26
Centos 7.5 如何安装VMware Tools工具
2023-01-26
Centos 7.5 新磁盘创建和挂载XFS文件系统
2023-01-26
Centos 7.5安装safe-rm,防止rm -rf /命令误删除文件
2023-01-26
CentOS 7.X 系统安装及优化
2023-01-26
Centos 7下安装php+mysql+nginx+wordpress教程新版
2023-01-26
CentOS 7之Postfix部署系列 (一) CentOS安装
2023-01-26
flask框架面向移动端的虚拟物品订购平台毕设源码+论文
2023-01-26
flask框架飞机订票管理系统(毕设源码+论文)
2023-01-26
flask框架餐饮管理系统毕设源码+论文
2023-01-26