功能设计

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:codesmbms>git remote add origin git@gitee.com:wl3pbzhyq/smbms.git

D:codesmbms>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:codesmbms>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:codesmbms>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:codesmbms>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:codesmbms>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:codesmbms>

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();
        }
    }
}

内容来源于网络如有侵权请私信删除
你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!