110_超市訂單管理系統(SMBMS)



功能設計

image.png

數據庫設計

image.png

項目搭建

創建MavenWeb項目

image.png
image.png

刪除pom文件中無用的配置

image.png

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.qing</groupId>
  <artifactId>smbms</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>
  
</project>

web.xml更新到最新版4.0

image.png

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                      http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0"
         metadata-complete="true">

</web-app>

創建java和resources

image.png

配置Tomcat

image.png
image.png

測試項目是否運行成功

image.png
image.png

在gitee創建遠程倉庫並關聯

創建遠程倉庫
image.png
創建本地倉庫

Administrator@L87Y12K91TH8M2R MINGW64 /d/code/smbms
$ git init
Initialized empty Git repository in D:/code/smbms/.git/

Administrator@L87Y12K91TH8M2R MINGW64 /d/code/smbms (main)
$ ll -a
total 18
drwxr-xr-x 1 Administrator 197121   0 Apr 22 22:44 ./
drwxr-xr-x 1 Administrator 197121   0 Apr 21 23:43 ../
drwxr-xr-x 1 Administrator 197121   0 Apr 22 22:44 .git/
drwxr-xr-x 1 Administrator 197121   0 Apr 22 22:43 .idea/
-rw-r--r-- 1 Administrator 197121 435 Apr 21 23:48 pom.xml
-rw-r--r-- 1 Administrator 197121  81 Apr 21 23:44 smbms.iml
drwxr-xr-x 1 Administrator 197121   0 Apr 21 23:44 src/
drwxr-xr-x 1 Administrator 197121   0 Apr 22 22:36 target/

Administrator@L87Y12K91TH8M2R MINGW64 /d/code/smbms (main)

關聯遠程倉庫,並拉取遠程倉庫文件

D:\code\smbms>git remote add origin git@gitee.com:wl3pbzhyq/smbms.git

D:\code\smbms>git pull origin master
remote: Enumerating objects: 6, done.
remote: Counting objects: 100% (6/6), done.
remote: Compressing objects: 100% (6/6), done.

Unpacking objects: 100% (6/6), 13.30 KiB | 46.00 KiB/s, done.
From gitee.com:wl3pbzhyq/smbms
 * branch            master     -> FETCH_HEAD
 * [new branch]      master     -> origin/master

配置忽略文件

# target
target/

# idea
.idea/
*.iml

image.png
提交main分支到遠程倉庫

D:\code\smbms>git add .
warning: LF will be replaced by CRLF in src/main/webapp/index.jsp.
The file will have its original line endings in your working directory

D:\code\smbms>git status
On branch main
Changes to be committed:
  (use "git restore --staged <file>..." to unstage)
        modified:   .gitignore
        new file:   pom.xml
        new file:   src/main/webapp/WEB-INF/web.xml
        new file:   src/main/webapp/index.jsp


D:\code\smbms>git commit -m "初始化"
[main cef378e] 初始化
 4 files changed, 34 insertions(+)
 create mode 100644 pom.xml
 create mode 100644 src/main/webapp/WEB-INF/web.xml
 create mode 100644 src/main/webapp/index.jsp

D:\code\smbms>git push --set-upstream origin main
Enumerating objects: 12, done.
Counting objects: 100% (12/12), done.
Delta compression using up to 4 threads
Compressing objects: 100% (7/7), done.
Writing objects: 100% (10/10), 1.14 KiB | 106.00 KiB/s, done.
Total 10 (delta 1), reused 0 (delta 0), pack-reused 0
remote: Powered by GITEE.COM [GNK-5.0]
remote: Create a pull request for 'main' on Gitee by visiting:
remote:     https://gitee.com/wl3pbzhyq/smbms/pull/new/wl3pbzhyq:main...wl3pbzhyq:master
To gitee.com:wl3pbzhyq/smbms.git
 * [new branch]      main -> main
Branch 'main' set up to track remote branch 'main' from 'origin'.

D:\code\smbms>

pom.xml添加依賴:servlet,jsp,JSTL表達式,standard標簽庫,mysql驅動,lombok

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.qing</groupId>
    <artifactId>smbms</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <dependencies>
        <!--Servlet-->
        <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
        </dependency>
        <!--JSP-->
        <!-- https://mvnrepository.com/artifact/javax.servlet.jsp/javax.servlet.jsp-api -->
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>javax.servlet.jsp-api</artifactId>
            <version>2.3.3</version>
        </dependency>
        <!--JSTL表達式-->
        <!-- https://mvnrepository.com/artifact/javax.servlet.jsp.jstl/jstl-api -->
        <dependency>
            <groupId>javax.servlet.jsp.jstl</groupId>
            <artifactId>jstl-api</artifactId>
            <version>1.2</version>
        </dependency>
        <!--standard標簽庫-->
        <!-- https://mvnrepository.com/artifact/taglibs/standard -->
        <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
            <version>1.1.2</version>
        </dependency>
        <!--mysql驅動-->
        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <!--lombok-->
        <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.12</version>
        </dependency>
    </dependencies>
