catalogue
Preparation for project construction
Implementation of login function
Implementation of login and logout function
Login interception optimization
Optimize password modification using AJAX
User management implementation
1. Get the number of users queried
4. Integrate resources into servlets
Query specified user information
Order management implementation
Supplier management implementation
Simple user management authority optimization
smbms
Garbled code in browser project: configure tomcat startup parameter - Dfile.encoding=UTF-8
Technical highlights
-
You can use EL expressions to extract request information to the login page
-
Using json to separate the front and back ends
-
Using ajax to update some web pages
-
For addition, deletion and modification, you need to start transaction processing and have a clearer understanding of the characteristics of transactions
-
StringBuffer can be used to realize string splicing, HashMap can be used to encapsulate key value pair parameters and pass them to the front end, list collection can be used to encapsulate and save multiple User classes, list collection can be used to splice parameters, and Object collection can be used to pass parameters
-
Get a clear understanding of MVC three-tier architecture and clear responsibilities for implementation, which is convenient for later maintenance and development
-
Multi use identifier switching control
-
Deeply understand the difference between redirection and request forwarding
-
In the back-end redirection path, you need to fill in the current project path plus the forwarding location. For request forwarding, you only need to fill in the forwarding location
-
The redirection request path will change, and the request forwarding will not change
-
-
Register immediately after writing a servlet (you can directly use the spring MVC framework in the future)
-
Obtain information through fuzzy query
-
The business layer can be said to be a bridge, calling the Dao layer for use by the control layer
System function structure diagram
database
Preparation for project construction
-
Build a template maven webapp project
-
Configure Tomcat
-
Can the test project run
-
Import dependent jar packages:
-
Servlet implements servlet interface
-
jsp jsp tag
-
MySQL connector Java database connection
-
jstl jsp tag library
-
The package that the standard jsp tag library depends on
-
-
Build project structure
-
Writing entity classes
ORM mapping: table ----- > class
-
Write basic public classes
-
Database configuration file
driver=com.mysql.cj.jdbc.Driver url=jdbc:mysql://localhost:3306/smbms?useUnicode=true&characterEncoding=utf8&useSSL=true username=root password=123456
-
Write a common class for the 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 blocks are initialized when the class is loaded static { //Read the corresponding resources through the class loader ClassLoader loader = BaseDao.class.getClassLoader(); InputStream is = loader.getResourceAsStream("db.properties"); Properties properties = new 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 connection to database public static Connection getConnection(){ Connection connection = null; try { Class.forName(driver); connection = DriverManager.getConnection(url, username, password); } catch (Exception e) { e.printStackTrace(); } return connection; } /* Precompiled sql does not need to be transferred to sql during execution */ //Write public classes for queries public static ResultSet execute(Connection connection,String sql,Object[] param,PreparedStatement statement,ResultSet resultSet){ try { statement = connection.prepareStatement(sql); //setObject, the placeholder starts with 1, and the parameter subscript starts with 0 for (int i = 0; i < param.length ; i++) { statement.setObject(i+1,param[i]); } resultSet = statement.executeQuery(); } catch (SQLException e) { e.printStackTrace(); } return resultSet; } //Prepare public classes for addition, deletion and modification public static int execeute(Connection connection,String sql,Object[] param,PreparedStatement statement){ int resultNum = 0; try { statement = connection.prepareStatement(sql); for (int i = 0; i < param.length ; i++) { statement.setObject(i+1,param[i]); } resultNum = statement.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } return resultNum; } //Close the public class of the resource public static boolean close(Connection connection,PreparedStatement statement,ResultSet resultSet){ boolean flag = true; if (resultSet != null){ try { resultSet.close(); //Operation of garbage collection resultSet = null; } catch (SQLException e) { e.printStackTrace(); //If the release is not successful flag = false; } } if (statement != null){ try { statement.close(); statement = null; } catch (SQLException e) { e.printStackTrace(); flag = false; } } if (connection != null){ try { connection.close(); connection = null; } catch (SQLException e) { e.printStackTrace(); flag = false; } } return flag; } }
-
Write character encoding filter
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { servletRequest.setCharacterEncoding("utf-8"); servletResponse.setCharacterEncoding("utf-8"); filterChain.doFilter(servletRequest, servletResponse); }
-
-
Import static resources
Implementation of login function
Idea:
-
Write front-end login page ----- -- > login.jsp
-
Set the welcome page to jump to the login page when the server has started
<!-- Set welcome page --> <welcome-file-list> <welcome-file>login.jsp</welcome-file> </welcome-file-list>
-
Write the Dao layer to get the user login interface
//Query the specified user from the database. There is no need to obtain the connection database object and leave it to the business layer public User getLoginUser(Connection connection,String userCode) throws SQLException;
-
Write the implementation class of Dao layer
public class UserDaoImpl implements UserDao { public User getLoginUser(Connection connection, String userCode) throws SQLException { PreparedStatement statement = null; ResultSet rs = null; User user = null; if (connection != null){ String sql = "select * from `smbms_user` where userCode=?"; Object[] param = {userCode}; rs = BaseDao.execute(connection, sql, param, statement, rs); while (rs.next()){ user = new User(); //Throw these values to the 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.setModifyBy(rs.getInt("modifyBy")); user.setModifyDate(rs.getDate("modifyDate")); } BaseDao.close(null,statement,rs); } return user; } }
-
Write business layer interface
//User login public User login(String userCode,String password) throws SQLException;
-
Write business layer implementation classes
public class UserServiceImpl implements UserService { //The business layer will call the Dao layer, so we need to introduce the Dao layer private UserDao userDao = null; public UserServiceImpl(){ userDao = new UserDaoImpl(); } public User login(String userCode, String password){ Connection connection = null; User user = null; try { connection = BaseDao.getConnection(); //Retrieve the data of the corresponding specific database through the business layer user = userDao.getLoginUser(connection,userCode,password); } catch (SQLException e) { e.printStackTrace(); }finally { BaseDao.close(connection,null,null); } return user; } @Test public void test(){ UserServiceImpl userService = new UserServiceImpl(); User admin = userService.login("admin", "12345678"); System.out.println(admin.getAddress()); } }
-
Write servlet: it is used to obtain the parameters of the front-end request and call the business layer to determine whether the user exists
public class LoginServlet extends HttpServlet { //servlet control layer: call business layer private UserService userService = new UserServiceImpl(); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("LoginServlet-start..."); //Get front-end data String userCode = req.getParameter("userCode"); String userPassword = req.getParameter("userPassword"); User user = null; //Call the corresponding operations of the business layer: compare with the users of the database try { user = userService.login(userCode,userPassword); if (user != null){ //Put the user's information into the session req.getSession().setAttribute(Constant.USER_SESSION,user); //Jump to home page resp.sendRedirect("/resmbms/jsp/frame.jsp"); }else { //Use the request to forward to the login page and prompt the user name or password error req.setAttribute("error","Username or password incorrect "); req.getRequestDispatcher("/login.jsp").forward(req,resp); } } catch (SQLException e) { e.printStackTrace(); } } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
-
Register servlet
<servlet> <servlet-name>LoginServlet</servlet-name> <servlet-class>com.kuang.servlet.user.LoginServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>LoginServlet</servlet-name> <url-pattern>/login.do</url-pattern> </servlet-mapping>
Login function optimization
Implementation of login and logout function
-
Write servlet: used to remove the session attribute and return to the login page
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.getSession().removeAttribute(Constant.USER_SESSION); resp.sendRedirect("/resmbms/login.jsp"); }
-
Register servlet
<servlet> <servlet-name>LogoutServlet</servlet-name> <servlet-class>com.kuang.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
-
In order to ensure that users can no longer enter the home page after logging out, you need to set a filter
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) servletRequest; HttpServletResponse response = (HttpServletResponse) servletResponse; Object userSession = request.getSession().getAttribute(Constant.USER_SESSION); if (userSession == null){ response.sendRedirect("/resmbms/error.jsp"); }else filterChain.doFilter(servletRequest, servletResponse); }
-
Register filter
<filter> <filter-name>SysFilter</filter-name> <filter-class>com.kuang.filter.SysFilter</filter-class> </filter> <filter-mapping> <filter-name>SysFilter</filter-name> <url-pattern>/jsp/*</url-pattern> </filter-mapping>
Password modification
To add, delete, change and query, you must write from low to high
-
Write the interface of Dao layer
//Modify current user password public int pwdModify(Connection connection,int id,String password);
-
Write the implementation class of Dao layer
//Modify current user password public int pwdModify(Connection connection, int id, String password) { PreparedStatement statement = null; int resultNum = 0; if (connection != null){ String sql = "update `smbms_user` set userPassword = ? where id = ? "; Object[] param = {password,id}; resultNum = BaseDao.execeute(connection, sql, param, statement); BaseDao.close(null,statement,null); } return resultNum; }
-
Write the interface of business layer
//Modify current user password public int pwdModify(int id,String password);
-
Write the implementation class of the business layer
//Modify current user password public int pwdModify(int id, String password) { Connection connection = BaseDao.getConnection(); int resultNum = userDao.pwdModify(connection, id, password); BaseDao.close(connection,null,null); return resultNum; }
-
Write control layer
//Change Password protected void pwdModify(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //Get new password parameters from the front end String newPassword = req.getParameter("newpassword"); //Get the id from the session //Don't worry. First judge whether the obtained exists. Code optimization is here // User user = (User) req.getSession().getAttribute(Constant.USER_SESSION); Object o = req.getSession().getAttribute(Constant.USER_SESSION); boolean flag = false; if (o != null && !StringUtils.isNullOrEmpty(newPassword)){ UserService userService = new UserServiceImpl(); flag = userService.pwdModify(((User)o).getId(), newPassword); if (flag){//Indicates that the modification was successful //Carry a parameter to the request req.setAttribute(Constant.MESSAGE,"The password has been modified successfully. Please exit and log in with a new password"); //After password modification, remove the session immediately req.getSession().removeAttribute(Constant.USER_SESSION); }else {//Modification failed //Carry a parameter to the request req.setAttribute(Constant.MESSAGE,"Password modification failed"); } }else { //Carry a parameter to the request req.setAttribute(Constant.MESSAGE,"There is a problem with the new password"); } req.getRequestDispatcher("pwdmodify.jsp").forward(req,resp); }
-
Register servlet
<servlet> <servlet-name>UserServlet</servlet-name> <servlet-class>com.kuang.servlet.user.UserServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>UserServlet</servlet-name> <url-pattern>/jsp/user.do</url-pattern> </servlet-mapping>
Problems encountered in password modification:
Because the old password is not verified, the old password verification is cleared, and because the browser has cached the old password, it cannot be submitted without verifying the old password
Resolution: clear browser cache
Problem: after clearing the cache, the css style cannot be loaded. Check that the response type is text/html instead of text/css
Reason: display all page information in html type in character encoding filter
servlet multiplexing is used to invoke its method in doGet.
Optimize password modification using AJAX
-
Using json to realize front-end and back-end interaction
-
Alibaba fastjson
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.78</version> </dependency>
-
-
Writing servlet s
//Verify old password public void pwdmodify(HttpServletRequest req, HttpServletResponse resp){ //The session contains the user's password. Take the old password from it and compare it with the parameters passed from the front end String oldpassword = req.getParameter("oldpassword"); Object o = req.getSession().getAttribute(Constant.USER_SESSION); //Using map to encapsulate data, everything can be saved using map HashMap<String, String> resultMap = new HashMap<String, String>(); if (o==null){//The session has expired or the session has expired resultMap.put("result","sessionerror"); }else if(StringUtils.isNullOrEmpty(oldpassword)){//The old password is blank resultMap.put("result","error"); }else { if (oldpassword.equals(((User)o).getUserPassword())){//The old password was entered correctly resultMap.put("result","true"); }else { resultMap.put("result","false"); } } //Because the front end uses json, you need to convert the map to json format for the front end to receive try { //Set return type resp.setContentType("application/json"); //Convert the map into JSON format output and use Alibaba's JSON tool class PrintWriter writer = resp.getWriter(); writer.write(JSONArray.toJSONString(resultMap)); writer.flush(); //Close flow operation writer.close(); } catch (IOException e) { e.printStackTrace(); } }
User management implementation
Idea:
Three object-oriented features:
-
Encapsulation (private property, get/set method, some unsafe situations in set method)
-
inherit
-
polymorphic
-
Import pagination tool class
-
View which pages need to be used for user management
-
userlist.jsp
-
1. Get the number of users queried
-
Write the interface of Dao layer
//Query the total number of users by user name or user role public int getUserCount(Connection connection,String username,int userRole) throws SQLException;
-
Write the implementation class of Dao layer
//Query the total number of users by user name or user role public int getUserCount(Connection connection, String username, int userRole) throws SQLException { PreparedStatement statement = null; //Integer cannot be used to wrap. Integer can be null. The result returned here is always of type int int count = 0; ResultSet rs = null; if (connection != null){ //Use the list collection to encapsulate parameters ArrayList<Object> params = new ArrayList<Object>(); //Because the query is based on the user role or user name, you need to use StringBuffer to splice strings StringBuffer sb = new StringBuffer("SELECT count(1) 'count' from `smbms_user` u,`smbms_role` r WHERE u.userRole = r.id"); if (!StringUtils.isNullOrEmpty(username)){ sb.append(" and userName like ?"); params.add("%"+username+"%"); } if (userRole > 0){ sb.append(" and userRole = ?"); params.add(userRole); } rs = BaseDao.execute(connection, sb.toString(), params.toArray(), statement, rs); if (rs.next()){ count = rs.getInt("count"); } BaseDao.close(null,statement,rs); System.out.println("UserDaoImpl--->getUserCount: "+sb.toString()); } //If the above two conditions are met, then there are two and return count; }
-
Write the interface of service layer
//Query the total number of users by user name or user role public int getUserCount(String username,int userRole) throws SQLException;
-
Write the implementation class of the service layer
public int getUserCount(String username, int userRole) throws SQLException { Connection connection = BaseDao.getConnection(); int count = userDao.getUserCount(connection, username, userRole); BaseDao.close(connection,null,null); return count; }
2. Display user list
-
UserDao
//Query user list public List<User> getUserList(Connection connection,String username,int userRole,int currentPageNo,int pageSize) throws SQLException;
-
UserDaoImpl
public List<User> getUserList(Connection connection, String username, int userRole, int currentPageNo, int pageSize) throws SQLException { PreparedStatement statement = null; ResultSet rs = null; //Use ArrayList to encapsulate user information ArrayList<User> users = new ArrayList<User>(); User user = null; if (connection != null){ //Use the list collection to encapsulate parameters ArrayList<Object> params = new ArrayList<Object>(); //Because the query is based on the user role or user name, you need to use StringBuffer to splice strings StringBuffer sql = new StringBuffer("SELECT * from `smbms_user` u,`smbms_role` r WHERE u.userRole = r.id"); if (!StringUtils.isNullOrEmpty(username)){ sql.append(" and userName like ?"); params.add("%"+username+"%"); } if (userRole > 0){ sql.append(" and userRole = ?"); params.add(userRole); } //Starting subscript int pageIndex = (currentPageNo - 1) * pageSize; sql.append(" order by u.creationDate DESC limit ?,?"); params.add(pageIndex); params.add(pageSize); rs = BaseDao.execute(connection, sql.toString(), params.toArray(), statement, rs); while (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.setModifyBy(rs.getInt("modifyBy")); user.setModifyDate(rs.getDate("modifyDate")); 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.setModifyBy(rs.getInt("modifyBy")); user.setModifyDate(rs.getDate("modifyDate")); users.add(user); } BaseDao.close(null,statement,rs); System.out.println("UserDaoImpl--->getUserCount: "+sql.toString()); } return users; }
-
UserService
//Query user list by criteria public List<User> getUserList(String username,int userRole,int currentPageNo,int PageSize) throws SQLException;
-
UserServiceImpl
//Query user list public List<User> getUserList(String username, int userRole, int currentPageNo, int pageSize) throws SQLException { ArrayList<User> users = new ArrayList<User>(); Connection connection = BaseDao.getConnection(); users = (ArrayList<User>) userDao.getUserList(connection, username, userRole, currentPageNo, pageSize); BaseDao.close(connection,null,null); return users; }
3. Get role list
In order to clarify our responsibilities, we need to put the role list into another package to facilitate code maintenance
-
RoleDao
//Get role list public List<Role> getRoleList(Connection connection) throws SQLException;
-
RoleDaoImpl
//Get role list public List<Role> getRoleList(Connection connection) throws SQLException { System.out.println("UserDaoImpl--->getRoleList"); ArrayList<Role> roles = new ArrayList<Role>(); PreparedStatement statement = null; ResultSet resultSet = null; Role role = null; if (connection != null){ String sql = "select * from smbms_role "; Object[] params = {}; System.out.println(params.length); resultSet = BaseDao.execute(connection, sql, params, statement, resultSet); while (resultSet.next()){ role = new Role(); role.setId(resultSet.getInt("id")); role.setRoleCode(resultSet.getString("roleCode")); role.setRoleName(resultSet.getString("roleName")); role.setCreatedBy(resultSet.getInt("createdBy")); role.setModifyBy(resultSet.getInt("modifyBy")); role.setCreationDate(resultSet.getDate("creationDate")); role.setModifyDate(resultSet.getDate("modifyDate")); roles.add(role); } BaseDao.close(null,statement,resultSet); } return roles; }
-
RoleService
//Query role list public List<Role> getRoleList() throws SQLException;
-
RoleServiceImpl
public List<Role> getRoleList() throws SQLException { System.out.println("RoleServiceImpl--->getRoleList"); List<Role> roles = new ArrayList<Role>(); Connection connection = BaseDao.getConnection(); roles = roleDao.getRoleList(connection); BaseDao.close(connection,null,null); return roles; }
4. Integrate resources into servlets
-
Getting front-end parameters is actually to prepare for query
-
To realize paging operation, you need to use page size, total pages, total number of pages, number of pages
-
Get user list
-
Transfer parameters according to the parameters required by the front end
-
Back to front end
public void query(HttpServletRequest req, HttpServletResponse resp) { //Get front-end data String userName = req.getParameter("queryname"); String temp = req.getParameter("queryUserRole"); String pageIndex = req.getParameter("pageIndex"); //If the user does not enter anything, we need to set some initial values to display the page if (userName == null){ userName = ""; } int userRole = 0; if (temp != null && !temp.equals("")){ userRole = Integer.parseInt(temp); } //The first time you access user management, it must be the first page, and the page size is fixed int pageSize = 2; int currentPageNo = 1; if (pageIndex != null){ currentPageNo = Integer.parseInt(pageIndex); } UserService userService = new UserServiceImpl(); List<User> userList = null; //Get the total number of users, where paging operation can be realized int totalCount = 0; try { totalCount = userService.getUserCount(userName, userRole); } catch (SQLException e) { e.printStackTrace(); } //Introduce support for total pages PageSupport pageSupport = new PageSupport(); pageSupport.setPageSize(pageSize); pageSupport.setTotalCount(totalCount); pageSupport.setCurrentPageNo(currentPageNo); //Control the first and last pages so that they do not overflow int totalPageCount = pageSupport.getTotalPageCount(); if (currentPageNo > totalPageCount) {//If the total number of pages is exceeded, the last page is displayed currentPageNo = totalPageCount; }else if (currentPageNo < 1){//When a negative number of pages appears, the first page is displayed currentPageNo = 1; } //Get user list display try { //Get user list display userList = userService.getUserList(userName, userRole, currentPageNo, pageSize); } catch (SQLException e) { e.printStackTrace(); } //Get role list display RoleService roleService = new RoleServiceImpl(); List<Role> roleList = null; try { roleList = roleService.getRoleList(); } catch (SQLException e) { e.printStackTrace(); } //Transfer data to the front end. Since the user query is every request operation, the information can be stored in the request req.setAttribute("userList",userList); req.setAttribute("roleList",roleList); req.setAttribute("queryUserName",userName); req.setAttribute("queryUserRole",userRole); req.setAttribute("totalCount",totalCount); req.setAttribute("currentPageNo",currentPageNo); req.setAttribute("totalPageCount",totalPageCount); //Back to front end try { req.getRequestDispatcher("userlist.jsp").forward(req,resp); } catch (ServletException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
Add user operation
1. User role list display
//Add get role list in user interface public void getRoleList(HttpServletRequest req, HttpServletResponse resp) { //Get role list RoleService roleService = new RoleServiceImpl(); List<Role> roleList = null; try { roleList = roleService.getRoleList(); } catch (SQLException e) { e.printStackTrace(); } //Convert roleList to Json format output try { PrintWriter out = resp.getWriter(); out.write(JSONArray.toJSONString(roleList)); out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } }
Idea:
2. User code determination
-
UserDao
//Query user public List<User> query(Connection connection) throws SQLException;
-
UserDaoImpl
//Query all users public List<User> query(Connection connection) throws SQLException { PreparedStatement statement = null; ResultSet resultSet = null; Object[] params = {}; User user = null; List<User> users = new ArrayList<User>(); if (connection != null){ String sql = "select * from `smbms_user`"; resultSet = BaseDao.execute(connection, sql, params, statement, resultSet); while (resultSet.next()){ user = new User(); user.setUserCode(resultSet.getString("userCode")); users.add(user); } BaseDao.close(null,statement,resultSet); System.out.println("UserDaoImpl----->query: " +sql); } return users; }
-
UserService
//Query user code public List<User> query() throws SQLException;
-
UserService
//Query user public List<User> query() throws SQLException { System.out.println("UserServiceImpl---->query..."); Connection connection = BaseDao.getConnection(); List<User> userList = userDao.query(connection); BaseDao.close(connection,null,null); return userList; }
-
Servlet
//Judge whether the user code exists public void isUserExist(HttpServletRequest req, HttpServletResponse resp) { //Get front end parameters String InsertUserCode = req.getParameter("userCode"); //Call business layer UserService userService = new UserServiceImpl(); List<User> userList = null; try { userList = userService.query(); } catch (SQLException e) { e.printStackTrace(); } //Encapsulate data with Map HashMap<String, String> map = new HashMap<String, String>(); if (userList != null){ for (User user:userList){ if (InsertUserCode != null && !StringUtils.isNullOrEmpty(InsertUserCode)) { if (InsertUserCode.equals( user.getUserCode())){//User already exists map.put("userCode","exist"); } } } } //Convert userList to Json format output resp.setContentType("application/json"); PrintWriter out = null; try { out = resp.getWriter(); out.write(JSONArray.toJSONString(map)); out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } }
3. Add user
-
UserDao
//Add user public boolean add(Connection connection,User user);
-
UserDaoImpl
//Add user public boolean add(Connection connection,User user) { PreparedStatement statement = null; boolean flag = false; if (connection != null){ //Add transaction try { //Open transaction connection.setAutoCommit(false); String sql = "insert into `smbms_user`(\n" + "userCode,userName,userpassword,gender,birthday,phone,address,userRole,createdBy,creationDate" + ")\n" + "VALUES(?,?,?,?,?,?,?,?,?,?)"; Object[] params = {user.getUserCode(),user.getUserName(),user.getUserPassword(),user.getGender(),user.getBirthday(),user.getPhone(),user.getAddress(),user.getUserRole(),user.getCreatedBy(),user.getCreationDate()}; int resultNum = BaseDao.execeute(connection, sql, params, statement); if (resultNum > 0){ flag = true; } System.out.println("UserDaoImpl--->add: "+sql.toString()); connection.commit(); System.out.println("UserDaoImpl---->add: " + sql); } catch (SQLException e) { try { connection.rollback(); } catch (SQLException ex) { ex.printStackTrace(); } }finally { BaseDao.close(null,statement,null); } } return flag; }
-
Userservice
//Add user public boolean add(User user);
-
UserserviceImpl
public boolean add(User user) { System.out.println("UserService---->add...."); Connection connection = BaseDao.getConnection(); boolean flag = false; if (user != null){ flag = userDao.add(connection,user); } BaseDao.close(connection,null,null); return flag; }
-
servlet
//Add user public void add(HttpServletRequest req, HttpServletResponse resp) { System.out.println("UserServlet---->add..."); String userCode = req.getParameter("userCode"); String userName = req.getParameter("userName"); String userPassword = req.getParameter("userPassword"); String genderTemp = req.getParameter("gender");//Temporary variable String birthdayTemp = req.getParameter("birthday"); String phone = req.getParameter("phone"); String address = req.getParameter("address"); String userRoleTemp = req.getParameter("userRole");//Temporary variable System.out.println("--------1---------"); int gender = 1; if (genderTemp != null && !StringUtils.isNullOrEmpty(genderTemp)) { gender = Integer.parseInt(genderTemp); } System.out.println("---------2--------"); Date birthday = null; try { //Format date string birthday = new SimpleDateFormat("yyyy-MM-dd").parse(birthdayTemp); } catch (ParseException e) { e.printStackTrace(); } System.out.println("---------3--------"); int userRole = 0; if (userRoleTemp != null) { userRole = Integer.parseInt(userRoleTemp); } System.out.println("---------4--------"); //Encapsulate into User class User user = new User(); user.setUserCode(userCode); user.setUserName(userName); user.setUserPassword(userPassword); user.setGender(gender); user.setBirthday(birthday); user.setPhone(phone); user.setUserRole(userRole); Object o = req.getSession().getAttribute(Constant.USER_SESSION); if (o != null){ user.setCreatedBy(((User) o).getId()); } user.setCreationDate(new Date()); //Call business layer UserService userService = new UserServiceImpl(); //Add user boolean flag = userService.add(user); System.out.println("---------5--------"); System.out.println(flag); //Judge whether it is added successfully if (flag){ //How to operate after adding successfully //Return to user management interface this.query(req, resp); }else { //What to do after adding failed //No need to operate, or on this page } }
delete user
How to obtain the specified user id? The front end directly obtains the id
-
UserDao
//Delete user by id public boolean deleteUser(Connection connection,int id);
-
UserDaoImpl
//Delete user by id public boolean deleteUser(Connection connection, int id) { PreparedStatement statement = null; boolean flag = false; if (connection != null){ //Add transaction try { //Open transaction connection.setAutoCommit(false); String sql = "delete from `smbms_user` where id = ?"; Object[] params = {id}; int resultNum = BaseDao.execeute(connection, sql, params, statement); if (resultNum > 0){ flag = true; } connection.commit(); System.out.println("UserDaoImpl---->delete: " + sql); } catch (SQLException e) { try { connection.rollback(); } catch (SQLException ex) { ex.printStackTrace(); } }finally { BaseDao.close(null,statement,null); } } return flag; }
-
UserService
//Delete user by id public boolean deleteUser(int id);
-
UserServiceImpl
public boolean deleteUser(int id) { System.out.println("UserService---->delete...."); Connection connection = BaseDao.getConnection(); boolean flag = false; userDao.deleteUser(connection,id); BaseDao.close(connection,null,null); return flag; }
-
Servlet
//delete user public void deleteUser(HttpServletRequest req, HttpServletResponse resp) { //Get parameters from the front end String userid = req.getParameter("uid"); //Call business layer UserService userService = new UserServiceImpl(); HashMap<String, String> map = new HashMap<String, String>(); boolean flag = false; if (userid==null && StringUtils.isNullOrEmpty(userid)){ map.put("delResult","notexist"); }else { flag = userService.deleteUser(Integer.valueOf(userid)); if (flag){ map.put("delResult","true"); }else { map.put("delResult","false"); } } try { resp.setContentType("applicaton/json"); PrintWriter writer = resp.getWriter(); writer.write(JSONArray.toJSONString(map)); writer.flush(); writer.close(); } catch (IOException e) { e.printStackTrace(); } }
Modify user
-
Analysis requirements
-
View the requested path
Idea:
userDao
//Modify user information according to id public boolean modifyById(Connection connection,User user);
userDaoImpl
//Modify user information according to id public boolean modifyById(Connection connection, User user) { PreparedStatement statement = null; boolean flag = false; if (connection != null){ //Add transaction try { //Open transaction connection.setAutoCommit(false); String sql = "update smbms_user set userName=?," + "gender=?,birthday=?,phone=?,address=?,userRole=?,modifyBy=?,modifyDate=? where id = ? "; Object[] params = {user.getUserName(), user.getGender(), user.getBirthday(), user.getPhone(), user.getAddress(), user.getUserRole(), user.getModifyBy(), user.getModifyDate(), user.getId()}; int resultNum = BaseDao.execeute(connection, sql, params, statement); if (resultNum > 0){ flag = true; } connection.commit(); System.out.println("UserDaoImpl---->modifyById: " + sql); } catch (SQLException e) { try { connection.rollback(); } catch (SQLException ex) { ex.printStackTrace(); } }finally { BaseDao.close(null,statement,null); } } return flag; }
UserService
//Modify user information according to id public boolean modifyById(User user);
UserService
public boolean modifyById(User user) { System.out.println("UserService---->delete...."); Connection connection = BaseDao.getConnection(); boolean flag = false; flag = userDao.modifyById(connection,user); BaseDao.close(connection,null,null); return flag; }
servlet
//Query the user information according to the id and return to the usermodify.jsp page public void modifyById(HttpServletRequest request, HttpServletResponse resp) { //Get front end parameters String id = request.getParameter("uid"); Integer uid = 0; //Determine whether the id value is obtained if (id != null){ uid = Integer.valueOf(id); }else { try { resp.sendRedirect(request.getContextPath() + "/error.jsp"); } catch (IOException e) { e.printStackTrace(); } } //Call business layer UserService userService = new UserServiceImpl(); User user = null; try { user = userService.getUserById(uid); } catch (SQLException e) { e.printStackTrace(); } if (user != null){//User information exists request.setAttribute("user",user); try { request.getRequestDispatcher("usermodify.jsp").forward(request,resp); } catch (ServletException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
//Modify the user according to the id and return to the user list page public void modifyExe(HttpServletRequest request, HttpServletResponse resp) { System.out.println("UserServlet----->modifyExe..."); //Get parameters from the front end String id = request.getParameter("uid"); String userName = request.getParameter("userName"); String gender = request.getParameter("gender"); String birthday = request.getParameter("birthday"); String phone = request.getParameter("phone"); String address = request.getParameter("address"); String userRole = request.getParameter("userRole"); System.out.println("UserServlet----->modifyById: "+ id); User user = new User(); user.setId(Integer.valueOf(id)); user.setUserName(userName); user.setGender(Integer.valueOf(gender)); try { user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday)); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println("An exception occurred..."); } user.setPhone(phone); user.setAddress(address); user.setUserRole(Integer.valueOf(userRole)); user.setModifyBy(((User) request.getSession().getAttribute(Constant.USER_SESSION)).getId()); user.setModifyDate(new Date()); //Call business layer UserService userService = new UserServiceImpl(); boolean flag = false; try { flag = userService.modifyById(user); } catch (Exception e) { e.printStackTrace(); } //There is no need to carry parameters in the request here. The user needs to input request.setAttribute("user",user); if (flag){//Successfully modified, redirect to user list page try { resp.sendRedirect(request.getContextPath()+"/jsp/user.do?method=query"); } catch (IOException e) { e.printStackTrace(); } }else {//Modification failed. You can not jump or re forward to the current page try { request.getRequestDispatcher("usermodify.jsp").forward(request,resp); } catch (ServletException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
Query specified user information
//Query the user information according to the id and return to the userview.jsp page public void getUserById(HttpServletRequest req, HttpServletResponse resp) { System.out.println("-----------1-----------"); String uid = req.getParameter("uid"); System.out.println(uid); Integer id = 0; try{ id = Integer.valueOf(uid); }catch (Exception e){ //handle exception id = 0; } System.out.println("-----------2-----------"); //Call business layer UserService userService = new UserServiceImpl(); User user = null; try { user = userService.getUserById(id); } catch (SQLException e) { e.printStackTrace(); } System.out.println(user); req.setAttribute("user",user); try { req.getRequestDispatcher("userview.jsp").forward(req,resp); } catch (ServletException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
Order management implementation
Supplier management implementation
summary
Simple user management authority optimization
-
Get current user information from session
-
Judge whether the user is a system administrator
-
If you are not a system administrator, you will return to the page with insufficient permissions
-
If so, pass
User permissions require the use of filters
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) servletRequest; HttpServletResponse response = (HttpServletResponse) servletResponse; HttpSession session = request.getSession(); User user = (User) session.getAttribute(Constant.USER_SESSION); if (!user.getUserCode().equals("admin")){ response.sendRedirect(request.getContextPath()+"/jsp/powererror.jsp"); }else { filterChain.doFilter(servletRequest, servletResponse); } }
Register filter
<filter> <filter-name>AuthorityFilter</filter-name> <filter-class>com.kuang.filter.AuthorityFilter</filter-class> </filter> <filter-mapping> <filter-name>AuthorityFilter</filter-name> <!--Specify specific interception path--> <url-pattern>/jsp/user.do</url-pattern> </filter-mapping> <filter-mapping> <filter-name>AuthorityFilter</filter-name> <url-pattern>/jsp/bill.do</url-pattern> </filter-mapping> <filter-mapping> <filter-name>AuthorityFilter</filter-name> <url-pattern>/jsp/provider.do</url-pattern> </filter-mapping>