實(shí)踐:SMBMS項(xiàng)目SMBMS是超市訂單管理系統(tǒng)的英文縮寫。 SMBMS項(xiàng)目SQL代碼:https://download.csdn.net/download/qq_39763246/15352854 百度網(wǎng)盤:https://pan.baidu.com/s/16fNpMkGeXZud-U58Z5y67g 提取碼: q3eq 項(xiàng)目架構(gòu): 數(shù)據(jù)庫架構(gòu): 項(xiàng)目搭建準(zhǔn)備工作搭建項(xiàng)目時(shí)要先考慮是否使用Maven,如果用Maven則需要寫依賴,如果不用Maven則要手動導(dǎo)入Jar包。這里選擇使用Maven。 1、搭建一個(gè)Maven Web項(xiàng)目 2、配置Tomcat 3、啟動Tomcat,測試項(xiàng)目能否跑起來 4、導(dǎo)入項(xiàng)目中會遇到的jar包 <dependencies> <!-- Servlet依賴 --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> <scope>provided</scope> </dependency> <!-- JSP依賴 --> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api</artifactId> <version>2.3.3</version> <scope>provided</scope> </dependency> <!-- JSTL表達(dá)式依賴 --> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- standard標(biāo)簽庫 --> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> </dependency> <!-- 連接數(shù)據(jù)庫 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.47</version> </dependency> <!-- 代碼測試 --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> <!-- 導(dǎo)入阿里巴巴的fastjson, 處理json轉(zhuǎn)化 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.62</version> </dependency> </dependencies> 5、創(chuàng)建項(xiàng)目包結(jié)構(gòu) 6、編寫實(shí)體類 ORM映射:數(shù)據(jù)庫 表—Java 類映射 Bill.java package com.zcy.pojo; import java.math.BigDecimal; import java.util.Date; public class Bill {private Integer id; //id private String billCode; //賬單編碼 private String productName; //商品名稱 private String productDesc; //商品描述 private String productUnit; //商品單位 private BigDecimal productCount; //商品數(shù)量 private BigDecimal totalPrice; //總金額 private Integer isPayment; //是否支付 private Integer providerId; //供應(yīng)商ID private Integer createdBy; //創(chuàng)建者 private Date creationDate; //創(chuàng)建時(shí)間 private Integer modifyBy; //更新者 private Date modifyDate;//更新時(shí)間 private String providerName;//供應(yīng)商名稱 public String getProviderName() {return providerName; } public void setProviderName(String providerName) {this.providerName = providerName; } public Integer getId() {return id; } public void setId(Integer id) {this.id = id; } public String getBillCode() {return billCode; } public void setBillCode(String billCode) {this.billCode = billCode; } public String getProductName() {return productName; } public void setProductName(String productName) {this.productName = productName; } public String getProductDesc() {return productDesc; } public void setProductDesc(String productDesc) {this.productDesc = productDesc; } public String getProductUnit() {return productUnit; } public void setProductUnit(String productUnit) {this.productUnit = productUnit; } public BigDecimal getProductCount() {return productCount; } public void setProductCount(BigDecimal productCount) {this.productCount = productCount; } public BigDecimal getTotalPrice() {return totalPrice; } public void setTotalPrice(BigDecimal totalPrice) {this.totalPrice = totalPrice; } public Integer getIsPayment() {return isPayment; } public void setIsPayment(Integer isPayment) {this.isPayment = isPayment; } public Integer getProviderId() {return providerId; } public void setProviderId(Integer providerId) {this.providerId = providerId; } public Integer getCreatedBy() {return createdBy; } public void setCreatedBy(Integer createdBy) {this.createdBy = createdBy; } public Date getCreationDate() {return creationDate; } public void setCreationDate(Date creationDate) {this.creationDate = creationDate; } public Integer getModifyBy() {return modifyBy; } public void setModifyBy(Integer modifyBy) {this.modifyBy = modifyBy; } public Date getModifyDate() {return modifyDate; } public void setModifyDate(Date modifyDate) {this.modifyDate = modifyDate; } } Provider.java package com.zcy.pojo; import java.util.Date; public class Provider {private Integer id; //id private String proCode; //供應(yīng)商編碼 private String proName; //供應(yīng)商名稱 private String proDesc; //供應(yīng)商描述 private String proContact; //供應(yīng)商聯(lián)系人 private String proPhone; //供應(yīng)商電話 private String proAddress; //供應(yīng)商地址 private String proFax; //供應(yīng)商傳真 private Integer createdBy; //創(chuàng)建者 private Date creationDate; //創(chuàng)建時(shí)間 private Integer modifyBy; //更新者 private Date modifyDate;//更新時(shí)間 public Integer getId() {return id; } public void setId(Integer id) {this.id = id; } public String getProCode() {return proCode; } public void setProCode(String proCode) {this.proCode = proCode; } public String getProName() {return proName; } public void setProName(String proName) {this.proName = proName; } public String getProDesc() {return proDesc; } public void setProDesc(String proDesc) {this.proDesc = proDesc; } public String getProContact() {return proContact; } public void setProContact(String proContact) {this.proContact = proContact; } public String getProPhone() {return proPhone; } public void setProPhone(String proPhone) {this.proPhone = proPhone; } public String getProAddress() {return proAddress; } public void setProAddress(String proAddress) {this.proAddress = proAddress; } public String getProFax() {return proFax; } public void setProFax(String proFax) {this.proFax = proFax; } public Integer getCreatedBy() {return createdBy; } public void setCreatedBy(Integer createdBy) {this.createdBy = createdBy; } public Date getCreationDate() {return creationDate; } public void setCreationDate(Date creationDate) {this.creationDate = creationDate; } public Integer getModifyBy() {return modifyBy; } public void setModifyBy(Integer modifyBy) {this.modifyBy = modifyBy; } public Date getModifyDate() {return modifyDate; } public void setModifyDate(Date modifyDate) {this.modifyDate = modifyDate; } } Role.java package com.zcy.pojo; import java.util.Date; public class Role {private Integer id; //id private String roleCode; //角色編碼 private String roleName; //角色名稱 private Integer createdBy; //創(chuàng)建者 private Date creationDate; //創(chuàng)建時(shí)間 private Integer modifyBy; //更新者 private Date modifyDate;//更新時(shí)間 public Integer getId() {return id; } public void setId(Integer id) {this.id = id; } public String getRoleCode() {return roleCode; } public void setRoleCode(String roleCode) {this.roleCode = roleCode; } public String getRoleName() {return roleName; } public void setRoleName(String roleName) {this.roleName = roleName; } public Integer getCreatedBy() {return createdBy; } public void setCreatedBy(Integer createdBy) {this.createdBy = createdBy; } public Date getCreationDate() {return creationDate; } public void setCreationDate(Date creationDate) {this.creationDate = creationDate; } public Integer getModifyBy() {return modifyBy; } public void setModifyBy(Integer modifyBy) {this.modifyBy = modifyBy; } public Date getModifyDate() {return modifyDate; } public void setModifyDate(Date modifyDate) {this.modifyDate = modifyDate; } } User.java package com.zcy.pojo; import java.util.Date; public class User { private Integer id; //id private String userCode; //用戶編碼 private String userName; //用戶名稱 private String userPassword; //用戶密碼 private Integer gender; //性別 private Date birthday; //出生日期 private String phone; //電話 private String address; //地址 private Integer userRole; //用戶角色 private Integer createdBy; //創(chuàng)建者 private Date creationDate; //創(chuàng)建時(shí)間 private Integer modifyBy; //更新者 private Date modifyDate; //更新時(shí)間 private Integer age;//年齡 private String userRoleName; //用戶角色名稱 public String getUserRoleName() { return userRoleName; } public void setUserRoleName(String userRoleName) { this.userRoleName = userRoleName; } public Integer getAge() { /*long time = System.currentTimeMillis()-birthday.getTime(); Integer age = Long.valueOf(time/365/24/60/60/1000).IntegerValue();*/ Date date = new Date(); Integer age = date.getYear()-birthday.getYear(); return age; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUserCode() { return userCode; } public void setUserCode(String userCode) { this.userCode = userCode; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getUserPassword() { return userPassword; } public void setUserPassword(String userPassword) { this.userPassword = userPassword; } public Integer getGender() { return gender; } public void setGender(Integer gender) { this.gender = gender; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public Integer getUserRole() { return userRole; } public void setUserRole(Integer userRole) { this.userRole = userRole; } public Integer getCreatedBy() { return createdBy; } public void setCreatedBy(Integer createdBy) { this.createdBy = createdBy; } public Date getCreationDate() { return creationDate; } public void setCreationDate(Date creationDate) { this.creationDate = creationDate; } public Integer getModifyBy() { return modifyBy; } public void setModifyBy(Integer modifyBy) { this.modifyBy = modifyBy; } public Date getModifyDate() { return modifyDate; } public void setModifyDate(Date modifyDate) { this.modifyDate = modifyDate; } } 7、編寫基礎(chǔ)公共類
8、導(dǎo)入靜態(tài)資源,放在webapp目錄下。 下載鏈接: CSDN 百度網(wǎng)盤:https://pan.baidu.com/s/16fNpMkGeXZud-U58Z5y67g 提取碼: q3eq 登錄功能1、編寫前端頁面(login.jsp) login.jsp <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <html> <head lang="en"> <meta charset="UTF-8"> <title>系統(tǒng)登錄 - 超市訂單管理系統(tǒng)</title> <link type="text/css" rel="stylesheet" href="${pageContext.request.contextPath}/css/style.css" /> </head> <body class="login_bg"> <section class="loginBox"> <header class="loginHeader"> <h1>超市訂單管理系統(tǒng)</h1> </header> <section class="loginCont"> <form class="loginForm" action="${pageContext.request.contextPath}/login.do" name="actionForm" id="actionForm" method="post" > <div class="info">${error }</div> <div class="inputbox"> <label>用戶名:</label> <input type="text" class="input-text" id="userCode" name="userCode" placeholder="請輸入用戶名" required/> </div> <div class="inputbox"> <label>密碼:</label> <input type="password" id="userPassword" name="userPassword" placeholder="請輸入密碼" required/> </div> <div class="subBtn"> <input type="submit" value="登錄"/> <input type="reset" value="重置"/> </div> </form> </section> </section> </body> </html> 2、設(shè)置歡迎頁,web.xml中設(shè)置 <!-- 設(shè)置歡迎頁(首頁) --> <welcome-file-list> <welcome-file>login.jsp</welcome-file> </welcome-file-list> 3、編寫Dao層 得到用戶登錄的接口 package com.zcy.dao.user; import com.zcy.pojo.User; import java.sql.Connection; import java.sql.SQLException; //操作用戶的Dao public interface UserDao {/** * 獲得想要登錄的用戶 * @param connection 連接參數(shù) * @param userCode 用戶賬號 * @return 返回想登錄的用戶對象,為null則沒有該用戶 */ public User getLoginUser(Connection connection, String userCode) throws SQLException; } 4、編寫Dao 接口的實(shí)現(xiàn)類 package com.zcy.dao.user; import com.zcy.dao.BaseDao; import com.zcy.pojo.User; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class UserDaoImpl implements UserDao {/** * * @param connection 連接參數(shù) * @param userCode 用戶賬號 * @return 返回想登錄的用戶對象,為null則沒有該用戶 * @throws SQLException */ public User getLoginUser(Connection connection, String userCode) throws SQLException {ResultSet resultSet = null; User user = null; if (connection != null){String sql = "select * from smbms_user where userCode = ?"; Object[] params = {userCode}; resultSet = BaseDao.execute(connection, sql, params); if (resultSet.next()){user = new User(); user.setId(resultSet.getInt("id")); user.setUserCode(resultSet.getString("userCode")); user.setUserName(resultSet.getString("userName")); user.setUserPassword(resultSet.getString("userPassword")); user.setGender(resultSet.getInt("gender")); user.setBirthday(resultSet.getDate("birthday")); user.setPhone(resultSet.getString("phone")); user.setAddress(resultSet.getString("address")); user.setUserRole(resultSet.getInt("userRole")); user.setCreatedBy(resultSet.getInt("createdBy")); user.setCreationDate(resultSet.getTimestamp("creationDate")); user.setModifyBy(resultSet.getInt("modifyBy")); user.setModifyDate(resultSet.getTimestamp("modifyDate")); } BaseDao.closeResource(null, null, resultSet); } return user; } } 5、業(yè)務(wù)層接口 package com.zcy.service.user; import com.zcy.pojo.User; public interface UserService {/** * 用戶登錄 * @param userCode 用戶編號 * @param password 用戶密碼 * @return 存在該用戶,則返回用戶對象,不存在則為null */ public User login(String userCode, String password); } 6、業(yè)務(wù)層實(shí)現(xiàn)類 package com.zcy.service.user; import com.zcy.dao.BaseDao; import com.zcy.dao.user.UserDao; import com.zcy.dao.user.UserDaoImpl; import com.zcy.pojo.User; import org.junit.Test; import java.sql.Connection; import java.sql.SQLException; public class UserServiceImpl implements UserService {//業(yè)務(wù)層都會調(diào)用Dao層,所有我們要先引入Dao層 private UserDao userDao; /** * 實(shí)例化Dao層的對象 */ public UserServiceImpl(){userDao = new UserDaoImpl(); } /** * 在這個(gè)業(yè)務(wù)層調(diào)用Dao層的具體數(shù)據(jù)庫操作,獲得要登錄的用戶對象 * @param userCode 用戶編碼 * @param password 用戶密碼 * @return 要登錄的用戶對象,為null則沒有該用戶 */ public User login(String userCode, String password) {Connection connection = null; User user = null; try {connection = BaseDao.getConnection(); //在業(yè)務(wù)層調(diào)用對應(yīng)的具體數(shù)據(jù)庫操作,這里就是獲取要登錄的用戶對象 user = userDao.getLoginUser(connection, userCode); } catch (SQLException e) {e.printStackTrace(); }finally {BaseDao.closeResource(connection, null, null); } if (user == null || !user.getUserPassword().equals(password)) return null; else return user; } /** * 用于測試,可直接刪除 */ @Test public void test(){UserServiceImpl userService = new UserServiceImpl(); User admin = userService.login("admin", "abcdefg"); System.out.println(admin.getUserPassword()); } } 7、編寫Servlet package com.zcy.servlet.user; import com.zcy.pojo.User; import com.zcy.service.UserService; import com.zcy.service.UserServiceImpl; import com.zcy.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:控制層,調(diào)用業(yè)務(wù)層代碼 @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"); UserService 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", "用戶名或密碼錯誤"); //這里之所以用轉(zhuǎn)發(fā)而不是重定向,是因?yàn)榍岸耸钦{(diào)用request里的error變量 //轉(zhuǎn)發(fā)可以將請求轉(zhuǎn)發(fā)出去,保證了error的存活 req.getRequestDispatcher("login.jsp").forward(req, resp); } } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doGet(req, resp); } } 之所以能夠提示用戶名或密碼錯誤,是因?yàn)閘ogin.jsp中引用了error變量 [外鏈圖片轉(zhuǎn)存失敗,源站可能有防盜鏈機(jī)制,建議將圖片保存下來直接上傳(img-ot3uF0Oy-1613812859456)(JavaWeb6.assets/1613662585905.png)] 在頁面頭部中,也引用了session中的用戶信息 8、注冊Servlet <servlet> <servlet-name>LoginServlet</servlet-name> <servlet-class>com.zcy.servlet.user.LoginServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>LoginServlet</servlet-name> <url-pattern>/login.do</url-pattern> </servlet-mapping> 注銷攔截[外鏈圖片轉(zhuǎn)存失敗,源站可能有防盜鏈機(jī)制,建議將圖片保存下來直接上傳(img-UmM8Fb6L-1613812859458)(JavaWeb6.assets/1613790345822.png)] 1、注銷功能:移除用戶session并返回登錄界面 LogoutServlet.java package com.zcy.servlet.user; import com.zcy.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 doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doGet(req,resp); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//注銷:移除用戶session req.getSession().removeAttribute(Constants.USER_SESSION); resp.sendRedirect(req.getContextPath() "/login.jsp"); } } 注冊Servlet <servlet> <servlet-name>LogoutServlet</servlet-name> <servlet-class>com.zcy.servlet.user.LogoutServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>LogoutServlet</servlet-name> <url-pattern>/jsp/logout.do</url-pattern> </servlet-mapping> 2、登錄攔截 package com.zcy.filter; import com.sun.deploy.net.HttpResponse; import com.zcy.pojo.User; import com.zcy.util.Constants; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class LoginFilter 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); //如果用戶沒有登錄或者已經(jīng)注銷,則再想進(jìn)入主頁面就會被攔截,然后重定向 if(user == null) response.sendRedirect(request.getContextPath() "/error.jsp"); else chain.doFilter(req, resp); } public void destroy() {} } 注冊 <!-- 過濾未登錄用戶 --> <filter> <filter-name>LoginFilter</filter-name> <filter-class>com.zcy.filter.LoginFilter</filter-class> </filter> <filter-mapping> <filter-name>LoginFilter</filter-name> <url-pattern>/jsp/*</url-pattern> </filter-mapping> 密碼修改[外鏈圖片轉(zhuǎn)存失敗,源站可能有防盜鏈機(jī)制,建議將圖片保存下來直接上傳(img-XpGMQN1r-1613812859459)(JavaWeb6.assets/1613700217236.png)] [外鏈圖片轉(zhuǎn)存失敗,源站可能有防盜鏈機(jī)制,建議將圖片保存下來直接上傳(img-XYkTlQvo-1613812859462)(JavaWeb6.assets/1613790384793.png)] 1、UserDao.java中添加方法 /** * 修改用戶密碼 * @param connection 連接參數(shù) * @param id 用戶ID號 * @param password 用戶新密碼 * @return 返回修改的行數(shù)(1表示成功 0表示失敗) * @throws SQLException */ public int updatePassword(Connection connection, int id, String password) throws SQLException; 2、UserDaoImpl.java中添加方法 /** * * @param connection 連接參數(shù) * @param id 用戶ID號 * @param password 用戶新密碼 * @return 返回修改的行數(shù)(1表示成功 0表示失敗) * @throws SQLException */ public int updatePassword(Connection connection, int id, String password) throws SQLException {PreparedStatement preparedStatement = null; int updateRows = 0; if (connection != null){String sql = "update smbms_user set userPassword = ? where id = ?"; preparedStatement = connection.prepareStatement(sql); Object[] params = {password, id}; updateRows = BaseDao.update(connection, preparedStatement, params); BaseDao.closeResource(null, preparedStatement, null); } return updateRows; } 3、UserServiceImp.java中添加方法 /** * 根據(jù)用戶id和密碼修改用戶密碼 * @param id 用戶id * @param password 用戶密碼 * @return 返回true 或 false */ public boolean updatePassword(int id, String password) {Connection connection = null; boolean flag = false; try {connection = BaseDao.getConnection(); if (userDao.updatePassword(connection, id, password) > 0) flag = true; } catch (SQLException e) {e.printStackTrace(); }finally {BaseDao.closeResource(connection, null, null); } return flag; } 4、UserServlet.java package com.zcy.servlet.user; import com.alibaba.fastjson.JSONArray; import com.mysql.jdbc.StringUtils; import com.zcy.pojo.User; import com.zcy.service.UserService; import com.zcy.service.UserServiceImpl; import com.zcy.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; import java.io.PrintWriter; import java.util.HashMap; import java.util.Map; public class UserServlet extends HttpServlet {@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//從前端獲取參數(shù),根據(jù)參數(shù)執(zhí)行對應(yīng)方法 String method = req.getParameter("method"); if (method.equals("savepwd")) updatePassword(req,resp); else if (method.equals("pwdmodify")) pwdModify(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doGet(req, resp); } //更新密碼 public void updatePassword(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {Object o = req.getSession().getAttribute(Constants.USER_SESSION); String newPassword = req.getParameter("newpassword"); boolean flag = false; if (o != null && !StringUtils.isEmptyOrWhitespaceOnly(newPassword)){UserService userService = new UserServiceImpl(); flag = userService.updatePassword(((User)o).getId(), newPassword); if (flag){//因?yàn)榍岸藀wdmodify.jsp中留有一個(gè)message的位置,可以顯示數(shù)據(jù) req.setAttribute("message", "密碼修改成功,請重新用新密碼登錄"); //移除用戶Session,相當(dāng)于自動注銷 req.getSession().removeAttribute(Constants.USER_SESSION); } else req.setAttribute("message", "密碼修改失敗"); } else req.setAttribute("message", "新密碼有問題"); req.getRequestDispatcher("pwdmodify.jsp").forward(req,resp); } //驗(yàn)證舊密碼,無需查詢數(shù)據(jù)庫,直接從當(dāng)前session中的user對象獲取 public void pwdModify(HttpServletRequest req, HttpServletResponse resp){//從session中拿取用戶對象 Object o = req.getSession().getAttribute(Constants.USER_SESSION); //獲取前端(Ajax部分)傳過來的舊密碼,并于user中的密碼比對 String oldPassword = req.getParameter("oldpassword"); //用Map結(jié)果集作為響應(yīng),返回給前端(Ajax部分) Map<String, String> resultMap = new HashMap<String, String>(); if (o == null){//session失效或過期時(shí)(真實(shí)網(wǎng)站的session會設(shè)置過期時(shí)間) resultMap.put("result", "sessionerror"); } else if(StringUtils.isEmptyOrWhitespaceOnly(oldPassword)){//輸入的舊密碼為空 resultMap.put("result", "error"); }else {String userPassword = ((User)o).getUserPassword();//已登錄用戶的現(xiàn)在密碼 //比對輸入的舊密碼和session中用戶密碼 if (oldPassword.equals(userPassword)) resultMap.put("result", "true"); else resultMap.put("result", "false"); } try {resp.setContentType("application/json"); PrintWriter writer = resp.getWriter(); //JSONArray 阿里巴巴的JSON工具類,將Map類轉(zhuǎn)換為json(前端Ajax接受的是json格式) writer.write(JSONArray.toJSONString(resultMap)); writer.flush(); writer.close(); }catch (IOException e){e.printStackTrace(); } } } 配合pwdmodify.js中的Ajax,看舊密碼驗(yàn)證部分 oldpassword.on("blur",function(){ $.ajax({ type:"GET", url:path "/jsp/user.do", data:{method:"pwdmodify",oldpassword:oldpassword.val()}, dataType:"json", success:function(data){ if(data.result == "true"){//舊密碼正確 validateTip(oldpassword.next(),{"color":"green"},imgYes,true); }else if(data.result == "false"){//舊密碼輸入不正確 validateTip(oldpassword.next(),{"color":"red"},imgNo " 原密碼輸入不正確",false); }else if(data.result == "sessionerror"){//當(dāng)前用戶session過期,請重新登錄 validateTip(oldpassword.next(),{"color":"red"},imgNo " 當(dāng)前用戶session過期,請重新登錄",false); }else if(data.result == "error"){//舊密碼輸入為空 validateTip(oldpassword.next(),{"color":"red"},imgNo " 請輸入舊密碼",false); } }, error:function(data){ //請求出錯 validateTip(oldpassword.next(),{"color":"red"},imgNo " 請求錯誤",false); } }); 5、注冊UserServlet <servlet> <servlet-name>UserServlet</servlet-name> <servlet-class>com.zcy.servlet.user.UserServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>UserServlet</servlet-name> <url-pattern>/jsp/user.do</url-pattern> </servlet-mapping> 用戶管理[外鏈圖片轉(zhuǎn)存失敗,源站可能有防盜鏈機(jī)制,建議將圖片保存下來直接上傳(img-0HpMxAHs-1613812859464)(JavaWeb6.assets/1613789097729.png)] 先寫 PageSupport.java 分頁工具類 package com.zcy.util; public class PageSupport { //當(dāng)前頁碼-來自于用戶輸入 private int currentPageNo = 1; //總數(shù)量(表) private int totalCount = 0; //頁面容量 private int pageSize = 0; //總頁數(shù)-totalCount/pageSize( 1) private int totalPageCount = 1; public int getCurrentPageNo() { return currentPageNo; } public void setCurrentPageNo(int currentPageNo) { if(currentPageNo > 0){ this.currentPageNo = currentPageNo; } } public int getTotalCount() { return totalCount; } public void setTotalCount(int totalCount) { if(totalCount > 0){ this.totalCount = totalCount; //設(shè)置總頁數(shù) this.setTotalPageCountByRs(); } } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { if(pageSize > 0){ this.pageSize = pageSize; } } public int getTotalPageCount() { return totalPageCount; } public void setTotalPageCount(int totalPageCount) { this.totalPageCount = totalPageCount; } public void setTotalPageCountByRs(){ if(this.totalCount % this.pageSize == 0){ this.totalPageCount = this.totalCount / this.pageSize; }else if(this.totalCount % this.pageSize > 0){ this.totalPageCount = this.totalCount / this.pageSize 1; }else{ this.totalPageCount = 0; } } } 1、獲取用戶數(shù)量1、UserDao.java添加方法 /** * 根據(jù)用戶名或角色類型 獲取用戶數(shù)量 * @param connection 連接參數(shù) * @param userName 用戶名 * @param userRole 用戶角色類型 * @return 用戶數(shù)量 */ public int getUserCount(Connection connection, String userName, int userRole) throws SQLException; 2、UserDaoImpl.java添加方法 /** * 根據(jù)用戶id和密碼修改密碼 * @param connection 連接參數(shù) * @param userName 用戶名 * @param userRole 用戶角色類型 * @return 用戶數(shù)量 * @throws SQLException */ public int getUserCount(Connection connection, String userName, int userRole) throws SQLException {PreparedStatement preparedStatement = null; ResultSet resultSet = null; int count = 0;//這里用int更好,Integer不合適,因?yàn)閏ount必定不為null 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>();//存放參數(shù) if (!StringUtils.isNullOrEmpty(userName)){sql.append(" and u.userName like ?"); list.add("%" userName "%");//like 模糊查詢 } //因?yàn)榻巧闹凳?nbsp;1 2 3 if (userRole>0){sql.append(" and r.id = ?"); list.add(userRole); } Object[] params = list.toArray(); //輸出完整SQL System.out.println("UserDaoImpl——>getUserCount:" sql.toString()); preparedStatement = connection.prepareStatement(sql.toString()); resultSet = BaseDao.query(connection, preparedStatement, params); if (resultSet.next()) count = resultSet.getInt("count"); BaseDao.closeResource(null, preparedStatement, resultSet); } return count; } 3、UserService.java添加方法 /** * 根據(jù)用戶名或用戶角色類型獲取用戶數(shù)量 * @param userName 用戶名 * @param userRole 用戶角色類型 * @return 用戶數(shù)量 */ public int getUserCount(String userName, int userRole); 4、UserServiceImpl.java添加方法 /** * 根據(jù)用戶名或用戶角色類型獲取用戶數(shù)量 * @param userName 用戶名 * @param userRole 用戶角色類型 * @return 用戶數(shù)量 */ 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; } @Test public void test(){UserServiceImpl userService = new UserServiceImpl(); int userCount = userService.getUserCount(null, 3); System.out.println(userCount); } 2、獲取用戶列表1、UserDao.java添加方法 /** * 通過條件查詢 * @param connection 連接參數(shù) * @param userName 用戶名 * @param userRole 用戶角色 * @param currentPageNo 當(dāng)前頁 * @param pageSize 頁面大小 * @return 用戶列表 */ public List<User> getUserList(Connection connection, String userName, int userRole, int currentPageNo, int pageSize) throws Exception; 2、UserDaoImpl.java添加方法 /** * 根據(jù)條件查詢 * @param connection 連接參數(shù) * @param userName 用戶名 * @param userRole 用戶角色 * @param currentPageNo 當(dāng)前頁 * @param pageSize 頁面大小 * @return 用戶列表 * @throws Exception */ public List<User> getUserList(Connection connection, String userName,int userRole,int currentPageNo, int pageSize) throws Exception {PreparedStatement preparedStatement = null; ResultSet resultSet = 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); } // 排序和分頁 // 分頁:limit 開始下標(biāo), 頁面大小 // 假如每頁3個(gè)數(shù)據(jù),我想從第2頁開始: 第一頁 0 1 2, 第二頁 3 4 5 // 開始下標(biāo)為 2 - 1 = 1, 1 * 3 = 3 // limit 3, 3 sql.append(" order by creationDate DESC limit ?,?"); currentPageNo = (currentPageNo-1)*pageSize; list.add(currentPageNo); list.add(pageSize); Object[] params = list.toArray(); System.out.println("UserDaoImpl——>getUserList:" sql.toString()); preparedStatement = connection.prepareStatement(sql.toString()); resultSet = BaseDao.query(connection, preparedStatement, params); while(resultSet.next()){User user = new User(); user.setId(resultSet.getInt("id")); user.setUserCode(resultSet.getString("userCode")); user.setUserName(resultSet.getString("userName")); user.setGender(resultSet.getInt("gender")); user.setBirthday(resultSet.getDate("birthday")); user.setPhone(resultSet.getString("phone")); user.setUserRole(resultSet.getInt("userRole")); user.setUserRoleName(resultSet.getString("userRoleName")); userList.add(user); } BaseDao.closeResource(null, preparedStatement, resultSet); } return userList; } 3、UserService.java添加方法 /** * 根據(jù)條件查詢用戶列表 * @param userName 用戶名 * @param userRole 用戶角色 * @param currentPageNo 當(dāng)前頁號 * @param pageSize 頁面大小 * @return 用戶列表 */ public List<User> getUserList(String userName, int userRole, int currentPageNo, int pageSize); 4、UserServiceImpl.java添加方法 public List<User> getUserList(String userName, int userRole, int currentPageNo, int pageSize) {Connection connection = null; List<User> users = null; System.out.println("UserServiceImpl——>getUserList:"); System.out.println("userName:" userName); System.out.println("userRole:" userRole); System.out.println("currentPageNo:" currentPageNo); System.out.println("pageSize:" pageSize); System.out.println("-------------------------------"); try {connection = BaseDao.getConnection(); userDao.getUserList(connection, userName, userRole, currentPageNo, pageSize); } catch (Exception e) {e.printStackTrace(); }finally {BaseDao.closeResource(connection, null, null); } return null; } 3、獲取角色列表為了職責(zé)更好統(tǒng)一,把角色的操作放在另一個(gè)包里,和POJO類對應(yīng)。 [外鏈圖片轉(zhuǎn)存失敗,源站可能有防盜鏈機(jī)制,建議將圖片保存下來直接上傳(img-2K42g1zg-1613812859466)(JavaWeb6.assets/1613812823643.png)] 1、RoleDao.java package com.zcy.dao.role; import com.zcy.pojo.Role; import java.sql.Connection; import java.sql.SQLException; import java.util.List; public interface RoleDao {/** * 角色列表是固定的,只有三個(gè)數(shù)據(jù),系統(tǒng)管理員1、經(jīng)理2、普通員工3 * @param connection 連接參數(shù) * @return 角色列表 */ public List<Role> getRoleList(Connection connection) throws SQLException; } 2、RoleDaoImpl.java package com.zcy.dao.role; import com.zcy.dao.BaseDao; import com.zcy.pojo.Role; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; public class RoleDaoImpl implements RoleDao {public List<Role> getRoleList(Connection connection) throws SQLException {PreparedStatement preparedStatement = null; ResultSet resultSet = null; ArrayList<Role> list = new ArrayList<Role>(); if(connection != null){String sql = "select * from smbms_role"; Object[] params = {}; preparedStatement = connection.prepareStatement(sql); resultSet = BaseDao.query(connection, preparedStatement, params); while (resultSet.next()){Role role = new Role(); role.setRoleName(resultSet.getString("roleName")); role.setId(resultSet.getInt("id")); role.setRoleCode(resultSet.getString("roleCode")); list.add(role); } BaseDao.closeResource(null, preparedStatement, resultSet); } return list; } } 3、RoleService.java package com.zcy.service.role; import com.zcy.pojo.Role; import java.util.List; public interface RoleService {//獲取角色列表 public List<Role> getRoleList(); } 4、RoleServiceImpl.java package com.zcy.service.role; import com.zcy.dao.BaseDao; import com.zcy.dao.role.RoleDao; import com.zcy.dao.role.RoleDaoImpl; import com.zcy.pojo.Role; import java.awt.image.RasterOp; 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(); } 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; } } 4、顯示前面的各種列表的Servlet 在UserServlet.java中增加方法 query //反饋給前端 用戶列表、角色列表、分頁(重難點(diǎn)) public void query(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//獲取用戶前端的數(shù)據(jù) String queryUserName = req.getParameter("queryname"); String temp = req.getParameter("queryUserRole"); String pageIndex = req.getParameter("pageIndex"); int queryUserRole = 0;//角色類型在數(shù)據(jù)庫整型的,默認(rèn)0,不代表任何角色 UserServiceImpl userService = new UserServiceImpl(); RoleServiceImpl roleService = new RoleServiceImpl(); int pageSize = 5;//默認(rèn)頁面大小顯示5個(gè)數(shù)據(jù) int currentPageNo = 1;//默認(rèn)當(dāng)前頁為第一頁 //判斷請求是否需要執(zhí)行,根據(jù)參數(shù)的值判斷 if (queryUserName == null){//請求中未包含用戶名參數(shù),角色名設(shè)置為空 queryUserName = ""; } if (!StringUtils.isNullOrEmpty(temp)){//請求包含了角色參數(shù),將字符串轉(zhuǎn)為整型 queryUserRole = new Integer(temp); } if (pageIndex != null){//請求中包含頁碼,表明想看某一頁數(shù)據(jù),設(shè)置當(dāng)前頁為想看的那一頁 currentPageNo = Integer.parseInt(pageIndex); } // 3. 為了實(shí)現(xiàn)分頁,需要計(jì)算出當(dāng)前頁面、總頁面、頁面大小 int totalCount = userService.getUserCount(queryUserName, queryUserRole);//用戶總數(shù) //總頁數(shù)支持 PageSupport pageSupport = new PageSupport(); pageSupport.setCurrentPageNo(currentPageNo); pageSupport.setPageSize(pageSize); pageSupport.setTotalCount(totalCount); int totalPageCount = pageSupport.getTotalPageCount();//總頁數(shù) //控制首頁和尾頁,如果頁面要小于1或者大于總頁數(shù),則進(jìn)行限制 if (currentPageNo < 1) currentPageNo = 1; else if (currentPageNo > totalPageCount) currentPageNo = totalPageCount; //獲得用戶列表數(shù)據(jù)和角色數(shù)據(jù)列表 List<User> userList = userService.getUserList(queryUserName, queryUserRole, currentPageNo, pageSize); List<Role> roleList = roleService.getRoleList(); //將數(shù)據(jù)放入request req.setAttribute("userList", userList); req.setAttribute("roleList", roleList); req.setAttribute("totalCount", totalCount); req.setAttribute("currentPageNo", currentPageNo); req.setAttribute("totalPageCount", totalPageCount); req.setAttribute("queryUserName", queryUserName); req.setAttribute("queryUserRole", queryUserRole); //返回前端,用請求轉(zhuǎn)發(fā),因?yàn)閿?shù)據(jù)放在request中 req.getRequestDispatcher("userlist.jsp").forward(req, resp); } 同時(shí),修改doGet里的程序 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//從前端獲取參數(shù),根據(jù)參數(shù)執(zhí)行對應(yīng)方法 String method = req.getParameter("method"); if (method!=null && method.equals("savepwd")) this.updatePassword(req,resp); else if (method!=null && method.equals("pwdmodify")) this.pwdModify(req, resp); else if (method!=null && method.equals("query")){this.query(req, resp); } } 4、添加用戶1、UserDao.java添加方法 /** * 增加一個(gè)用戶 * @param connection * @param user * @return 操作成功的行數(shù) */ public int addUser(Connection connection, User user) throws SQLException; 2、UserDaoImpl.java添加方法 public int addUser(Connection connection, User user) throws SQLException {PreparedStatement preparedStatement = null; int updateRows = 0; if (connection != null){String sql = "insert into smbms_user" " (userCode, userName, userPassword, gender, birthday, phone, address, userRole, creationDate, createdBy)" "values (?,?,?,?,?,?,?,?,?,?)"; preparedStatement = connection.prepareStatement(sql); Object[] params = {user.getUserCode(),user.getUserName(),user.getUserPassword(), user.getGender(),user.getBirthday(), user.getPhone(),user.getAddress(), user.getUserRole(), user.getCreationDate(),user.getCreatedBy()}; updateRows = BaseDao.update(connection, preparedStatement, params); BaseDao.closeResource(null, preparedStatement, null); } return updateRows; } 3、UserService.java添加方法 /** * 添加一個(gè)用戶 * @param user 用戶對象 * @return true 添加成功,false 添加失敗 */ public boolean addUser(User user); 4、UserServiceImpl.java添加方法 /** * 添加一個(gè)用戶 * @param user 用戶對象 * @return true 添加成功,false 添加失敗 */ public boolean addUser(User user) {Connection connection = null; boolean flag = false; try {connection = BaseDao.getConnection(); connection.setAutoCommit(false);//關(guān)閉自動提交,開啟事務(wù)管理 int updateRows = userDao.addUser(connection, user); connection.commit();//提交 if (updateRows > 0){flag = true; System.out.println("UserServiceImpl——>addUser:成功添加用戶"); } else System.out.println("UserServiceImpl——>addUser:添加用戶失敗"); } catch (Exception e) {e.printStackTrace(); try {connection.rollback(); System.out.println("UserServiceImpl——>addUser:回滾"); } catch (SQLException ex) {ex.printStackTrace(); } }finally {//Service層關(guān)閉connection連接 BaseDao.closeResource(connection, null, null); } return flag; } 5、UserServlet.java添加方法 //添加用戶 public void add(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {String userCode = req.getParameter("userCode"); String userName = req.getParameter("userName"); String userPassword = req.getParameter("userPassword"); String gender = req.getParameter("gender"); String birthday = req.getParameter("birthday"); String phone = req.getParameter("phone"); String address = req.getParameter("address"); String userRole = req.getParameter("userRole"); User user = new User(); user.setUserCode(userCode); user.setUserName(userName); user.setUserPassword(userPassword); user.setGender(Integer.parseInt(gender)); try {user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday)); } catch (ParseException e) {e.printStackTrace(); } user.setPhone(phone); user.setAddress(address); user.setUserRole(Integer.parseInt(userRole)); user.setCreationDate(new Date()); user.setCreatedBy(((User)req.getSession().getAttribute(Constants.USER_SESSION)).getId()); UserServiceImpl userService = new UserServiceImpl(); //添加成功,就直接重定向到查詢頁面顯示數(shù)據(jù);添加失敗,則請求轉(zhuǎn)發(fā),重新添加。(請求轉(zhuǎn)發(fā)能保留request的數(shù)據(jù)) if (userService.addUser(user)) resp.sendRedirect(req.getContextPath() "/jsp/user.do?method=query"); else req.getRequestDispatcher("useradd.jsp").forward(req, resp); } 總結(jié)項(xiàng)目的功能沒有全部實(shí)現(xiàn)完,整個(gè)項(xiàng)目邏輯比較簡單,主要是將之前學(xué)的鞏固練手,其他的功能實(shí)現(xiàn)方法都是類似的。 |
|