</project>

創建項目包結構

image.png

編寫實體類:ORM映射:表-類映射

idea連接數據庫

image.png

編寫實體類

/*
Navicat MySQL Data Transfer

Source Server         : local
Source Server Version : 50729
Source Host           : localhost:3306
Source Database       : smbms

Target Server Type    : MYSQL
Target Server Version : 50729
File Encoding         : 65001

Date: 2021-04-26 23:06:06
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for `smbms_address`
-- ----------------------------
DROP TABLE IF EXISTS `smbms_address`;
CREATE TABLE `smbms_address` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '收貨地址主鍵',
  `user_id` int(11) DEFAULT NULL COMMENT '用戶主鍵',
  `contact` varchar(64) DEFAULT NULL COMMENT '聯系人',
  `address` varchar(64) DEFAULT NULL COMMENT '地址',
  `post_code` varchar(64) DEFAULT NULL COMMENT '郵政編碼',
  `phone` varchar(64) DEFAULT NULL COMMENT '電話',
  `create_by` int(11) DEFAULT NULL COMMENT '創建者',
  `create_date` datetime DEFAULT NULL COMMENT '創建時間',
  `modify_by` int(11) DEFAULT NULL COMMENT '更新者',
  `modify_date` datetime DEFAULT NULL COMMENT '更新時間',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='收貨地址表';

-- ----------------------------
-- Records of smbms_address
-- ----------------------------

-- ----------------------------
-- Table structure for `smbms_bill`
-- ----------------------------
DROP TABLE IF EXISTS `smbms_bill`;
CREATE TABLE `smbms_bill` (
  `id` int(11) NOT NULL COMMENT '賬單主鍵',
  `provider_id` int(11) DEFAULT NULL COMMENT '供應商主鍵',
  `code` varchar(64) DEFAULT NULL COMMENT '賬單編號',
  `product_name` varchar(64) DEFAULT NULL COMMENT '商品名稱',
  `product_desc` varchar(64) DEFAULT NULL COMMENT '商品描述',
  `product_unit` varchar(64) DEFAULT NULL COMMENT '商品單位',
  `product_count` decimal(20,2) DEFAULT NULL COMMENT '商品數量',
  `total_price` decimal(20,2) DEFAULT NULL COMMENT '總金額',
  `status` int(11) DEFAULT NULL COMMENT '賬單狀態:1未支付/2已支付',
  `create_by` int(11) DEFAULT NULL COMMENT '創建者',
  `create_date` datetime DEFAULT NULL COMMENT '創建時間',
  `modify_by` int(11) DEFAULT NULL COMMENT '更新者',
  `modify_date` datetime DEFAULT NULL COMMENT '更新時間',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='賬單表';

-- ----------------------------
-- Records of smbms_bill
-- ----------------------------

-- ----------------------------
-- Table structure for `smbms_provider`
-- ----------------------------
DROP TABLE IF EXISTS `smbms_provider`;
CREATE TABLE `smbms_provider` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '供應商主鍵',
  `code` varchar(64) DEFAULT NULL COMMENT '供應商編號',
  `name` varchar(64) DEFAULT NULL COMMENT '供應商名稱',
  `pro_desc` varchar(64) DEFAULT NULL COMMENT '供應商描述',
  `contact` varchar(64) DEFAULT NULL COMMENT '聯系人',
  `phone` varchar(64) DEFAULT NULL COMMENT '電話',
  `address` varchar(64) DEFAULT NULL COMMENT '地址',
  `fax` varchar(64) DEFAULT NULL COMMENT '傳真',
  `create_by` int(11) DEFAULT NULL COMMENT '創建者',
  `create_date` datetime DEFAULT NULL COMMENT '創建時間',
  `modify_by` int(11) DEFAULT NULL COMMENT '更新者',
  `modify_date` datetime DEFAULT NULL COMMENT '更新時間',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='供應商表';

-- ----------------------------
-- Records of smbms_provider
-- ----------------------------

-- ----------------------------
-- Table structure for `smbms_role`
-- ----------------------------
DROP TABLE IF EXISTS `smbms_role`;
CREATE TABLE `smbms_role` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '角色主鍵',
  `code` varchar(64) DEFAULT NULL COMMENT '角色編號',
  `name` varchar(64) DEFAULT NULL COMMENT '角色名稱',
  `create_by` int(11) DEFAULT NULL COMMENT '創建者',
  `create_date` datetime DEFAULT NULL COMMENT '創建時間',
  `modify_by` int(11) DEFAULT NULL COMMENT '更新者',
  `modify_date` datetime DEFAULT NULL COMMENT '更新時間',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='角色表';

-- ----------------------------
-- Records of smbms_role
-- ----------------------------

-- ----------------------------
-- Table structure for `smbms_user`
-- ----------------------------
DROP TABLE IF EXISTS `smbms_user`;
CREATE TABLE `smbms_user` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '用戶主鍵',
  `role_id` int(11) DEFAULT NULL COMMENT '角色主鍵',
  `code` varchar(64) DEFAULT NULL COMMENT '用戶編號',
  `name` varchar(64) DEFAULT NULL COMMENT '用戶名稱',
  `password` varchar(64) DEFAULT NULL COMMENT '用戶密碼',
  `gender` int(11) DEFAULT NULL COMMENT '性別:1男/2女',
  `birthday` date DEFAULT NULL COMMENT '出生日期',
  `phone` varchar(64) DEFAULT NULL COMMENT '電話',
  `address` varchar(64) DEFAULT NULL COMMENT '地址',
  `create_by` int(11) DEFAULT NULL COMMENT '創建者',
  `create_date` datetime DEFAULT NULL COMMENT '創建時間',
  `modify_by` int(11) DEFAULT NULL COMMENT '更新者',
  `modify_date` datetime DEFAULT NULL COMMENT '更新時間',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='用戶表';

-- ----------------------------
-- Records of smbms_user
-- ----------------------------

image.png

編寫基礎公共類

數據庫配置文件 db.properties

image.png

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/smbms?useUnicode=true&characterEncoding=utf8&useSSL=false
username=root
password=123456

編寫數據庫的公共類:獲取數據庫連接,釋放資源,公共查詢,公共增刪改

image.png

package com.qing.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 {
        Properties properties = new Properties();
        // 通過類加載器讀取資源:資源轉為流
        InputStream is = BaseDao.class.getClassLoader().getResourceAsStream("db.properties");
        try {
            properties.load(is);
            driver = properties.getProperty("driver");
            url = properties.getProperty("url");
            username = properties.getProperty("username");
            password = properties.getProperty("password");
            Class.forName(driver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 獲取數據庫連接
     */
    public static Connection getConnection() {
        Connection connection = null;
        try {
            connection = DriverManager.getConnection(url, username, password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return connection;
    }

    /**
     * 公共查詢
     */
    public static ResultSet execute(Connection connection,String sql,PreparedStatement ps,Object[] params,ResultSet rs) throws SQLException {
        ps = connection.prepareStatement(sql);
        for (int i = 0; i < params.length; i++) {
            // 占位符從1開始,數組從0開始
            ps.setObject(i+1,params[i]);
        }
        rs = ps.executeQuery();
        return rs;
    }

    /**
     * 公共增刪改
     */
    public static int execute(Connection connection,String sql,PreparedStatement ps,Object[] params) throws SQLException {
        ps = connection.prepareStatement(sql);
        for (int i = 0; i < params.length; i++) {
            // 占位符從1開始,數組從0開始
            ps.setObject(i+1,params[i]);
        }
        // 影響的行數
        int updateRows = ps.executeUpdate();
        return updateRows;
    }

    /**
     * 釋放資源
     */
    public static boolean close(Connection connection,PreparedStatement ps,ResultSet rs) {
        boolean flag = true;
        if (rs != null) {
            try {
                rs.close();
                // GC回收
                rs = null;
            } catch (SQLException e) {
                e.printStackTrace();
                flag = false;
            }
        }
        if (ps != null) {
            try {
                ps.close();
                // GC回收
                ps = null;
            } catch (SQLException e) {
                e.printStackTrace();
                flag = false;
            }
        }
        if (connection != null) {
            try {
                connection.close();
                // GC回收
                connection = null;
            } catch (SQLException e) {
                e.printStackTrace();
                flag = false;
            }
        }
        return flag;
    }
}

編寫字符編碼過濾器,web.xml中配置過濾器

image.png

package com.qing.filter;

import javax.servlet.*;
import java.io.IOException;

/**
 * 字符編碼過濾器
 */
public class CharacterEncodingFilter implements Filter {
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        servletRequest.setCharacterEncoding("utf-8");
        servletResponse.setCharacterEncoding("utf-8");
        // 讓請求繼續通行,如果不寫,程序到這里就被攔截停止
        filterChain.doFilter(servletRequest,servletResponse);
    }

    public void destroy() {

    }
}

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                      http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0"
         metadata-complete="true">
    
    <!--字符編碼過濾器-->
    <filter>
        <filter-name>CharacterEncodingFilter</filter-name>
        <filter-class>com.qing.filter.CharacterEncodingFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

