SMBMS
•
Java
SMBMS(Supermarket Billing Management System )
1. Project structure
2. Preparation for project construction
3. Realization of login function
1. Write front page
2. Set home page
<!--设置欢迎页面-->
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>
3. Write Dao layer and user login interface
package com.wang.dao.user;
import com.wang.pojo.User;
import java.sql.Connection;
import java.sql.sqlException;
public interface UserDao {
//得到登录的用户
public User getLoginUser(Connection connection,String userCode) throws sqlException;
}
4. Write the implementation class of Dao interface
package com.wang.dao.user;
import com.wang.dao.BaseDao;
import com.wang.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 rs = null;
User user = null;
if (connection != null) {
String sql = "select * from smbms_user where userCode = ?";
Object[] params = {userCode};
rs = BaseDao.execute(connection,sql,params,rs,pstm);
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;
}
}
5. Business layer interface
package com.wang.service.user;
import com.wang.pojo.User;
public interface UserService {
//用户登录
public User login(String userCode,String password);
}
6. Business layer implementation
package com.wang.service.user;
import com.wang.dao.BaseDao;
import com.wang.dao.user.UserDao;
import com.wang.dao.user.UserDaoImpl;
import com.wang.pojo.User;
import org.junit.Test;
import java.sql.Connection;
import java.sql.sqlException;
public class UserServiceImpl implements UserService {
//业务层都会调用dao层,因此我们要引入dao层
private UserDao userDao;
public UserServiceImpl() {
userDao = new UserDaoImpl();
}
@Override
public User login(String userCode,String password) {
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);
}
return user;
}
@Test
public void test() {
UserServiceImpl userService = new UserServiceImpl();
User admin = userService.login("admin","1234567");
System.out.println(admin.getUserPassword());
}
}
7. Write Servlet
package com.wang.servlet.user;
import com.wang.pojo.User;
import com.wang.service.user.UserServiceImpl;
import com.wang.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,IOException {
doGet(req,resp);
}
}
8. Register Servlet
<!--Servlet-->
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>com.wang.servlet.user.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/login.do</url-pattern>
</servlet-mapping>
9. Test access to ensure that the above functions can be realized
4. Login function optimization
Logout function:
Idea: remove the session and return to the login page
package com.wang.servlet.user;
import com.wang.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,IOException {
//移除用户的Session
req.getSession().removeAttribute(Constants.USER_SESSION);
//返回登录页面
resp.sendRedirect(req.getContextPath() + "/login.jsp");
}
@Override
protected void doPost(HttpServletRequest req,resp);
}
}
Register XML
<servlet>
<servlet-name>logoutServlet</servlet-name>
<servlet-class>com.wang.servlet.user.logoutServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>logoutServlet</servlet-name>
<url-pattern>/jsp/logout.do</url-pattern>
</servlet-mapping>
Login interception optimization
Write filters and register
package com.wang.filter;
import com.wang.pojo.User;
import com.wang.util.Constants;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class SysFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest req,ServletResponse resp,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 {
chain.doFilter(req,resp);
}
}
@Override
public void destroy() {
}
}
<!--用户登录过滤器-->
<filter>
<filter-name>SysFilter</filter-name>
<filter-class>com.wang.filter.SysFilter</filter-class>
</filter>
<!--所有的访问jsp目录下的资源都会被过滤-->
<filter-mapping>
<filter-name>SysFilter</filter-name>
<url-pattern>/jsp/*</url-pattern>
</filter-mapping>
5. Password modification
1. Import front-end materials
2. Write the project from the bottom up
3. Userdao interface
//修改当前用户的密码
public int updatePwd(Connection connection,int id,int password) throws sqlException;
4. Userdao implementation class
//修改当前用户的密码,返回受影响的行数
@Override
public int updatePwd(Connection connection,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,pstm);
BaseDao.closeResource(null,null);
}
return execute;
}
5. Userservice interface
//根据用户ID修改密码
public boolean updatePwd(int id,int pwd);
6. Userservice implementation class
@Override
public boolean updatePwd(int id,int pwd) {
Connection connection = null;
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);
}
return flag;
}
7. Remember to extract methods to realize reuse!
package com.wang.servlet.user;
import com.MysqL.jdbc.StringUtils;
import com.wang.pojo.User;
import com.wang.service.user.UserService;
import com.wang.service.user.UserServiceImpl;
import com.wang.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;
//实现Servlet服用
public class UserServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req,IOException {
String method = req.getParameter("method");
if (method.equals("savepwd") && method != null) {
this.updatePwd(req,resp);
}
}
@Override
protected void doPost(HttpServletRequest req,resp);
}
public void updatePwd(HttpServletRequest req,HttpServletResponse resp) {
//从Session里面拿ID
Object o = req.getSession().getAttribute(Constants.USER_SESSION);
String newpassword = req.getParameter("newpassword");
boolean flag = false;
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();
}
}
}
8. Register Servlet
<servlet>
<servlet-name>UserServlet</servlet-name>
<servlet-class>com.wang.servlet.user.UserServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UserServlet</servlet-name>
<url-pattern>/jsp/user.do</url-pattern>
</servlet-mapping>
6. Optimize password modification: use ajax
1. Introduce Alibaba's fastjson
2. Background code modification
//验证旧密码,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<>();
if (o == null) {
//Session失效了,Session过期了
resultMap.put("result","sessionerror");
} else if (StringUtils.isNullOrEmpty(oldpassword)) {
resultMap.put("result","error");
} else {
//Session用户的密码
String userPassword = ((User) o).getUserPassword();
if (oldpassword.equals(userPassword)) {
resultMap.put("result","true");
} else {
resultMap.put("result","false");
}
}
try {
//限定响应返回的格式为json
resp.setContentType("application/json");
PrintWriter writer = resp.getWriter();
//JSONArray 阿里巴巴的JSON工具类转换格式
/*
把resultMap转为JSON格式
*/
writer.write(JSONArray.toJSONString(resultMap));
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
7. Implementation of user management
1. Ideas
2. Import pagination tool class
3. User list page import
4. Get the number of users
//根据用户名或者角色查询用户总数
public int getUserCount(Connection connection,String username,int userRole) throws sqlException;
//根据用户名或者角色查询用户总数
@Override
public int getUserCount(Connection connection,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 as u,smbms_role as 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 like ?");
list.add(userRole); //index = 1
}
//把list转为数组
Object[] objects = list.toArray();
rs = BaseDao.execute(connection,sql.toString(),objects,pstm);
if (rs.next()) {
//从结果集中获得最终的结果
count = rs.getInt("count");
}
BaseDao.closeResource(null,rs);
}
return count;
}
//查询记录数
public int getUserCount(String username,int userRole);
//查询记录数
@Override
public int getUserCount(String username,int userRole) {
Connection connection = null;
int userCount = 0;
try {
connection = BaseDao.getConnection();
userCount = userDao.getUserCount(connection,userRole);
} catch (sqlException throwables) {
throwables.printStackTrace();
} finally {
BaseDao.closeResource(connection,null);
}
return userCount;
}
5. Get user list
//通过条件查询-userlist
public List<User> getUserList(Connection connection,String userName,int userRole,int currentPageNo,int pageSize) throws sqlException;
//通过条件查询-userlist
@Override
public List<User> getUserList(Connection connection,int pageSize) throws sqlException {
PreparedStatement pstm = null;
ResultSet rs = null;
ArrayList<User> userList = new ArrayList<>();
if (connection != null) {
StringBuffer sql = new StringBuffer();
sql.append("select u.*,r.roleName userRoleName from smbms_user as u join smbms_role as r on 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 like ?");
list.add(userRole); //index = 1
}
//在数据库中,分页使用limit startIndex,pageSize; 总数
//0,5
//6,5
//(当前页-1)*页面大小
sql.append("order by creationDate desc limit ?,?");
currentPageNo = (currentPageNo - 1) * pageSize;
list.add(currentPageNo);
list.add(pageSize);
Object[] params = list.toArray();
rs = BaseDao.execute(connection,pstm);
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,rs);
}
return userList;
}
//根据条件查询用户列表
public List<User> getUserList(String queryUserName,int queryUserRole,int pageSize);
//根据条件查询用户列表
@Override
public List<User> getUserList(String queryUserName,int pageSize) {
Connection connection = null;
List<User> userList = null;
try {
connection = BaseDao.getConnection();
userList = userDao.getUserList(connection,queryUserName,queryUserRole,currentPageNo,pageSize);
} catch (sqlException throwables) {
throwables.printStackTrace();
} finally {
BaseDao.closeResource(connection,null);
}
return userList;
}
6. Get role operation
In order to unify our responsibilities, we can put the role operations in a separate package, corresponding to the POJO class
RoleDao
public interface RoleDao {
//获取角色列表
public List<Role> getRoleList(Connection connection) throws sqlException;
}
RoleDaoImpl
package com.wang.dao.role;
import com.wang.dao.BaseDao;
import com.wang.pojo.Role;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.sqlException;
import java.util.List;
public class RoleDaoImpl implements RoleDao{
//获取角色列表
@Override
public List<Role> getRoleList(Connection connection) throws sqlException {
PreparedStatement pstm = null;
ResultSet rs = null;
List<Role> roleList = null;
if (connection != null) {
String sql = "select * from smbms_role";
Object[] params = null;
rs = BaseDao.execute(connection,pstm);
while (rs.next()) {
Role _role = new Role();
_role.setId(rs.getInt("id"));
_role.setRoleName(rs.getString("roleName"));
_role.setRoleCode(rs.getString("roleCode"));
roleList.add(_role);
}
BaseDao.closeResource(null,rs);
}
return roleList;
}
}
RoleService
package com.wang.service.role;
import com.wang.pojo.Role;
import java.util.List;
public interface RoleService {
//获取角色列表
public List<Role> getRoleList();
}
RoleServiceImpl
package com.wang.service.role;
import com.wang.dao.BaseDao;
import com.wang.dao.role.RoleDao;
import com.wang.dao.role.RoleDaoImpl;
import com.wang.pojo.Role;
import java.sql.Connection;
import java.sql.sqlException;
import java.util.List;
public class RoleServiceImpl implements RoleService{
//引入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(connection,null);
}
return roleList;
}
}
7. Servlet displayed by the user
//重点,难点
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); //给查询赋值
} if (pageIndex != null) {
currentPageNo = Integer.parseInt(pageIndex);
}
//获取用户的总数(分页:上一页,下一页)
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 (totalPageCount < 1) {
currentPageNo = 1;
} else if (currentPageNo > totalPageCount){
//当前页面大于最后一页
currentPageNo = totalPageCount;
}
//获取用户列表展示
userList = userService.getUserList(queryUserName,pageSize);
req.setAttribute("userList",userList);
//展示角色列表
RoleServiceImpl roleService = new RoleServiceImpl();
List<Role> roleList = roleService.getRoleList();
req.setAttribute("roleList",roleList);
req.setAttribute("queryUserName",queryUserName);
req.setAttribute("queryUserRole",queryUserRole);
//展示分页
req.setAttribute("totalCount",totalCount);
req.setAttribute("currentPageNo",currentPageNo);
req.setAttribute("totalPageCount",totalPageCount);
//返回前端
try {
req.getRequestDispatcher("userlist.jsp").forward(req,resp);
} catch (ServletException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码