- 功能设计
- 数据库设计
- 项目搭建
- 创建MavenWeb项目
- 删除pom文件中无用的配置
- web.
- 创建java和resources
- 配置Tomcat
- 测试项目是否运行成功
- 在gitee创建远程仓库并关联
- pom.
- 创建项目包结构
- 编写实体类:ORM映射:表-类映射
- idea连接数据库
- 编写实体类
- 编写基础公共类
- 数据库配置文件 db.properties
- 编写数据库的公共类:获取数据库连接,释放资源,公共查询,公共增删改
- 编写字符编码过滤器,web.
- 导入静态资源
- 登录功能实现
- 编写前端页面
- 设置欢迎页面:web.
- 编写Dao层接口和实现类:根据编号获取用户方法
- 编写Service层接口和实现类:登录方法
- 编写Servlet层类:登录Servlet,web.
- 测试访问
- 登录功能优化
- 退出系统功能:编写退出Servlet类,web.
- 登录拦截功能:编写登录验证过滤器,web.
- 密码修改
- web.
- pom.
- 编写前端页面
- 编写后端服务
- web.
- 用户管理
- 编写前端页面
- 编写分页工具类
- 编写后端服务
功能设计

数据库设计

项目搭建
创建MavenWeb项目


删除pom文件中无用的配置

<?<?
<?创建java和resources

配置Tomcat


测试项目是否运行成功


在gitee创建远程仓库并关联
创建远程仓库
创建本地仓库
Administrator@L87Y12K91TH8M2R MINGW64 /d/code/smbms$ git initInitialized empty Git repository in D:/code/smbms/.git/Administrator@L87Y12K91TH8M2R MINGW64 /d/code/smbms (main)$ ll -atotal 18drwxr-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.关联远程仓库,并拉取远程仓库文件
D:\code\smbms>git remote add origin git@gitee.com:wl3pbzhyq/smbms.gitD:\code\smbms>git pull origin masterremote: 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配置忽略文件
# targettarget/# idea.idea/*.iml
提交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 directoryD:\code\smbms>git statusOn branch mainChanges to be committed: (use "git restore --staged <file>..." to unstage) modified: .gitignore new file: pom.创建项目包结构

编写实体类:ORM映射:表-类映射
idea连接数据库

编写实体类
/*Navicat MySQL Data TransferSource Server : localSource Server Version : 50729Source Host : localhost:3306Source Database : smbmsTarget Server Type : MYSQLTarget Server Version : 50729File Encoding : 65001Date: 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-- ----------------------------
编写基础公共类
数据库配置文件 db.properties

driver=com.mysql.jdbc.Driverurl=jdbc:mysql://localhost:3306/smbms?useUnicode=true&characterEncoding=utf8&useSSL=falseusername=rootpassword=123456编写数据库的公共类:获取数据库连接,释放资源,公共查询,公共增删改

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; }}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() { }}
<?
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() { }}<?导入静态资源

登录功能实现

编写前端页面

<%@ 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 ><section > <header > <h1>超市订单管理系统</h1> </header> <section > <form action="${pageContext.request.contextPath}/login.do" method="post" name="actionForm" id="actionForm"> <div >${error}</div> <div > <label for="code">用户名:</label> <input type="text" id="code" name="code" placeholder="请输入用户名" required/> </div> <div > <label for="password">密码:</label> <input type="password" id="password" name="password" placeholder="请输入密码" required/> </div> <div > <input type="submit" value="登录"/> <input type="reset" value="重置"/> </div> </form></section></section></body></html>
编写Dao层接口和实现类:根据编号获取用户方法

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层接口和实现类:登录方法

pom.
<!-- 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() : "用户名或密码错误"); }}
编写公共常量类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>
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>测试访问


登录功能优化
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>
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>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>
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>密码修改

<!-- 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 > <div > <strong>你现在所在的位置是:</strong> <span>密码修改页面</span> </div> <div > <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 >${message}</div> <div > <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 > <!--<a href="#">保存</a>--> <input type="button" name="save" id="save" value="保存" > </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(); } }}用户管理


编写前端页面
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %><%@include file="/jsp/common/head.jsp" %><div > <div > <strong>你现在所在的位置是:</strong> <span>用户管理页面</span> </div> <div > <form method="get" action="${pageContext.request.contextPath }/jsp/user.do"> <input name="method" value="query" type="hidden"> <span>用户名:</span> <input name="queryname" 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 cellpadding="0" cellspacing="0"> <tr > <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 href="javascript:;" userid=${user.id } username=${user.name }><img src="${pageContext.request.contextPath }/images/read.png" alt="查看" title="查看"/></a></span> <span><a href="javascript:;" userid=${user.id } username=${user.name }><img src="${pageContext.request.contextPath }/images/xiugai.png" alt="修改" title="修改"/></a></span> <span><a 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 ></div><div id="removeUse"> <div > <h2>提示</h2> <div > <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(); } }}原文转载:http://www.shaoqun.com/a/788312.html
auction:https://www.ikjzd.com/w/2311
中国邮政邮乐网:https://www.ikjzd.com/w/1776
智赢:https://www.ikjzd.com/w/1511
萌店:https://www.ikjzd.com/w/1538
目录功能设计数据库设计项目搭建创建MavenWeb项目删除pom文件中无用的配置web.创建java和resources配置Tomcat测试项目是否运行成功在gitee创建远程仓库并关联pom.创建项目包结构编写实体类:ORM映射:表-类映射idea连接数据库编写实体类编写基础公共类数据库配置文件db.properties编写数据库的公共类:获取数据库连接,释放资源,公共查询,公共增删改编写字符编
Lengow:https://www.ikjzd.com/w/404
鹰熊汇:https://www.ikjzd.com/w/1572
康超:https://www.ikjzd.com/w/1824
SageMailer:https://www.ikjzd.com/w/2448
蜂鸟跨境电商:https://www.ikjzd.com/w/2598
e淘网:https://www.ikjzd.com/w/1698
tchibo:https://www.ikjzd.com/w/1928
口述:我例假委身男友换来噩梦一场:http://lady.shaoqun.com/m/a/108365.html
口述:我把"哥们"变成了情人:http://lady.shaoqun.com/m/a/272381.html
我的家教老师让我和她 冲进浴室把家教老师摁在地上猛烈撞击:http://lady.shaoqun.com/m/a/274710.html
口述:老公让我养育他的代孕儿子:http://lady.shaoqun.com/a/273407.html
男友笑我胸部太小 一亲热我就自卑:http://lady.shaoqun.com/a/271947.html
寂寞女教师 那晚疯狂要了我:http://www.30bags.com/a/255153.html
我高中陪女同学的那个夜晚 口述我和女同学的一段恋情:http://www.30bags.com/m/a/250173.html
老公性无能我找小叔求安慰:http://www.30bags.com/m/a/251334.html
当美女的我碰到无能的多金男:http://www.30bags.com/m/a/253298.html
上司偷亲我的脚 还说把我当女儿:http://www.30bags.com/m/a/252649.html
没有评论:
发表评论