</web-app>

導入靜態資源

image.png

登錄功能實現

image.png

編寫前端頁面

image.png

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>

<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>系統登錄 - 超市訂單管理系統</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>超市訂單管理系統</h1>
    </header>
    <section class="loginCont">
        <form class="loginForm" action="${pageContext.request.contextPath}/login.do" method="post" name="actionForm"
              id="actionForm">
            <div class="info">${error}</div>
            <div class="inputbox">
                <label for="code">用戶名:</label>
                <input type="text" class="input-text" id="code" name="code" placeholder="請輸入用戶名" required/>
            </div>
            <div class="inputbox">
    <label for="password">密碼:</label>
    <input type="password" id="password" name="password" placeholder="請輸入密碼" required/>
    </div>
    <div class="subBtn">
        <input type="submit" value="登錄"/>
        <input type="reset" value="重置"/>
    </div>
    </form>
</section>
</section>
</body>
</html>

設置歡迎頁面:web.xml中設置

<!--設置歡迎頁面-->
<welcome-file-list>
  <welcome-file>login.jsp</welcome-file>
</welcome-file-list>
<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                      http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0"
         metadata-complete="true">

    <!--字符編碼過濾器-->
    <filter>
        <filter-name>CharacterEncodingFilter</filter-name>
        <filter-class>com.qing.filter.CharacterEncodingFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!--設置歡迎頁面-->
    <welcome-file-list>
        <welcome-file>login.jsp</welcome-file>
    </welcome-file-list>

