<> Project brief

smbms Supermarket order management system , It is mainly used for user management , Order management , Supplier management and other functions , It's learning JavaWeb A small project of practice

This blog only talks about some functions ( User login interface , And password modification interface ), And the realization of user management .

The implementation of the main write back end .

<> Using technology

Maven: Managing dependent packaged projects
Mysql: Store business data
HTML: Making front end login page
Servlet: Background service resources complete related business
Tomcat:web Server for project deployment
Filter: Unified session management for all logins


<> Basic framework construction

establish dao layer ( Data persistence layer ),pojo layer ( ordinary Java object ),service( Business layer ),servlet( Server layer ),tools( Tool layer ),filter( Filter layer )

dao Layer is mainly used for database operation ,Service( Business layer ) call dao layer , And transmit the data to servlet layer ,

servlet Layer is responsible for the front and back end interaction , Get data from the front end , To the back end , And the data obtained by the back end is returned to the front end

service Layer capture exception , Transaction processing

transaction processing : Call different dao Multiple methods for , You must use the same connection(connection Pass as parameter ) After the transaction is completed , Need to be in service Layer connection Closure of , stay dao Layer off (PreparedStatement and ResultSet object )

pojo Layer is mainly some objects corresponding to database

The filter layer first writes the coding filter layer , To prevent the front and back end coding inconsistent garbled situation

<> Project page

Login interface

System home page

Password modification page

User Management Homepage

<> Project construction

1, Build a maven web project

2, to configure tomcat

3, Can the test project run

4, Problems encountered in importing projects jar package

jsp,servlet,mysql drive ,jstl,stand…

5, Create package structure

6, Write entity class

ORM mapping : surface - Class mapping

7, Write basic public classes

​ 1, Database profile
username=root password=123456
3, Writing character encoding filters

It is mainly for the front and back end connection without garbled code
public class CharacterEncoding implements Filter { @Override public void init(
FilterConfig filterConfig) throws ServletException { } @Override public void
doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
FilterChain filterChain) throws IOException, ServletException { servletRequest.
setCharacterEncoding("utf-8"); servletResponse.setCharacterEncoding("utf-8");
filterChain.doFilter(servletRequest,servletResponse); } @Override public void
destroy() { } }
8, Import static resources

<> Login function implementation

1, Write front end page

* First in web.xml Set in welcome-file-list
* Front end page login.jsp
* loginservlet
* request.getparam() Get front end data
* Call business layer
* Set if match is successful session, Page redirection , otherwise , Prompt error ( Setup page error attribute )
2, Set home page
<!-- Set up welcome page --> <welcome-file-list> <welcome-file>login.jsp</welcome-file> </
3, to write dao Layer login user login interface

Create objects by database user class
public interface UserDao { // Get the user to log in public User getLoginUser(Connection
connection,String userCode) throws Exception; }
BaseDao class

