超市订单管理系统smbms
项目环境:
windows10, idea2021.1.1, jdk8, tomcat9, mysql5
项目源代码(包括完善前和完善后)
链接:https://pan.baidu.com/s/17Pw24Q70A2mksXB_LTJ9qA
提取码:o402
1.准备工作
1.1项目框架图
1.2数据库
1.3idea新建Maven web项目
- 搭建一个maven web 项目
- 配置Tomcat
- 测试项目是否能够跑起来
- 导入项目中需要的jar包;
jsp,Servlet,mysql驱动jstl,stand… - 构建项目包结构
-
编写实体类
ROM映射:表-类映射 -
编写基础公共类
7-1、数据库配置文件(mysql5.xx和8.xx的编写有差异)driver=com.mysql.cj.jdbc.Driver url=jdbc:mysql://127.0.0.1:3306/lxw001?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai user=root password=123456
7-2、编写数据库的公共类
package com.badwei.dao; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Properties; /** * 操作数据库的基类--静态类 * */ 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,Object[] params,ResultSet resultSet,PreparedStatement preparedStatement) throws SQLException { preparedStatement = connection.prepareStatement(sql); for (int i = 0; i < params.length; i++) { preparedStatement.setObject(i+1,params[i]); } resultSet = preparedStatement.executeQuery(); return resultSet; } //编写增删改公共类 public static int execute(Connection connection,String sql,Object[] params,PreparedStatement preparedStatement) throws SQLException { preparedStatement = connection.prepareStatement(sql); for (int i = 0; i < params.length; i++) { preparedStatement.setObject(i+1,params[i]); } int updateRows = preparedStatement.executeUpdate(); return updateRows; } //关闭连接,释放资源 public static boolean closeResource(Connection connection,PreparedStatement preparedStatement,ResultSet resultSet){ boolean flag = true; if (resultSet != null) { try { resultSet.close(); resultSet = null; } catch (SQLException throwables) { throwables.printStackTrace(); flag = false; } } if(preparedStatement != null) { try { preparedStatement.close(); preparedStatement = null; } catch (SQLException throwables) { throwables.printStackTrace(); flag = false; } } if (connection != null) { try { connection.close(); connection = null; } catch (SQLException throwables) { throwables.printStackTrace(); flag = false; } } return flag; } }
7-3、编写字符编码过滤器
package com.badwei.filter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.*; public class CharacterEncodingFilter implements Filter { public void init(FilterConfig filterConfig) throws ServletException { } //@Override public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException { request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); chain.doFilter(request, response); } //@Override public void destroy() { } }
-
导入静态资源(前端)
前端资源和整个项目资源等项目结束后打包放入百度云
2.登录功能实现
登录流程图
2.1编写前端页面
2.2设置首页/欢迎页(web.xml配置)
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>
2.3编写Dao层登录用户登录的接口
package com.badwei.dao.user;
import com.badwei.pojo.User;
import java.sql.Connection;
import java.sql.SQLException;
public interface UserDao {
public User getLoginUser(Connection connection,String userCode) throws SQLException;
}
2.4编写Dao层接口的实现类
package com.badwei.dao.user;
import com.badwei.dao.BaseDao;
import com.badwei.pojo.User;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class UserDaoImpl implements UserDao{
@Override
public User getLoginUser(Connection connection, String userCode) throws SQLException {
PreparedStatement pstm = null;
ResultSet resultSet = null;
User user = null;
if (connection != null) {
String sql = "select * from smbms_user where userCode=?";
Object[] params = {userCode};
resultSet = BaseDao.execute(connection, pstm, resultSet, sql, params);
if (resultSet.next()){
user = new User();
user.setId(resultSet.getInt("id"));
user.setUserCode(resultSet.getString("userCode"));
user.setUserName(resultSet.getString("userName"));
user.setUserPassword(resultSet.getString("userPassword"));
user.setGender(resultSet.getInt("gender"));
user.setBirthday(resultSet.getDate("birthday"));
user.setPhone(resultSet.getString("phone"));
user.setAddress(resultSet.getString("address"));
user.setUserRole(resultSet.getInt("userRole"));
user.setCreatedBy(resultSet.getInt("createdBy"));
user.setCreationDate(resultSet.getTimestamp("creationDate"));
user.setModifyBy(resultSet.getInt("modifyBy"));
user.setModifyDate(resultSet.getTimestamp("modifyDate"));
}
//关闭连接
BaseDao.closeResource(null,pstm,resultSet);
}
return user;
}
}
2.5业务层接口
package com.badwei.service.user;
import com.badwei.pojo.User;
public interface UserService {
//用户登录
public User login(String userCode, String psssword);
}
2.6业务层实现类
package com.badwei.service.user;
import com.badwei.dao.BaseDao;
import com.badwei.dao.user.UserDao;
import com.badwei.dao.user.UserDaoImpl;
import com.badwei.pojo.User;
import org.junit.jupiter.api.Test;
import java.sql.Connection;
import java.sql.SQLException;
public class UserServiceImpl implements UserService{
private UserDao userDao;
public UserServiceImpl(){//无参构造,实例化则执行
userDao = new UserDaoImpl();
}
@Override
public User login(String userCode, String psssword) {
Connection connection = null;
User user = null;
try {
connection = BaseDao.getConnection();
user = userDao.getLoginUser(connection,userCode);
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
BaseDao.closeResource(connection,null,null);
}
if (psssword.equals(user.getUserPassword())){//判断密码是否正确
return user;
}else{
return null;
}
}
@Test
public void test1(){
UserServiceImpl userService = new UserServiceImpl();
User admin = userService.login("lxw", "777777");
System.out.println(admin.getUserPassword());
}
}
2.7编写servlet
package com.badwei.servlet.user;
import com.badwei.pojo.User;
import com.badwei.service.user.UserServiceImpl;
import com.badwei.util.Constants;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class LoginServlet extends HttpServlet {
//servlet控制层,调用业务层代码
@Override
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);
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);
}
}
2.8xml注册servlet
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>com.badwei.servlet.user.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/login.do</url-pattern>
</servlet-mapping>
2.9测试
3.登录功能优化完善
目标:
- 实现注销
- 增加登录拦截(防止用户在未登录时访问主页面)
3.1注销功能
思路:移除session,返回登录页面
package com.badwei.servlet.user;
import com.badwei.util.Constants;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class LogoutServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//移除用户的Session
req.getSession().removeAttribute(Constants.USER_SESSION);
resp.sendRedirect("/login.jsp");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
注册xml
<servlet>
<servlet-name>LogoutServlet</servlet-name>
<servlet-class>com.badwei.servlet.user.LogoutServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LogoutServlet</servlet-name>
<url-pattern>/jsp/logout.do</url-pattern>
</servlet-mapping>
3.2登录拦截优化(过滤器)
避免用户直接访问到地址
package com.badwei.filter;
import com.badwei.pojo.User;
import com.badwei.util.Constants;
import javax.servlet.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class SysFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request1 = (HttpServletRequest)request;
HttpServletResponse response1 = (HttpServletResponse) response;
//从session中获取用户
User user = (User)request1.getSession().getAttribute(Constants.USER_SESSION);
if (user == null){
response1.sendRedirect("/error.jsp");
}else{
chain.doFilter(request,response);
}
}
}
注册xml
<filter>
<filter-name>SysFilter</filter-name>
<filter-class>com.badwei.filter.SysFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>SysFilter</filter-name>
<url-pattern>/jsp/*</url-pattern>
</filter-mapping>
3.3测试
登录,注销,访问权限都保证测试成功。
4.密码修改
4.1写项目的架构
4.2.准备工作:前端页面导入
4.3UserDao接口
//修改当前用户密码
public int updatePwd(Connection connection,int id,String password) throws SQLException;
4.4UserDao实现类
//修改当前用户密码
@Override
public int updatePwd(Connection connection, int id, String password) throws SQLException {
//测试
System.out.println("UserDaoImpl的password=" + password);
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, pstm, sql, params);
BaseDao.closeResource(null, pstm, null);
}
return execute;
}
4.5UserService层
//根据用户id修改密码
public boolean updatePwd(int id,String pwd);
4.6UserService实现类
@Override
public boolean updatePwd(int id, String pwd) {
Connection connection = null;
//测试
System.out.println("UserServiceImpl的pwd=" + pwd);
boolean flag = false;
try {
connection = BaseDao.getConnection();
if (userDao.updatePwd(connection,id,pwd)>0) {
flag = true;
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
BaseDao.closeResource(connection,null,null);
}
return flag;
}
4.7UserServlet
实现复用,提取出方法,在 dao层 和 service层 自己写映射类和实现类
下面是 servlet层 的主体
package com.badwei.servlet.user;
import com.badwei.pojo.User;
import com.badwei.service.user.UserServiceImpl;
import com.badwei.util.Constants;
import com.mysql.jdbc.StringUtils;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
//实现servlet复用
public class UserServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String method = req.getParameter("method");
if ("savepwd".equals(method)){
this.updatePwd(req,resp);
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
public void updatePwd(HttpServletRequest req, HttpServletResponse resp){
Object o = req.getSession().getAttribute(Constants.USER_SESSION);
String newpassword = req.getParameter("newpassword");
//测试
System.out.println("UserServlet的newpassword=" + newpassword);
boolean flag = false;
System.out.println(((User)o).toString());
if (o!=null && !StringUtils.isNullOrEmpty(newpassword)){
UserServiceImpl 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();
}
}
}
4.8Servlet注册web.xml
<servlet>
<servlet-name>UserServlet</servlet-name>
<servlet-class>com.badwei.servlet.user.UserServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UserServlet</servlet-name>
<url-pattern>/jsp/user.do</url-pattern>
</servlet-mapping>
5.密码修改功能优化完善
目标:
- 利用Ajax增加对旧密码的验证(使用阿里巴巴的fastjson)
5.1导包依赖
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.76</version>
</dependency>
5.2Servlet中新增判断旧密码的方法
package com.badwei.servlet.user;
import com.alibaba.fastjson.JSONArray;
import com.badwei.pojo.User;
import com.badwei.service.user.UserServiceImpl;
import com.badwei.util.Constants;
import com.mysql.jdbc.StringUtils;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.HashSet;
//实现servlet复用
public class UserServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String method = req.getParameter("method");
if ("savepwd".equals(method)){//修改密码
this.updatePwd(req,resp);
}
if ("pwdmodify".equals(method)){//验证旧密码
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){
Object o = req.getSession().getAttribute(Constants.USER_SESSION);
String newpassword = req.getParameter("newpassword");
//测试
System.out.println("UserServlet的newpassword=" + newpassword);
boolean flag = false;
System.out.println(((User)o).toString());
if (o!=null && !StringUtils.isNullOrEmpty(newpassword)){
UserServiceImpl 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();
}
}
//验证旧密码
public void pwdModify(HttpServletRequest req, HttpServletResponse resp){
Object o = req.getSession().getAttribute(Constants.USER_SESSION);
String oldpassword = req.getParameter("oldpassword");
//万能的Map
HashMap<String,String> resultMap = new HashMap<>();
if (o==null){//session过期
resultMap.put("result","sessionerror");
}else if(StringUtils.isNullOrEmpty(oldpassword)) {//输入密码为空
resultMap.put("result","error");
}else{
String userPassword = ((User) o).getUserPassword();
if (userPassword.equals(oldpassword)) {
resultMap.put("result","true");
}else{
resultMap.put("result","false");
}
}
try {
resp.setContentType("application/json");
PrintWriter writer = resp.getWriter();
//阿里巴巴的JSON工具类
/*
resultMap = ["result","sessionerror","result","error"]
JSON = {key: value}
*/
writer.write(JSONArray.toJSONString(resultMap));
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
5.3测试功能是否正常
密码输入错误:
密码输入正确
6.用户管理实现
步骤
- UserDao
- UserDaoImpl
- UserService
- UserServiceImpl
流程:
准备:
编写PageSupport.java作为页面的管理
package com.badwei.util;
public class PageSupport {
//当前页码-来自于用户输入
private int currentPageNo = 1;
//总数量(表)
private int totalCount = 0;
//页面容量
private int pageSize = 0;
//总页数-totalCount/pageSize(+1)
private int totalPageCount = 1;
public int getCurrentPageNo() {
return currentPageNo;
}
public void setCurrentPageNo(int currentPageNo) {
if(currentPageNo > 0){
this.currentPageNo = currentPageNo;
}
}
public int getTotalCount() {
return totalCount;
}
public void setTotalCount(int totalCount) {
if(totalCount > 0){
this.totalCount = totalCount;
//设置总页数
this.setTotalPageCountByRs();
}
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
if(pageSize > 0){
this.pageSize = pageSize;
}
}
public int getTotalPageCount() {
return totalPageCount;
}
public void setTotalPageCount(int totalPageCount) {
this.totalPageCount = totalPageCount;
}
public void setTotalPageCountByRs(){
if(this.totalCount % this.pageSize == 0){
this.totalPageCount = this.totalCount / this.pageSize;
}else if(this.totalCount % this.pageSize > 0){
this.totalPageCount = this.totalCount / this.pageSize + 1;
}else{
this.totalPageCount = 0;
}
}
}
6.1获取用户数量
6.1-1、UserDao
//查询用户总数
public int getUserCount(Connection connection,String username,int userRole)throws SQLException;
6.1-2、UserDaoImpl
//根据用户名或角色查询用户总数
public int getUserCount(Connection connection,String username,int userRole) throws SQLException{
PreparedStatement pstm = null;
ResultSet rs = null;
int count = 0;
if (connection!=null){
StringBuffer sql = new StringBuffer();
sql.append("SELECT count(1) as count FROM smbms_user 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:0
}
Object[] params = list.toArray();
System.out.println("UserDaoImpl->getUserCount():" + sql.toString());
rs = BaseDao.execute(connection, pstm, rs, sql.toString(), params);
if (rs.next()){
count = rs.getInt("count");//从结果集中获取最终的数量
}
BaseDao.closeResource(null,pstm,rs);
}
return count;
}
6.1-3、UserService
//查询记录数
public int getUserCount(String username,int userRole);
6.1-4、UserServiceImpl
@Override
public int getUserCount(String username, int userRole) {
Connection connection = null;
int count = 0;
try {
connection = BaseDao.getConnection();
count = userDao.getUserCount(connection, username, userRole);
} catch (Exception e) {
e.printStackTrace();
} finally {
BaseDao.closeResource(connection,null,null);
}
return count;
}
6.2获取用户列表
6.2-1、UserDao
//获取用户列表
public List<User> getUserList(Connection connection,String userName,int userRole,int currentPageNo,int pageSize)throws SQLException;
6.2-2、UserDaoImpl
@Override
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<>();
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<>();
if(!StringUtils.isNullOrEmpty(userName)){
sql.append(" and u.userName like ?");
list.add("%"+userName+"%");
}
if(userRole > 0){
sql.append(" and u.userRole = ?");
list.add(userRole);
}
//在数据库中,分页显示 limit startIndex,pageSize;总数
//当前页 (当前页-1)*页面大小
//0,5 1,0 01234
//5,5 5,0 56789
//10,5 10,0 10~
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());
System.out.println(Arrays.toString(params));
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);
}
System.out.println(Arrays.toString(userList.toArray()));
return userList;
}
6.2-3、UserService
//根据条件查询用户列表
public List<User> getUserList(String queryUserName,int queryRole,int currentPageNo,int pageSize);
6.2-4、UserServiceImpl
@Override
public List<User> getUserList(String queryUserName, int queryUserRole, int currentPageNo, int pageSize) {
Connection connection = null;
List<User> userList = null;
System.out.println("queryUserName ---- > " + queryUserName);
System.out.println("queryUserRole ---- > " + queryUserRole);
System.out.println("currentPageNo ---- > " + currentPageNo);
System.out.println("pageSize ---- > " + pageSize);
try {
connection = BaseDao.getConnection();
userList = userDao.getUserList(connection, queryUserName,queryUserRole,currentPageNo,pageSize);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
BaseDao.closeResource(connection, null, null);
}
return userList;
}
6.3获取角色操作
为了我们的职责统一,我们可以把角色的操作单独放在一个包中,和pojo类对应。。。
6.3-1、RoleDao
package com.badwei.dao.role;
import com.badwei.pojo.Role;
import java.sql.Connection;
import java.util.List;
public interface RoleDao {
//获取角色列表
public List<Role> getRoleList(Connection connection)throws Exception;
}
6.3-2、RoleDaoImpl
package com.badwei.dao.role;
import com.badwei.dao.BaseDao;
import com.badwei.pojo.Role;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
public class RoleDaoImpl implements RoleDao{
@Override
public List<Role> getRoleList(Connection connection) throws Exception {
PreparedStatement pstm = null;
ResultSet rs = null;
List<Role> roleList = new ArrayList<>();
if (connection != null) {
String sql = "select * from smbms_role";
Object[] params = {};
rs = BaseDao.execute(connection, pstm, 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, pstm, rs);
}
return roleList;
}
}
6.3-3、RoleService
package com.badwei.service.role;
import com.badwei.pojo.Role;
import java.util.List;
public interface RoleService {
//角色列表查询
public List<Role> getRoleList();
}
6.3-4、RoleServiceImpl
package com.badwei.service.role;
import com.badwei.dao.BaseDao;
import com.badwei.dao.role.RoleDao;
import com.badwei.dao.role.RoleDaoImpl;
import com.badwei.pojo.Role;
import java.sql.Connection;
import java.util.List;
public class RoleServiceImpl implements RoleService{
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 (Exception e) {
e.printStackTrace();
}finally{
BaseDao.closeResource(connection, null, null);
}
return roleList;
}
}
6.4Servlet显示
- 获取用户前端的数据(查询)
- 判断请求是否需要执行,看参数的值判断
- 为了实现分页,需要计算出当前页面和总页面,页面大小…
- 用户列表展示
- 返回前端
UserServlet
public void query(HttpServletRequest req, HttpServletResponse resp){
//查询用户列表
//从前端获取数据
String queryUsername = req.getParameter("queryname");
String temp = 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 (temp!=null && !temp.equals("")){
queryUserRole = Integer.parseInt(temp);
System.out.println("用户等级:" + queryUserRole);
}
if (pageIndex!=null){
try {
currentPageNo = Integer.parseInt(pageIndex);
} catch (NumberFormatException e) {
e.printStackTrace();
}
}
//获取用户总数
int totalCount = userService.getUserCount(queryUsername, queryUserRole);
//总页数支持
PageSupport pageSupport = new PageSupport();
pageSupport.setCurrentPageNo(currentPageNo);
pageSupport.setPageSize(pageSize);
pageSupport.setTotalCount(totalCount);
int totalPageCount = pageSupport.getTotalPageCount();
//控制首页和尾页
//如果页面小于1,显示第一页
if (currentPageNo<1){
currentPageNo = 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();
} catch (IOException e) {
e.printStackTrace();
}
}
狂神建议---->小黄鸭调试法:自言自语
7.项目原理流程图
8.待完善... ...(已完善)
项目到此为止实现了
-
完整的登录功能
-
完整的密码修改功能
-
用户管理功能(未实现增加用户及部分细节请求)
未实现的:
- 订单管理
- 供应商管理
待完善... ...
完善后:
实现了项目的完整功能,自此,项目功能包括:
1.登录
2.密码修改
3.用户管理
4.订单管理
5.供应商管理
1.登录界面:
2.订单管理:
3.供应商管理
4.用户管理
5.密码修改
9.javaweb总结
通过狂神javaweb课以及超市订单管理系统项目的实现,收获颇多。加油!
评论区