</web-app>

image.png

編寫Dao層接口和實現類:根據編號獲取用戶方法

image.png

package com.qing.dao.user;

import com.qing.pojo.User;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * 用戶Dao接口
 */
public interface UserDao {

    /**
     * 根據編號和密碼獲取用戶
     */
    public User getLoginUser(Connection connection, String code, String password) throws SQLException;
}

package com.qing.dao.user;

import com.qing.dao.BaseDao;
import com.qing.pojo.User;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 用戶Dao實現類
 */
public class UserDaoImpl implements UserDao {

    /**
     * 根據編號和密碼獲取用戶
     */
    public User getLoginUser(Connection connection, String code, String password) throws SQLException {
        User user = null;
        if (connection != null) {
            PreparedStatement ps = null;
            ResultSet rs = null;
            String sql = "select * from smbms_user where code=? and password=?";
            Object[] params = {code,password};
            rs = BaseDao.execute(connection, ps, rs, sql, params);
            if (rs.next()) {
                user = new User();
                user.setId(rs.getInt("id"));
                user.setCode(rs.getString("code"));
                user.setName(rs.getString("name"));
                user.setPassword(rs.getString("password"));
            }
            // 關閉資源,連接有可能還要使用,不關閉
            BaseDao.close(null,ps,rs);
        }
        return user;
    }
}
package com.qing.dao.user;

import com.qing.dao.BaseDao;
import com.qing.pojo.User;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 用戶Dao實現類
 */
public class UserDaoImpl implements UserDao {

    /**
     * 根據編號獲取用戶
     */
    public User getUserByCode(Connection connection, String code) throws SQLException {
        User user = null;
        if (connection != null) {
            PreparedStatement ps = null;
            ResultSet rs = null;
            String sql = "select * from smbms_user where code=?";
            Object[] params = {code};
            rs = BaseDao.execute(connection, ps, rs, sql, params);
            if (rs.next()) {
                user = new User();
                user.setId(rs.getInt("id"));
                user.setCode(rs.getString("code"));
                user.setName(rs.getString("name"));
                user.setPassword(rs.getString("password"));
            }
            // 關閉資源,連接有可能還要使用,不關閉
            BaseDao.close(null,ps,rs);
        }
        return user;
    }
}

編寫Service層接口和實現類:登錄方法

image.png
pom.xml引入junit

<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>4.13.2</version>
</dependency>
package com.qing.service.user;