Methods of database operation ( connect , query , to update )
package dao; import java.io.IOException; import java.io.InputStream; import
java.sql.*; import java.util.Properties; 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 a link to the database public static Connection getConnection(){ Connection connection
= null; try { Class.forName("com.mysql.jdbc.Driver"); connection = DriverManager
.getConnection(url, username, password); } catch (Exception e) { e.
printStackTrace(); } return connection; } // Write query public method public static ResultSet
execute(Connection connection,PreparedStatement preparedStatement,ResultSet
resultSet,String sql,Object[] params) throws SQLException {
// Precompiled sql, Just execute it directly in the back preparedStatement = connection.prepareStatement(sql); for
(int i = 0; i < params.length; i++) { //setObject, Place holder from 1 start , But our array is from 0 start !
preparedStatement.setObject(i+1,params[i]); } resultSet = preparedStatement.
executeQuery(); return resultSet; } // Writing public methods of addition, deletion and modification 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, Place holder from 1 start , But our array is from 0 start ! preparedStatement.setObject(i+1,params[i]); }
int updateRows = preparedStatement.executeUpdate(); return updateRows; }
4, to write dao Interface implementation class
public class UserDaoImpl implements UserDao{ @Override public User getLoginUser
(Connection connection, String userCode) throws Exception { // TODO
Auto-generated method stub PreparedStatement pstm = null; ResultSet rs = null;
User user= null; if(null != connection){ String sql = "select * from smbms_user
where userCode=?"; Object[] params = {userCode}; 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.getTimestamp("creationDate")); user.setModifyBy(rs.
getInt("modifyBy")); user.setModifyDate(rs.getTimestamp("modifyDate")); }
BaseDao.closeResource(null, pstm, rs); } return user; } }
5, Write business layer interface
public interface UserService { // User login public User login(String userCode,String
userPassword); }
6, Write the implementation class of business layer interface
public class UserServiceImpl implements UserService{ // The business layer will call dao layer , So we're going to introduce dao layer
private UserDao userDao; public UserServiceImpl(){ userDao = new UserDaoImpl();
} public User login(String userCode,String password){ Connection connection=null
; User user=null; // Call the corresponding specific database operation through the business layer try { connection= BaseDao.getConnection()
; user=userDao.getLoginUser(connection,userCode); } catch (Exception e) { e.
printStackTrace(); }finally { BaseDao.closeResource(connection,null,null); }
return user; }
7, to write servlet class
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"); // Compare with the password in the database , Call business layer ; UserService userService
= new UserServiceImpl(); User user = userService.login(userCode, userPassword);
// The person who logged in has been found out here System.out.println(userCode); System.out.println(userPassword);
if (user!=null){ // Check out this person , You can log in // Put user information in Session in ; req.getSession().setAttribute(
Constants.USER_SESSION,user); // Jump to home page redirection resp.sendRedirect("jsp/frame.jsp"); }
else {// There is no such person , Unable to sign in // Forward back to login page , By the way, prompt it , Wrong user name or password ; req.setAttribute("error",
" Incorrect user name or password "); req.getRequestDispatcher("login.jsp").forward(req,resp); } }
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp
) throws ServletException, IOException { doGet(req, resp); } }
8, register servlet

Finish one servlet Remember to register
<servlet> <servlet-name>LoginServlet</servlet-name> <servlet-class>
servlet.user.LoginServlet</servlet-class> </servlet> <servlet-mapping> <
servlet-name>LoginServlet</servlet-name> <url-pattern>/login.do</url-pattern> </
9, Test access , Ensure that the above functions are realized

<> Login function optimization

remove session
public class LogoutServlet extends HttpServlet { @Override protected void doGet
(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
IOException{ // Remove user's session req.getSession().removeAttribute(Constants.
USER_SESSION); resp.sendRedirect(req.getContextPath()+"/login.jsp");// Return to login page }
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp
) throws ServletException, IOException { super.doPost(req, resp); } }
register xml
<servlet> <servlet-name>LogoutServlet</servlet-name> <servlet-class>
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

Under normal circumstances, you cannot log in after you log out of the system , But at present, you can still log in by entering the address directly . So we need to optimize

