1. Smbms (supermarket management project)
[external chain picture transfer failed. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-r5ny1ksq-1632046547618) (smbms (supermarket management project)]. assets/20200516122458676.png)
Database:
[external chain picture transfer failed. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-jvt6c7nf-1632046547622) (smbms (supermarket management project)]. assets/20200516122532275.png)
How to build the project?
Consider using maven? jar package, dependency
2. Construction project preparation
1. Build a maven web project
2. Configure Tomcat
3. Test whether the project can run
4. Import the jar package required in the project;
jsp, Servlet, mysql driver, jstl, stand
<dependencies> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> </dependency> <!-- https://mvnrepository.com/artifact/javax.servlet.jsp/javax.servlet.jsp-api --> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api</artifactId> <version>2.3.3</version> <scope>provided</scope> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.47</version> </dependency> <!-- https://mvnrepository.com/artifact/javax.servlet.jsp.jstl/jstl-api --> <dependency> <groupId>javax.servlet.jsp.jstl</groupId> <artifactId>jstl-api</artifactId> <version>1.2</version> </dependency> <!-- https://mvnrepository.com/artifact/taglibs/standard --> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> </dependency> </dependencies>
5. Build project package structure
[external chain picture transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-cvis6hxk-1632046547626) (smbms (supermarket management project)]. assets/202005161230352.png)
6. Write entity class
ROM mapping: table class mapping
7. Preparation of basic public classes
7.1 database configuration file (the preparation of mysql5.xx and 8.xx is different)
driver=com.mysql.jdbc.Driver #In the process of transferring data with mysql, the unicode encoding format is used, and the character set is set to utf-8 url=jdbc:mysql://localhost:3306?useUnicode=true&characterEncoding=utf-8 username=root password=123456
7.2 compiling public classes of database
/** * Public class for operating database */ public class BaseDao { private static String driver; private static String url; private static String username; private static String password; //Static code block. Class is initialized when it is loaded static { Properties properties = new Properties(); //Read the corresponding resources through the class loader 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"); } //Get database connection public static Connection getConnection(){ Connection connection = null; try { Class.forName(driver); connection = DriverManager.getConnection(url, username, password); } catch (Exception e) { e.printStackTrace(); } return connection; } //Write query public methods public static ResultSet execute(Connection connection,String sql,Object[] params,ResultSet resultSet,PreparedStatement preparedStatement) throws SQLException { //Precompiled sql can be executed directly later preparedStatement = connection.prepareStatement(sql); for (int i = 0; i < params.length; i++) { //setObject, placeholders start with 1, but our array starts with 0 preparedStatement.setObject(i+1,params[i]); } resultSet = preparedStatement.executeQuery(); return resultSet; } //Prepare public methods for addition, deletion, modification and query 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++) { //setObject, placeholders start with 1, but our array starts with 0 preparedStatement.setObject(i+1,params[i]); } int updateRows = preparedStatement.executeUpdate(); return updateRows; } //Release resources public static boolean closeResource(Connection connection,PreparedStatement preparedStatement,ResultSet resultSet){ boolean flag = true; if (resultSet!=null){ try { resultSet.close(); //gc recovery resultSet = null; } catch (SQLException e) { e.printStackTrace(); flag = false; } } if (preparedStatement!=null){ try { preparedStatement.close(); //gc recovery preparedStatement = null; } catch (SQLException e) { e.printStackTrace(); flag = false; } } if (connection!=null){ try { connection.close(); //gc recovery connection = null; } catch (SQLException e) { e.printStackTrace(); flag = false; } } return flag; } }
7.3 writing character encoding filters
public class CharacterEncodingFilter implements Filter{ public void init(FilterConfig filterConfig) throws ServletException { } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); chain.doFilter(request,response); } public void destroy() { } }
<filter> <filter-name>Filter</filter-name> <filter-class>com.tree.filter.CharacterEncodingFilter</filter-class> </filter> <filter-mapping> <filter-name>Filter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
- 4 import static resources
3. Implementation of login function
[external chain picture transfer failed. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-cfke0nph-1632046547634) (smbms (supermarket management project)]. assets/20200516125301633.png)
1. Write front page
2. Set home page
2.1 setting welcome home page
<welcome-file-list> <welcome-file>login.jsp</welcome-file> </welcome-file-list>
3. Write dao layer login user login interface
public interface UserDao { //Get the user to log in public User getLoginUser(Connection connection,String userCode,String userPassword) throws SQLException; }
4. Write the implementation class of dao layer interface
public class UserDaoImpl implements UserDao { //The persistence layer only queries the contents of the database public User getLoginUser(Connection connection, String userCode,String userPasswrod) throws SQLException { PreparedStatement pstm = null; ResultSet rs = null; User user = null; //Determine whether the connection is successful if(null!=connection) { String sql = "select * from smbms_user where userCode=? and userPassword=?"; Object[] params = {userCode,userPasswrod}; 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.getDate("creationDate")); user.setModifyBy(rs.getInt("modifyBy")); user.setModifyDate(rs.getDate("modifyDate")); } BaseDao.closeResource(null,pstm,rs); } return user; } }
5. Business layer interface
public interface UserService { //User login public User login(String userCode,String userPassword); }
6. Business layer implementation class
public class UserServiceImpl implements UserService { //The business layer will call the Dao layer, so we introduce the Dao layer private UserDao userDao; public UserServiceImpl(){ userDao = new UserDaoImpl(); } public User login(String userCode, String userPassword) { Connection connection = null; User user = null; try { connection = BaseDao.getConnection(); //Call the corresponding database operation through the business layer user = userDao.getLoginUser(connection,userCode,userPassword); } catch (SQLException e) { e.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
public class LoginServlet extends HttpServlet { //Servlet control layer, calling business layer code @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("LoginServlet----start..."); //Get user name and password String userCode = req.getParameter("userCode"); String userPassword = req.getParameter("userPassword"); //Compared with the password in the database, call the business layer UserServiceImpl userService = new UserServiceImpl(); User user = userService.login(userCode, userPassword); if(user!=null){ //Store user information in Session req.getSession().setAttribute(Constants.USER_SESSION,user); //Jump to home page resp.sendRedirect("jsp/frame.jsp"); }else { req.setAttribute("error","Username or password incorrect "); req.getRequestDispatcher("login.jsp").forward(req,resp); } } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
Constants class
public class Constants { public final static String USER_SESSION = "userSession"; }
8. Register Servlet
<servlet> <servlet-name>LoginServlet</servlet-name> <servlet-class>com.tree.servlet.user.LoginServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>LoginServlet</servlet-name> <url-pattern>/login.do</url-pattern> </servlet-mapping>
4. Login function optimization
4.1 logout function
Idea: remove the session and return to the login page
public class LogoutServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //Clear 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); } }
Register xml
<!--Log out xml--> <servlet> <servlet-name>logout</servlet-name> <servlet-class>com.tree.servlet.user.LogoutServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>logout</servlet-name> <url-pattern>/jsp/logout.do</url-pattern> </servlet-mapping>
4.2 login interception optimization
Write a filter and register it
public class SysFilter implements Filter { public void init(FilterConfig filterConfig) throws ServletException { } public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest)req; HttpServletResponse response = (HttpServletResponse)resp; User user = (User) request.getSession().getAttribute(Constants.USER_SESSION); if(user==null){ response.sendRedirect("/smbms/error.jsp"); }else { chain.doFilter(req,resp); } } public void destroy() { } }
<!--Login interception optimization filter--> <filter> <filter-name>loginFilter</filter-name> <filter-class>com.tree.filter.SysFilter</filter-class> </filter> <filter-mapping> <filter-name>loginFilter</filter-name> <url-pattern>/jsp/*</url-pattern> </filter-mapping>
Test, login, logout and permission should be OK
5. Password modification
1. Import front-end materials
<li><a href="${pageContext.request.contextPath }/jsp/pwdmodify.jsp">Password modification</a></li>
2. Write the project from the bottom up
[external chain picture transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-w68iwiqc-16320465471) (smbms (supermarket management project)]. assets/20200516180913135.png)
3. UserDao interface
//Modify current password public int updatePwd(Connection connection,int id,String password) throws SQLException;
4. UserDao interface implementation
//Modify current password public int updatePwd(Connection connection, int id, String 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, sql, params); BaseDao.closeResource(null,pstm,null); } return execute; }
5. UserService layer
//Change password according to user ID public boolean updatePwd(int id,String pwd);
6. UserService interface implementation
//Change password according to user ID public boolean updatePwd(int id, String pwd) { Connection connection = null; boolean flag = false; try { connection = BaseDao.getConnection(); if(userDao.updatePwd(connection,id,pwd)>0){ flag = true; } } catch (SQLException e) { e.printStackTrace(); }finally { BaseDao.closeResource(connection,null,null); } return flag; }
7. Remember to realize reuse and extract methods!
Write your own mapping class and implementation class in dao layer and service layer
Below is the body of the servlet layer
public void updatePwd(HttpServletRequest req, HttpServletResponse resp){ Object session = req.getSession().getAttribute(Constants.USER_SESSION); String newpassword = req.getParameter("newpassword"); boolean flag = false; if(session!=null && newpassword!=null){ UserServiceImpl userService = new UserServiceImpl(); flag = userService.updatePwd(((User) session).getId(), newpassword); if(flag){ req.setAttribute("message","The password is modified successfully. Please exit and log in with the new password"); req.getSession().removeAttribute(Constants.USER_SESSION); }else { req.setAttribute("message","Password modification failed"); } }else { req.setAttribute("message","There is a problem with the new password"); } try { req.getRequestDispatcher("pwdmodify.jsp").forward(req,resp); } catch (ServletException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
Register xml
<servlet> <servlet-name>UserServlet</servlet-name> <servlet-class>com.tree.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 using Ajax
- Alibaba fastjson
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.68</version> </dependency>
- Background code modification
import java.io.IOException; import java.io.PrintWriter; //import java.io.Writer; import java.sql.SQLException; import java.util.HashMap; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.mysql.cj.util.StringUtils; import com.mysql.cj.xdevapi.JsonArray; //import com.mysql.cj.util.StringUtils; import pojo.User; import service.user.UserService; import service.user.UserServiceImpl; import util.Constants; @SuppressWarnings("serial") public class UserServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // Method stub automatically generated by TODO String method = req.getParameter("method"); if (method.equals( "savepwd") && method != null) { this.updatePwd(req, resp); }else if (method.equals( "pwdmodify") && method != null) { } // If you want to add, delete, or modify a query, you can directly use if (method! = "savepwd" & & method! = null); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // Method stub automatically generated by TODO doGet(req, resp); } public void updatePwd(HttpServletRequest req, HttpServletResponse resp) { // Obtain user id through session Object o = req.getSession().getAttribute(Constants.USER_SESSION); String newpassword = req.getParameter("newpassword"); boolean flag = false; if (o != null && newpassword != null) { UserService userService = new UserServiceImpl(); try { flag = userService.updatePwd(((User) o).getId(), newpassword); } catch (SQLException e) { // catch block automatically generated by TODO e.printStackTrace(); } catch (Exception e) { // catch block automatically generated by TODO e.printStackTrace(); } if (flag) { req.setAttribute("message", "The password has been modified successfully. Please exit and log in with a new password"); // The password is modified successfully, and the session is removed (the password cannot be modified again after removal, so it is recommended not to remove it) req.getSession().removeAttribute(Constants.USER_SESSION); } else { // Password modification failed req.setAttribute("message", "Password modification failed"); } } else { // There is a problem with password modification req.setAttribute("message", "There is a problem with the new password"); } try { req.getRequestDispatcher("/jsp/pwdmodify.jsp").forward(req, resp); } catch (ServletException e) { // catch block automatically generated by TODO e.printStackTrace(); } catch (IOException e) { // catch block automatically generated by TODO e.printStackTrace(); } } public void pqdmodify(HttpServletRequest req, HttpServletResponse resp) { // Obtain user id through session Object o = req.getSession().getAttribute(Constants.USER_SESSION); String oldpassword = req.getParameter("oldpassword"); Map<String, String> resultMap = new HashMap<String, String>(); if(o==null) {//session failed. session expired resultMap.put("result","seesionerror"); }else if(StringUtils.isNullOrEmpty(oldpassword)){//The password entered is blank resultMap.put("result","error"); }else {// String userPassword = ((User)o).getUserPassword();//User password in seesion if(oldpassword.equals(userPassword)) { resultMap.put("result","true"); }else { resultMap.put("result","false"); } } try { resp.setContentType("application/josn"); PrintWriter writer = resp.getWriter(); /* * resultMap = ["result","sessionerror","result",error] * josn Format = {key,value */ //writer.write(JSONArray.toJSONString(resultMap)); writer.write(JsonArray.class.toString()); writer.flush(); writer.close(); } catch (IOException e) { // catch block automatically generated by TODO e.printStackTrace(); } } }
- test
7. User management implementation
[external chain picture transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-akusbpup-1632046547643) (smbms (supermarket management project)]. Assets / 2020051721007269. PNG)
- Import pagination tool class - PageSupport
- User list page import - userlist.jsp
1. Get the number of users
- UserDao
//Total number of query users public int getUserCount(Connection connection,String username,int userRole) throws SQLException;
- 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<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); } 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; }
- UserServiceImpl
//Number of query records public int getUserCount(String username,int userRole);
- UserServiceImpl
public int getUserCount(String username, int userRole) { Connection connection = null; int count = 0; try { connection = BaseDao.getConnection(); count = userDao.getUserCount(connection, username, userRole); } catch (SQLException e) { e.printStackTrace(); }finally { BaseDao.closeResource(connection,null,null); } return count; }
2. Get user list
- UserDao
//Get user list public List<User> getUserList(Connection connection,String username,int userRole,int currentPageNo,int pageSize) throws SQLException;
- UserDaoImpl
//Get user list 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(); rs = BaseDao.execute(connection, pstm, rs, sql.toString(), params); if(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); } } return userList; }
- UserService
//Query user list by criteria public List<User> getUserList(String queryUserName,int queryUserRole,int currentPageNo,int pageSize);
- UserServiceImpl
public List<User> getUserList(String queryUserName, int queryUserRole, int currentPageNo, int pageSize) { Connection connection = null; List<User> userList = null; try { connection = BaseDao.getConnection(); userDao.getUserList(connection,queryUserName,queryUserRole,currentPageNo,pageSize); } catch (SQLException e) { e.printStackTrace(); }finally { BaseDao.closeResource(connection,null,null); } return userList; }
3. Get role action
In order to unify our responsibilities, we can put the role operations in a separate package, corresponding to the pojo class...
- RoleDao
//Get role list public List<Role> getRoleList(Connection connection) throws SQLException;
- RoleDaoImpl
public List<Role> getRoleList(Connection connection) throws SQLException { PreparedStatement pstm = null; ResultSet rs = null; List<Role> roleList = new ArrayList<Role>(); 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); } } return roleList; }
- RoleService
//Role list query public List<Role> getRoleList();
- RoleServiceImpl
public class RoleServiceImpl implements RoleService{ private RoleDao roleDao; public RoleServiceImpl() { roleDao = new RoleDaoImpl(); } public List<Role> getRoleList() { Connection connection = null; List<Role> roleList = null; try { connection = BaseDao.getConnection(); roleList = roleDao.getRoleList(connection); } catch (SQLException e) { e.printStackTrace(); }finally { BaseDao.closeResource(connection,null,null); } return roleList; } }