import com.qing.pojo.User;

import java.sql.SQLException;

/**
 * 用戶Service接口
 */
public interface UserService {

    /**
     * 用戶登錄
     */
    public User login(String code,String password);
}

package com.qing.service.user;

import com.qing.dao.BaseDao;
import com.qing.dao.user.UserDao;
import com.qing.dao.user.UserDaoImpl;
import com.qing.pojo.User;
import org.junit.Test;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * 用戶Service實現類
 */
public class UserServiceImpl implements UserService {

    // 用戶Dao
    private UserDao userDao;

    public UserServiceImpl() {
        userDao = new UserDaoImpl();
    }

    /**
     * 用戶登錄
     */
    public User login(String code,String password) {
        User user = null;
        Connection connection = BaseDao.getConnection();
        try {
            user = userDao.getLoginUser(connection, code, password);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            BaseDao.close(connection,null,null);
        }
        return user;
    }

    @Test
    public void test() {
        User user = new UserServiceImpl().login("admin", "");
        System.out.println(user != null ? user.getPassword() : "用戶名或密碼錯誤");
    }
}

編寫Servlet層類:登錄Servlet,web.xml注冊Servlet

image.png
編寫公共常量類

package com.qing.util;

/**
 * 公共常量類
 */
public class Constants {
    public static final String USER_SESSION = "userSession"; // 用戶Session
}

package com.qing.servlet.user;