Write a filter and register
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; // filter , from Session Get users from ,
User user= (User) request.getSession().getAttribute(Constants.USER_SESSION); if
(user==null){ // Has been removed or logged off , Or not logged in response.sendRedirect("/smbms/error.jsp"); }
else { chain.doFilter(req,resp); } } public void destroy() { } } <filter> <
filter-name>Sysfilter</filter-name> <filter-class>filter.SysFilter</filter-class
> </filter> <filter-mapping> <filter-name>Sysfilter</filter-name> <url-pattern>
/jsp/*</url-pattern> </filter-mapping>
<> Password modification

Import front end material

Write from the bottom

UserDao Interface implementation class
// Modify current user password // Adding, deleting and modifying will affect the changes of the database , So it's a return int type , Indicates that several lines have been affected @Override public int updatePwd
(Connection connection, int id, int password) throws Exception { int updateRow=0
; PreparedStatement pstm=null; if (connection!=null){ String sql="UPDATE
`smbms_user` SET `userPassword`=? WHERE `id`=? "; Object[] params={password,id};
BaseDao.execute(connection,sql,params,pstm); } BaseDao.closeResource(null,pstm,
null); return updateRow; }
UserService layer

Transaction processing , call dao layer , lookup servlet The related users of the data from the layer , And in servlet Layer data
// Change Password public boolean updatePwd(int id,int pwd);
UserService Layer implementation class
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 (Exception e) { e.printStackTrace(
); }finally { BaseDao.closeResource(connection,null,null); } return flag; }
Write a password modification program servlet class

Get database user data , And set session attribute userlist
public class UserServlet extends HttpServlet { @Override protected void doGet(
HttpServletRequest req, HttpServletResponse resp) throws ServletException,
IOException{ String method = req.getParameter("method"); if (method.equals(
"savepwd")&&method!=null){ this.modifyPwd(req,resp); }else if (method.equals(
"pwdmodify")&&method!=null){ this.pwdmodify(req,resp); } } @Override protected
void doPost(HttpServletRequest req, HttpServletResponse resp) throws
ServletException, IOException { doGet(req, resp); } // Change Password public void modifyPwd
(HttpServletRequest req, HttpServletResponse resp){ // Get the password and password to modify id Object
attribute= req.getSession().getAttribute(Constants.USER_SESSION); String
newpassword= req.getParameter("newpassword"); boolean flag = false;
// Judge this session And whether the new password exists if(attribute!=null && !StringUtils.isNullOrEmpty(
newpassword)){ UserServiceImpl userService = new UserServiceImpl(); flag =
userService.modifyPwd(((User) attribute).getId(), newpassword); if(flag){ req.
setAttribute("message"," Password changed successfully "); // Password modification successfully removed the current password session req.getSession().
removeAttribute(Constants.USER_SESSION); }else { req.setAttribute("message",
" Password modification failed "); } }else{ // There is a problem with the new password 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 userservlet
<servlet> <servlet-name>userServlet</servlet-name> <servlet-class>
servlet.user.UserServlet</servlet-class> </servlet> <servlet-mapping> <
servlet-name>userServlet</servlet-name> <url-pattern>/jsp/user.do</url-pattern>
Password modification success interface

Optimize password modification Ajax

AJAX = asynchronous JavaScript and XML.

AJAX Is a technology for creating fast dynamic web pages .

Through a small amount of data exchange with the server in the background ,AJAX Web pages can be updated asynchronously . This means that you can do this without reloading the entire page , Update a part of the web page .

Traditional web pages ( Not used AJAX) If you need to update the content , The entire page face must be overloaded .

There are many uses AJAX Application case of : Sina Weibo ,Google Map , Happy net and so on .

use jQuery Import required jQuery, use Vue Import Vue, Use both , The realization of self original ecology

Trilogy :

1, Write corresponding processing controller, Returns a message or string or json Formatted data

2, to write ajax request

* url:controller request
* data: Key value pair
* success: Callback function
3, to ajax Binding events , click .click, Lose focus onblur, The keyboard pops up keyup

<> Implementation of user management

thinking :

1, Import pagination tool class

2, User list page import

<> Get the number of users

// Total number of query users public int getUserCount(Connection connection,String username ,int
userRole)throws SQLException;
public int getUserCount(Connection connection, String username, int userRole)
throws SQLException { // Query the total number of users according to the user name or role 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>();// Store our parameters 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:1 }
// How to do it List Convert to array Object[] params = list.toArray(); System.out.println(
"UserDaoImpl->getUserCount:"+sql.toString()); // Output the last complete SQL sentence rs = BaseDao.
execute(connection, pstm, rs, sql.toString(), params); if (rs.next()){ count =
rs.getInt("count"); // Get the final quantity from the result set } BaseDao.closeResource(null,pstm,rs); }
return count; }
// Number of query records public int getUserCount(String username,int userRole);
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; }
<> Get user list

// Query by condition -userList public List<User> getUserList(Connection connection, String
userName, int userRole, int currentPageNo, int pageSize)throws Exception;
public List<User> getUserList(Connection connection, String userName, int
userRole, int currentPageNo, int pageSize) throws Exception { 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(); System.out.println("sql ----> " + sql.toString
()); 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); } return userList; }
// Query user list according to conditions public List<User> getUserList(String queryUserName, int
queryUserRole, int currentPageNo, int pageSize);
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) { e.printStackTrace(); }finally{ BaseDao.closeResource(
connection, null, null); } return userList; }
<> Get role actions

public interface RoleDao { // Get role list public List<Role> getRoleList(Connection
connection) throws SQLException; }
public class RoleDaoImpl implements RoleDao { // Get role list public List<Role>
getRoleList(Connection connection) throws SQLException { PreparedStatement pstm
= null; ResultSet resultSet = null; ArrayList<Role> roleList = new ArrayList<
Role>(); if (connection!=null){ String sql = "select * from smbms_role"; Object[
] params = {}; resultSet = BaseDao.execute(connection, pstm, resultSet, sql,
params); while (resultSet.next()){ Role _role = new Role(); _role.setId(
resultSet.getInt("id")); _role.setRoleCode(resultSet.getString("roleCode"));
_role.setRoleName(resultSet.getString("roleName")); roleList.add(_role); }
BaseDao.closeResource(null,pstm,resultSet); } return roleList; } }
// Get role list public List<Role> getRoleList();
public class RoleServiceImpl implements RoleService { // introduce Dao 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; } }
userservlet Add in query method

The page is not paginated , It's all on one page , Add paging query
//query method public void query(HttpServletRequest req, HttpServletResponse resp){
// Query user list // Get data from the front end ; String queryUserName = req.getParameter("queryname");
String temp= req.getParameter("queryUserRole"); String pageIndex = req.
getParameter("pageIndex"); int queryUserRole = 0; // Get user list UserServiceImpl
userService= new UserServiceImpl(); List<User> userList = null;
// For the first time, this request , It must be the first page , Fixed page size ; int pageSize = 5; // You can add this to the configuration file , Convenient for later modification ; int
currentPageNo= 1; if (queryUserName ==null){ queryUserName = ""; } if (temp!=
null&& !temp.equals("")){ queryUserRole = Integer.parseInt(temp);
// Assign values to queries !0,1,2,3 } if (pageIndex!=null){ currentPageNo = Integer.parseInt(
pageIndex); } // Gets the total number of users ( paging : previous page , Next page ) int totalCount = userService.
getUserCount(queryUserName, queryUserRole); // Total page support PageSupport pageSupport =
new PageSupport(); pageSupport.setCurrentPageNo(currentPageNo); pageSupport.
setPageSize(pageSize); pageSupport.setTotalCount(totalCount); int totalPageCount
= ((int)(totalCount/pageSize))+1; // Control front and back pages // If the page is smaller than 1 It's over , Just show the first page if (
currentPageNo<1){ currentPageNo = 1; }else if (currentPageNo>totalPageCount){
// The current page is larger than the last page ; currentPageNo = totalPageCount; } // Get user list display 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); // Back to front end try { req.
getRequestDispatcher("userlist.jsp").forward(req,resp); } catch (
ServletException e) { e.printStackTrace(); } catch (IOException e) { e.
printStackTrace(); } }
Almost login and user management module is these

©2019-2020 Toolsou All rights reserved,
Huawei 2021 session Hardware Engineer Logical post (FPGA) Super detailed surface !!!Vue-element-admin upgrade ui edition virtual machine VMware Download and install the most detailed tutorial !C++ Move constructor and copy constructor sound of dripping water java Backstage interview pygame Realize full screen mode and adjustable window size mysql Database setting character set configuration modification my.ini file (windows)30 What's the experience of being a junior programmer at the age of 20 C++ Multithreading programming ( Summary of common functions and parameters )python_ cherry tree