import com.qing.pojo.User;
import com.qing.service.user.UserService;
import com.qing.service.user.UserServiceImpl;
import com.qing.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 {

    // 用戶Service
    private UserService userService;

    public LoginServlet() {
        userService = new UserServiceImpl();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("進入LoginServlet--doGet");
        String code = req.getParameter("code");
        String password = req.getParameter("password");
        // 獲取登錄用戶
        User user = userService.login(code, password);
        // 有此用戶,可以登錄
        if (user != null) {
            // 將用戶信息放到session中
            req.getSession().setAttribute(Constants.USER_SESSION,user);
            // 重定向到主頁
            resp.sendRedirect("jsp/frame.jsp");
        } else {
            // 無此用戶,轉發到登錄頁,返回提示信息
            req.setAttribute("error","用戶名或密碼錯誤");
            req.setAttribute("code",code);
            req.setAttribute("password",password);
            req.getRequestDispatcher("login.jsp").forward(req,resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

<!--注冊登錄Servlet-->
<servlet>
  <servlet-name>LoginServlet</servlet-name>
  <servlet-class>com.qing.servlet.user.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
  <servlet-name>LoginServlet</servlet-name>
  <url-pattern>/login.do</url-pattern>
</servlet-mapping>

測試訪問

image.png
image.png

登錄功能優化

退出系統功能:編寫退出Servlet類,web.xml中注冊

image.png

package com.qing.servlet.user;

import com.qing.pojo.User;
import com.qing.util.Constants;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 退出接口
 */
public class LogoutServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("進入LogoutServlet--doGet");
        // 刪除session中的用戶信息
        req.getSession().removeAttribute(Constants.USER_SESSION);
        // 重定向到登錄頁面
        resp.sendRedirect(req.getContextPath() + "/login.jsp");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

<!--注冊退出Servlet-->
<servlet>
  <servlet-name>LogoutServlet</servlet-name>
  <servlet-class>com.qing.servlet.user.LogoutServlet</servlet-class>
</servlet>
<servlet-mapping>
  <servlet-name>LogoutServlet</servlet-name>
  <url-pattern>/jsp/logout.do</url-pattern>
</servlet-mapping>

登錄攔截功能:編寫登錄驗證過濾器,web.xml中注冊

image.png

package com.qing.filter;

import com.qing.pojo.User;
import com.qing.util.Constants;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登錄驗證過濾器
 */
public class SysFilter implements Filter {
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        User user = (User) request.getSession().getAttribute(Constants.USER_SESSION);
        // 用戶已登錄,繼續執行;用戶未登錄或已退出,重定向到錯誤頁面,程序攔截停止,不繼續執行
        if (user == null) {
            response.sendRedirect(request.getContextPath() + "/error.jsp");
        } else {
            filterChain.doFilter(servletRequest,servletResponse);
        }
    }

    public void destroy() {

    }
}

    <!--登錄驗證過濾器-->
    <filter>
        <filter-name>SysFilter</filter-name>
        <filter-class>com.qing.filter.SysFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>SysFilter</filter-name>
        <url-pattern>/jsp/*</url-pattern>
    </filter-mapping>

密碼修改

image.png

web.xml中設置session過期時間

    <!--設置session過期時間:30分-->
    <session-config>
        <session-timeout>30</session-timeout>
    </session-config>

pom.xml添加fastjson依賴

        <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.76</version>
        </dependency>

編寫前端頁面

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<%@include file="/jsp/common/head.jsp" %>
<div class="right">
    <div class="location">
        <strong>你現在所在的位置是:</strong>
        <span>密碼修改頁面</span>
    </div>
    <div class="providerAdd">
        <form id="userForm" name="userForm" method="post" action="${pageContext.request.contextPath }/jsp/user.do">
            <input type="hidden" name="method" value="savepwd">
            <!--div的class 為error是驗證錯誤,ok是驗證成功-->
            <div class="info">${message}</div>
            <div class="">
                <label for="oldPassword">舊密碼:</label>
                <input type="password" name="oldpassword" id="oldpassword" value="">
                <font color="red"></font>
            </div>
            <div>
                <label for="newPassword">新密碼:</label>
                <input type="password" name="newpassword" id="newpassword" value="">
                <font color="red"></font>
            </div>
            <div>
                <label for="rnewpassword">確認新密碼:</label>
                <input type="password" name="rnewpassword" id="rnewpassword" value="">
                <font color="red"></font>
            </div>
            <div class="providerAddBtn">
                <!--<a href="#">保存</a>-->
                <input type="button" name="save" id="save" value="保存" class="input-button">
            </div>
        </form>
    </div>
</div>
</section>
<%@include file="/jsp/common/foot.jsp" %>
<script type="text/javascript" src="${pageContext.request.contextPath }/js/pwdmodify.js"></script>

編寫后端服務

package com.qing.servlet.user;

import com.alibaba.fastjson.JSON;
import com.mysql.jdbc.StringUtils;
import com.qing.pojo.User;
import com.qing.service.user.UserService;
import com.qing.service.user.UserServiceImpl;
import com.qing.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 {

    // 用戶Service
    private UserService userService;

    public UserServlet() {
        userService = new UserServiceImpl();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("進入UserServlet--doGet");
        String method = req.getParameter("method");
        if ("savepwd".equals(method)) {
            updateOwnPwd(req,resp);
        } else if ("pwdmodify".equals(method)) {
            checkPwd(req,resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    /**
     * 驗證自己的密碼
     * @param req
     * @param resp
     */
    private void checkPwd(HttpServletRequest req, HttpServletResponse resp) {
        Map<String,String> resultMap = new HashMap<String,String>();
        String oldpassword = req.getParameter("oldpassword");
        // 舊密碼輸入為空
        if (StringUtils.isNullOrEmpty(oldpassword)) {
            resultMap.put("result","error");
        } else {
            Object o = req.getSession().getAttribute(Constants.USER_SESSION);
            // 當前用戶session過期,請重新登錄
            if (o == null) {
                resultMap.put("result","sessionerror");
            } else {
                String password = ((User) o).getPassword();
                // 舊密碼正確
                if (oldpassword.equals(password)) {
                    resultMap.put("result", "true");
                    // 舊密碼輸入不正確
                } else {
                    resultMap.put("result", "false");
                }
            }
        }
        try {
            resp.setContentType("application/json");
            PrintWriter writer = resp.getWriter();
            writer.write(JSON.toJSONString(resultMap));
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 修改自己的密碼
     * @param req
     * @param resp
     */
    private void updateOwnPwd(HttpServletRequest req, HttpServletResponse resp) {
        Object o = req.getSession().getAttribute(Constants.USER_SESSION);
        if (o != null && ((User) o).getId() != null) {
            Integer id = ((User) o).getId();
            String password = req.getParameter("newpassword");
            boolean flag = userService.updatePwd(id, password);
            // 修改密碼成功,移除session中的用戶信息
            if (flag) {
                req.getSession().removeAttribute(Constants.USER_SESSION);
                req.setAttribute("message","修改密碼成功,請退出,使用新密碼登錄");
            } else {
                // 修改密碼失敗
                req.setAttribute("message","修改密碼失敗");
            }
        } else {
            // 修改密碼失敗
            req.setAttribute("message","修改密碼失敗");
        }
        // 轉發到修改密碼頁
        try {
            req.getRequestDispatcher("pwdmodify.jsp").forward(req,resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

web.xml中注冊用戶Servlet

    <!--用戶Servlet-->
    <servlet>
        <servlet-name>UserServlet</servlet-name>
        <servlet-class>com.qing.servlet.user.UserServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>UserServlet</servlet-name>
        <url-pattern>/jsp/user.do</url-pattern>
    </servlet-mapping>

用戶管理

image.png
image.png

編寫前端頁面

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<%@include file="/jsp/common/head.jsp" %>
<div class="right">
    <div class="location">
        <strong>你現在所在的位置是:</strong>
        <span>用戶管理頁面</span>
    </div>
    <div class="search">
        <form method="get" action="${pageContext.request.contextPath }/jsp/user.do">
            <input name="method" value="query" class="input-text" type="hidden">
            <span>用戶名:</span>
            <input name="queryname" class="input-text" type="text" value="${queryname }">

            <span>用戶角色:</span>
            <select name="queryUserRole">
                <c:if test="${roleList != null }">
                    <option value="">--請選擇--</option>
                    <c:forEach var="role" items="${roleList}">
                        <option
                                <c:if test="${role.id == queryUserRole }">selected="selected"</c:if>
                                value="${role.id}">${role.name}</option>
                    </c:forEach>
                </c:if>
            </select>

            <input type="hidden" name="pageIndex" value="1"/>
            <input value="查 詢" type="submit" id="searchbutton">
            <a href="${pageContext.request.contextPath}/jsp/useradd.jsp">添加用戶</a>
        </form>
    </div>
    <!--用戶-->
    <table class="providerTable" cellpadding="0" cellspacing="0">
        <tr class="firstTr">
            <th width="10%">用戶編碼</th>
            <th width="20%">用戶名稱</th>
            <th width="10%">性別</th>
            <th width="10%">年齡</th>
            <th width="10%">電話</th>
            <th width="10%">用戶角色</th>
            <th width="30%">操作</th>
        </tr>
        <c:forEach var="user" items="${userList }" varStatus="status">
            <tr>
                <td>
                    <span>${user.code }</span>
                </td>
                <td>
                    <span>${user.name }</span>
                </td>
                <td>
							<span>
								<c:if test="${user.gender==1}">男</c:if>
								<c:if test="${user.gender==2}">女</c:if>
							</span>
                </td>
                <td>
                    <span>${user.age}</span>
                </td>
                <td>
                    <span>${user.phone}</span>
                </td>
                <td>
                    <span>${user.roleName}</span>
                </td>
                <td>
                    <span><a class="viewUser" href="javascript:;" userid=${user.id } username=${user.name }><img
                            src="${pageContext.request.contextPath }/images/read.png" alt="查看" title="查看"/></a></span>
                    <span><a class="modifyUser" href="javascript:;" userid=${user.id } username=${user.name }><img
                            src="${pageContext.request.contextPath }/images/xiugai.png" alt="修改" title="修改"/></a></span>
                    <span><a class="deleteUser" href="javascript:;" userid=${user.id } username=${user.name }><img
                            src="${pageContext.request.contextPath }/images/schu.png" alt="刪除" title="刪除"/></a></span>
                </td>
            </tr>
        </c:forEach>
    </table>
    <input type="hidden" id="totalPageCount" value="${totalPageCount}"/>
    <c:import url="rollpage.jsp">
        <c:param name="totalCount" value="${totalCount}"/>
        <c:param name="currentPageNo" value="${currentPageNo}"/>
        <c:param name="totalPageCount" value="${totalPageCount}"/>
    </c:import>
</div>
</section>

<!--點擊刪除按鈕后彈出的頁面-->
<div class="zhezhao"></div>
<div class="remove" id="removeUse">
    <div class="removerChid">
        <h2>提示</h2>
        <div class="removeMain">
            <p>你確定要刪除該用戶嗎?</p>
            <a href="#" id="yes">確定</a>
            <a href="#" id="no">取消</a>
        </div>
    </div>
</div>

<%@include file="/jsp/common/foot.jsp" %>
<script type="text/javascript" src="${pageContext.request.contextPath }/js/userlist.js"></script>

編寫分頁工具類

package com.qing.util;

public class PageSupport {
    //當前頁碼-來自於用戶輸入
    private int currentPageNo = 1;

    //總數量(表)
    private int totalCount = 0;

    //頁面容量
    private int pageSize = 0;

    //總頁數-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;
            //設置總頁數
            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;
        }
    }

}

編寫后端服務

package com.qing.servlet.user;

import com.alibaba.fastjson.JSON;
import com.mysql.jdbc.StringUtils;
import com.qing.pojo.Role;
import com.qing.pojo.User;
import com.qing.service.user.RoleService;
import com.qing.service.user.RoleServiceImpl;
import com.qing.service.user.UserService;
import com.qing.service.user.UserServiceImpl;
import com.qing.util.Constants;
import com.qing.util.PageSupport;

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.List;
import java.util.Map;

/**
 * 用戶接口
 */
public class UserServlet extends HttpServlet {

    // 用戶Service
    private UserService userService;
    // 角色Service
    private RoleService roleService;

    public UserServlet() {
        userService = new UserServiceImpl();
        roleService = new RoleServiceImpl();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("進入UserServlet--doGet");
        String method = req.getParameter("method");
        if ("savepwd".equals(method)) {
            updateOwnPwd(req,resp);
        } else if ("pwdmodify".equals(method)) {
            checkPwd(req,resp);
        } else if ("query".equals(method)) {
            query(req,resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    /**
     * 驗證自己的密碼
     * @param req
     * @param resp
     */
    private void checkPwd(HttpServletRequest req, HttpServletResponse resp) {
        Map<String,String> resultMap = new HashMap<String,String>();
        String oldpassword = req.getParameter("oldpassword");
        // 舊密碼輸入為空
        if (StringUtils.isNullOrEmpty(oldpassword)) {
            resultMap.put("result","error");
        } else {
            Object o = req.getSession().getAttribute(Constants.USER_SESSION);
            // 當前用戶session過期,請重新登錄
            if (o == null) {
                resultMap.put("result","sessionerror");
            } else {
                String password = ((User) o).getPassword();
                // 舊密碼正確
                if (oldpassword.equals(password)) {
                    resultMap.put("result", "true");
                    // 舊密碼輸入不正確
                } else {
                    resultMap.put("result", "false");
                }
            }
        }
        try {
            resp.setContentType("application/json");
            PrintWriter writer = resp.getWriter();
            writer.write(JSON.toJSONString(resultMap));
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 修改自己的密碼
     * @param req
     * @param resp
     */
    private void updateOwnPwd(HttpServletRequest req, HttpServletResponse resp) {
        Object o = req.getSession().getAttribute(Constants.USER_SESSION);
        if (o != null && ((User) o).getId() != null) {
            Integer id = ((User) o).getId();
            String password = req.getParameter("newpassword");
            boolean flag = userService.updatePwd(id, password);
            // 修改密碼成功,移除session中的用戶信息
            if (flag) {
                req.getSession().removeAttribute(Constants.USER_SESSION);
                req.setAttribute("message","修改密碼成功,請退出,使用新密碼登錄");
            } else {
                // 修改密碼失敗
                req.setAttribute("message","修改密碼失敗");
            }
        } else {
            // 修改密碼失敗
            req.setAttribute("message","修改密碼失敗");
        }
        // 轉發到修改密碼頁
        try {
            req.getRequestDispatcher("pwdmodify.jsp").forward(req,resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 用戶列表
     * @param req
     * @param resp
     */
    private void query(HttpServletRequest req, HttpServletResponse resp) {
        // 用戶列表
        String queryname = req.getParameter("queryname");
        if (! StringUtils.isNullOrEmpty(queryname)) {
            req.setAttribute("queryname",queryname);
        }
        String queryUserRole = req.getParameter("queryUserRole");
        if (! StringUtils.isNullOrEmpty(queryUserRole)) {
            req.setAttribute("queryUserRole",queryUserRole);
        }
        String pageIndex = req.getParameter("pageIndex");
        if (StringUtils.isNullOrEmpty(pageIndex)) {
            pageIndex = "1";
        }
        int currentPageNo = Integer.parseInt(pageIndex);
        int pageSize = 2;
        List<User> userList = userService.list(queryname, queryUserRole, currentPageNo, pageSize);
        req.setAttribute("userList",userList);
        // 用戶數量
        int totalCount = userService.count(queryname, queryUserRole);
        // 分頁
        PageSupport pageSupport = new PageSupport();
        pageSupport.setCurrentPageNo(currentPageNo);
        pageSupport.setPageSize(pageSize);
        pageSupport.setTotalCount(totalCount);
        pageSupport.setTotalPageCountByRs();
        int totalPageCount = pageSupport.getTotalPageCount();
        req.setAttribute("totalCount", totalCount);
        req.setAttribute("currentPageNo", currentPageNo);
        req.setAttribute("totalPageCount", totalPageCount);

        // 角色列表
        List<Role> roleList = roleService.list();
        req.setAttribute("roleList",roleList);

        // 轉發到用戶列表頁
        try {
            req.getRequestDispatcher("userlist.jsp").forward(req,resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM