系列文章

JavaWeb 开发 01 —— 基本概念、Web服务器、HTTP、Maven

JavaWeb 开发 02 —— ServletContext、读取资源、下载文件、重定向和请求转发

JavaWeb 开发 03 —— Cookie 和 Session

JavaWeb 开发 04 —— JSP(原理、语法、指令、内置对象、JSP标签、JSTP标签)、JavaBean、MVC

JavaWeb 开发 05 —— 过滤器、监听器

JavaWeb 开发 06 —— smbms项目实践

文章目录

  • 系列文章
  • 实践:SMBMS项目
  • 项目搭建准备工作
  • 登录功能
  • 注销拦截
  • 密码修改
  • 用户管理
    • 1、获取用户数量
    • 2、获取用户列表
    • 3、获取角色列表
    • 4、添加用户
  • 总结

实践:SMBMS项目

SMBMS是超市订单管理系统的英文缩写。

SMBMS项目SQL代码:https://download.csdn.net/download/qq_39763246/15352854

百度网盘:https://pan.baidu.com/s/16fNpMkGeXZud-U58Z5y67g 提取码: q3eq

项目架构:

数据库架构:

项目搭建准备工作

搭建项目时要先考虑是否使用Maven,如果用Maven则需要写依赖,如果不用Maven则要手动导入Jar包。这里选择使用Maven。

1、搭建一个Maven Web项目

2、配置Tomcat

3、启动Tomcat,测试项目能否跑起来

4、导入项目中会遇到的jar包

<dependencies><!-- Servlet依赖 --><dependency><groupId>javax.servlet</groupId><artifactId>javax.servlet-api</artifactId><version>4.0.1</version><scope>provided</scope></dependency><!-- JSP依赖 --><dependency><groupId>javax.servlet.jsp</groupId><artifactId>javax.servlet.jsp-api</artifactId><version>2.3.3</version><scope>provided</scope></dependency><!-- JSTL表达式依赖 --><dependency><groupId>javax.servlet</groupId><artifactId>jstl</artifactId><version>1.2</version></dependency><!-- standard标签库 --><dependency><groupId>taglibs</groupId><artifactId>standard</artifactId><version>1.1.2</version></dependency><!-- 连接数据库 --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.47</version></dependency><!-- 代码测试 --><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version></dependency><!-- 导入阿里巴巴的fastjson, 处理json转化 --><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.62</version></dependency>
</dependencies>

5、创建项目包结构

6、编写实体类

ORM映射:数据库 表—Java 类映射

Bill.java

package com.zcy.pojo;import java.math.BigDecimal;
import java.util.Date;public class Bill {private Integer id;   //idprivate String billCode; //账单编码private String productName; //商品名称private String productDesc; //商品描述private String productUnit; //商品单位private BigDecimal productCount; //商品数量private BigDecimal totalPrice; //总金额private Integer isPayment; //是否支付private Integer providerId; //供应商IDprivate Integer createdBy; //创建者private Date creationDate; //创建时间private Integer modifyBy; //更新者private Date modifyDate;//更新时间private String providerName;//供应商名称public String getProviderName() {return providerName;}public void setProviderName(String providerName) {this.providerName = providerName;}public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getBillCode() {return billCode;}public void setBillCode(String billCode) {this.billCode = billCode;}public String getProductName() {return productName;}public void setProductName(String productName) {this.productName = productName;}public String getProductDesc() {return productDesc;}public void setProductDesc(String productDesc) {this.productDesc = productDesc;}public String getProductUnit() {return productUnit;}public void setProductUnit(String productUnit) {this.productUnit = productUnit;}public BigDecimal getProductCount() {return productCount;}public void setProductCount(BigDecimal productCount) {this.productCount = productCount;}public BigDecimal getTotalPrice() {return totalPrice;}public void setTotalPrice(BigDecimal totalPrice) {this.totalPrice = totalPrice;}public Integer getIsPayment() {return isPayment;}public void setIsPayment(Integer isPayment) {this.isPayment = isPayment;}public Integer getProviderId() {return providerId;}public void setProviderId(Integer providerId) {this.providerId = providerId;}public Integer getCreatedBy() {return createdBy;}public void setCreatedBy(Integer createdBy) {this.createdBy = createdBy;}public Date getCreationDate() {return creationDate;}public void setCreationDate(Date creationDate) {this.creationDate = creationDate;}public Integer getModifyBy() {return modifyBy;}public void setModifyBy(Integer modifyBy) {this.modifyBy = modifyBy;}public Date getModifyDate() {return modifyDate;}public void setModifyDate(Date modifyDate) {this.modifyDate = modifyDate;}
}

Provider.java

package com.zcy.pojo;import java.util.Date;public class Provider {private Integer id;   //idprivate String proCode; //供应商编码private String proName; //供应商名称private String proDesc; //供应商描述private String proContact; //供应商联系人private String proPhone; //供应商电话private String proAddress; //供应商地址private String proFax; //供应商传真private Integer createdBy; //创建者private Date creationDate; //创建时间private Integer modifyBy; //更新者private Date modifyDate;//更新时间public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getProCode() {return proCode;}public void setProCode(String proCode) {this.proCode = proCode;}public String getProName() {return proName;}public void setProName(String proName) {this.proName = proName;}public String getProDesc() {return proDesc;}public void setProDesc(String proDesc) {this.proDesc = proDesc;}public String getProContact() {return proContact;}public void setProContact(String proContact) {this.proContact = proContact;}public String getProPhone() {return proPhone;}public void setProPhone(String proPhone) {this.proPhone = proPhone;}public String getProAddress() {return proAddress;}public void setProAddress(String proAddress) {this.proAddress = proAddress;}public String getProFax() {return proFax;}public void setProFax(String proFax) {this.proFax = proFax;}public Integer getCreatedBy() {return createdBy;}public void setCreatedBy(Integer createdBy) {this.createdBy = createdBy;}public Date getCreationDate() {return creationDate;}public void setCreationDate(Date creationDate) {this.creationDate = creationDate;}public Integer getModifyBy() {return modifyBy;}public void setModifyBy(Integer modifyBy) {this.modifyBy = modifyBy;}public Date getModifyDate() {return modifyDate;}public void setModifyDate(Date modifyDate) {this.modifyDate = modifyDate;}
}

Role.java

package com.zcy.pojo;import java.util.Date;public class Role {private Integer id;   //idprivate String roleCode; //角色编码private String roleName; //角色名称private Integer createdBy; //创建者private Date creationDate; //创建时间private Integer modifyBy; //更新者private Date modifyDate;//更新时间public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getRoleCode() {return roleCode;}public void setRoleCode(String roleCode) {this.roleCode = roleCode;}public String getRoleName() {return roleName;}public void setRoleName(String roleName) {this.roleName = roleName;}public Integer getCreatedBy() {return createdBy;}public void setCreatedBy(Integer createdBy) {this.createdBy = createdBy;}public Date getCreationDate() {return creationDate;}public void setCreationDate(Date creationDate) {this.creationDate = creationDate;}public Integer getModifyBy() {return modifyBy;}public void setModifyBy(Integer modifyBy) {this.modifyBy = modifyBy;}public Date getModifyDate() {return modifyDate;}public void setModifyDate(Date modifyDate) {this.modifyDate = modifyDate;}
}

User.java

package com.zcy.pojo;import java.util.Date;public class User {private Integer id; //idprivate String userCode; //用户编码private String userName; //用户名称private String userPassword; //用户密码private Integer gender;  //性别private Date birthday;  //出生日期private String phone;   //电话private String address; //地址private Integer userRole;    //用户角色private Integer createdBy;   //创建者private Date creationDate; //创建时间private Integer modifyBy;     //更新者private Date modifyDate;   //更新时间private Integer age;//年龄private String userRoleName;    //用户角色名称public String getUserRoleName() {return userRoleName;}public void setUserRoleName(String userRoleName) {this.userRoleName = userRoleName;}public Integer getAge() {/*long time = System.currentTimeMillis()-birthday.getTime();Integer age = Long.valueOf(time/365/24/60/60/1000).IntegerValue();*/Date date = new Date();Integer age = date.getYear()-birthday.getYear();return age;}public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getUserCode() {return userCode;}public void setUserCode(String userCode) {this.userCode = userCode;}public String getUserName() {return userName;}public void setUserName(String userName) {this.userName = userName;}public String getUserPassword() {return userPassword;}public void setUserPassword(String userPassword) {this.userPassword = userPassword;}public Integer getGender() {return gender;}public void setGender(Integer gender) {this.gender = gender;}public Date getBirthday() {return birthday;}public void setBirthday(Date birthday) {this.birthday = birthday;}public String getPhone() {return phone;}public void setPhone(String phone) {this.phone = phone;}public String getAddress() {return address;}public void setAddress(String address) {this.address = address;}public Integer getUserRole() {return userRole;}public void setUserRole(Integer userRole) {this.userRole = userRole;}public Integer getCreatedBy() {return createdBy;}public void setCreatedBy(Integer createdBy) {this.createdBy = createdBy;}public Date getCreationDate() {return creationDate;}public void setCreationDate(Date creationDate) {this.creationDate = creationDate;}public Integer getModifyBy() {return modifyBy;}public void setModifyBy(Integer modifyBy) {this.modifyBy = modifyBy;}public Date getModifyDate() {return modifyDate;}public void setModifyDate(Date modifyDate) {this.modifyDate = modifyDate;}
}

7、编写基础公共类

  1. 数据库配置文件(resources目录下db.properties)

    driver=com.mysql.jdbc.Driver
    url=jdbc:mysql://localhost:3306/smbms?useUnicode=true&characterEncoding=utf8&useSSL=false
    username=root
    password=123456
    
  1. 数据库公共类(java目录下dao的BaseDao.java)
    数据库参考我另一篇博客:数据库 —— Java操作MySQL

    package com.zcy.dao;import javax.servlet.jsp.jstl.sql.Result;
    import javax.servlet.jsp.jstl.sql.ResultSupport;
    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);} catch (IOException e) {e.printStackTrace();}driver = properties.getProperty("driver");url = properties.getProperty("url");userName = properties.getProperty("username");password = properties.getProperty("password");}//获取数据库连接public static Connection getConnection(){Connection connection = null;try {Class.forName(driver);connection = DriverManager.getConnection(url, userName, password);} catch (Exception e) {e.printStackTrace();}return connection;}//查询公共方法public static ResultSet execute(Connection connection,PreparedStatement preparedStatement,Object[] param) throws SQLException {//这里i+1是因为PreparedStatement 用的占位符是从1开始for (int i = 0; i < param.length; i++) {preparedStatement.setObject(i+1, param[i]);}ResultSet resultSet = preparedStatement.executeQuery();return resultSet;}//更新公共方法public static int update(Connection connection, PreparedStatement preparedStatement,Object[] param) throws SQLException {for (int i = 0; i < param.length; i++) {preparedStatement.setObject(i+1, param[i]);}int updateRows = preparedStatement.executeUpdate();return updateRows;}public static boolean closeResource(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet){boolean flag = true;if (resultSet != null){try {resultSet.close();//让JVM回收,GC 垃圾回收机制resultSet = null;} catch (SQLException e) {e.printStackTrace();flag = false;}}if (preparedStatement != null){try {preparedStatement.close();//让JVM回收,GC 垃圾回收机制preparedStatement = null;} catch (SQLException e) {e.printStackTrace();flag = false;}}if (connection != null){try {connection.close();//让JVM回收,GC 垃圾回收机制connection = null;} catch (SQLException e) {e.printStackTrace();flag = false;}}return flag;}
    }
    
  1. 编写过滤器

    package com.zcy.filter;import javax.servlet.*;
    import java.io.IOException;public class CharacterEncodingFilter implements Filter {public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {request.setCharacterEncoding("utf-8");response.setCharacterEncoding("utf-8");response.setContentType("text/html;charset=utf-8");chain.doFilter(request, response);}
    }
    
  2. web.xml中注册

    <!-- 过滤所有请求,处理中文乱码 -->
    <filter><filter-name>CharacterEncodingFilter</filter-name><filter-class>com.zcy.filter.CharacterEncodingFilter</filter-class>
    </filter>
    <filter-mapping><filter-name>CharacterEncodingFilter</filter-name><url-pattern>/*</url-pattern>
    </filter-mapping>
    

8、导入静态资源,放在webapp目录下。

下载链接: CSDN

百度网盘:https://pan.baidu.com/s/16fNpMkGeXZud-U58Z5y67g 提取码: q3eq

登录功能

1、编写前端页面(login.jsp)

login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<head lang="en"><meta charset="UTF-8"><title>系统登录 - 超市订单管理系统</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"  name="actionForm" id="actionForm"  method="post" ><div class="info">${error }</div><div class="inputbox"><label>用户名:</label><input type="text" class="input-text" id="userCode" name="userCode" placeholder="请输入用户名" required/></div>  <div class="inputbox"><label>密码:</label><input type="password" id="userPassword" name="userPassword" placeholder="请输入密码" required/></div>   <div class="subBtn"><input type="submit" value="登录"/><input type="reset" value="重置"/></div>  </form></section></section>
</body>
</html>

2、设置欢迎页,web.xml中设置

<!-- 设置欢迎页(首页)  -->
<welcome-file-list><welcome-file>login.jsp</welcome-file>
</welcome-file-list>

3、编写Dao层 得到用户登录的接口

package com.zcy.dao.user;
import com.zcy.pojo.User;
import java.sql.Connection;
import java.sql.SQLException;//操作用户的Dao
public interface UserDao {/*** 获得想要登录的用户* @param connection 连接参数* @param userCode 用户账号* @return 返回想登录的用户对象,为null则没有该用户*/public User getLoginUser(Connection connection, String userCode) throws SQLException;
}

4、编写Dao 接口的实现类

package com.zcy.dao.user;import com.zcy.dao.BaseDao;
import com.zcy.pojo.User;import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;public class UserDaoImpl implements UserDao {/**** @param connection 连接参数* @param userCode 用户账号* @return 返回想登录的用户对象,为null则没有该用户* @throws SQLException*/public User getLoginUser(Connection connection, String userCode) throws SQLException {ResultSet resultSet = null;User user = null;if (connection != null){String sql = "select * from smbms_user where userCode = ?";Object[] params = {userCode};resultSet = BaseDao.execute(connection, sql, params);if (resultSet.next()){user = new User();user.setId(resultSet.getInt("id"));user.setUserCode(resultSet.getString("userCode"));user.setUserName(resultSet.getString("userName"));user.setUserPassword(resultSet.getString("userPassword"));user.setGender(resultSet.getInt("gender"));user.setBirthday(resultSet.getDate("birthday"));user.setPhone(resultSet.getString("phone"));user.setAddress(resultSet.getString("address"));user.setUserRole(resultSet.getInt("userRole"));user.setCreatedBy(resultSet.getInt("createdBy"));user.setCreationDate(resultSet.getTimestamp("creationDate"));user.setModifyBy(resultSet.getInt("modifyBy"));user.setModifyDate(resultSet.getTimestamp("modifyDate"));}BaseDao.closeResource(null, null, resultSet);}return user;}
}

5、业务层接口

package com.zcy.service.user;
import com.zcy.pojo.User;
public interface UserService {/*** 用户登录* @param userCode 用户编号* @param password 用户密码* @return 存在该用户,则返回用户对象,不存在则为null*/public User login(String userCode, String password);
}

6、业务层实现类

package com.zcy.service.user;import com.zcy.dao.BaseDao;
import com.zcy.dao.user.UserDao;
import com.zcy.dao.user.UserDaoImpl;
import com.zcy.pojo.User;
import org.junit.Test;import java.sql.Connection;
import java.sql.SQLException;public class UserServiceImpl implements UserService {//业务层都会调用Dao层,所有我们要先引入Dao层private UserDao userDao;/*** 实例化Dao层的对象*/public UserServiceImpl(){userDao = new UserDaoImpl();}/*** 在这个业务层调用Dao层的具体数据库操作,获得要登录的用户对象* @param userCode 用户编码* @param password 用户密码* @return 要登录的用户对象,为null则没有该用户*/public User login(String userCode, String password) {Connection connection = null;User user = null;try {connection = BaseDao.getConnection();//在业务层调用对应的具体数据库操作,这里就是获取要登录的用户对象user = userDao.getLoginUser(connection, userCode);} catch (SQLException e) {e.printStackTrace();}finally {BaseDao.closeResource(connection, null, null);}if (user == null || !user.getUserPassword().equals(password))return null;elsereturn user;}/*** 用于测试,可直接删除*/@Testpublic void test(){UserServiceImpl userService = new UserServiceImpl();User admin = userService.login("admin", "abcdefg");System.out.println(admin.getUserPassword());}
}

7、编写Servlet

package com.zcy.servlet.user;import com.zcy.pojo.User;
import com.zcy.service.UserService;
import com.zcy.service.UserServiceImpl;
import com.zcy.util.Constants;import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;public class LoginServlet extends HttpServlet {//Servlet:控制层,调用业务层代码@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {System.out.println("LoginServlet————Start....");//获取用户编码和密码String userCode = req.getParameter("userCode");String userPassword = req.getParameter("userPassword");UserService userService = new UserServiceImpl();User user = userService.login(userCode, userPassword);if (user!=null){//有此人,登录成功//将用户信息放在session中req.getSession().setAttribute(Constants.USER_SESSION, user);//使用重定向到主页面resp.sendRedirect("jsp/frame.jsp");}else {//没有此人或密码错误,返回登录界面并给出提示req.setAttribute("error", "用户名或密码错误");//这里之所以用转发而不是重定向,是因为前端是调用request里的error变量//转发可以将请求转发出去,保证了error的存活req.getRequestDispatcher("login.jsp").forward(req, resp);}}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doGet(req, resp);}
}

之所以能够提示用户名或密码错误,是因为login.jsp中引用了error变量

在页面头部中,也引用了session中的用户信息

8、注册Servlet

<servlet><servlet-name>LoginServlet</servlet-name><servlet-class>com.zcy.servlet.user.LoginServlet</servlet-class>
</servlet>
<servlet-mapping><servlet-name>LoginServlet</servlet-name><url-pattern>/login.do</url-pattern>
</servlet-mapping>

注销拦截

1、注销功能:移除用户session并返回登录界面

LogoutServlet.java

package com.zcy.servlet.user;import com.zcy.util.Constants;import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;public class LogoutServlet extends HttpServlet {@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doGet(req,resp);}@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//注销:移除用户sessionreq.getSession().removeAttribute(Constants.USER_SESSION);resp.sendRedirect(req.getContextPath()+"/login.jsp");}
}

注册Servlet

<servlet><servlet-name>LogoutServlet</servlet-name><servlet-class>com.zcy.servlet.user.LogoutServlet</servlet-class>
</servlet>
<servlet-mapping><servlet-name>LogoutServlet</servlet-name><url-pattern>/jsp/logout.do</url-pattern>
</servlet-mapping>

2、登录拦截

package com.zcy.filter;import com.sun.deploy.net.HttpResponse;
import com.zcy.pojo.User;
import com.zcy.util.Constants;import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;public class LoginFilter implements Filter {public void init(FilterConfig filterConfig) throws ServletException {}public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {HttpServletRequest request = (HttpServletRequest)req;HttpServletResponse response = (HttpServletResponse) resp;//获得已登录的用户User user = (User) request.getSession().getAttribute(Constants.USER_SESSION);//如果用户没有登录或者已经注销,则再想进入主页面就会被拦截,然后重定向if(user == null)response.sendRedirect(request.getContextPath()+"/error.jsp");elsechain.doFilter(req, resp);}public void destroy() {}
}

注册

<!-- 过滤未登录用户  -->
<filter><filter-name>LoginFilter</filter-name><filter-class>com.zcy.filter.LoginFilter</filter-class>
</filter>
<filter-mapping><filter-name>LoginFilter</filter-name><url-pattern>/jsp/*</url-pattern>
</filter-mapping>

密码修改


1、UserDao.java中添加方法

/**
* 修改用户密码
* @param connection 连接参数
* @param id 用户ID号
* @param password 用户新密码
* @return 返回修改的行数(1表示成功 0表示失败)
* @throws SQLException
*/
public int updatePassword(Connection connection, int id, String password) throws SQLException;

2、UserDaoImpl.java中添加方法

/**
*
* @param connection 连接参数
* @param id 用户ID号
* @param password 用户新密码
* @return 返回修改的行数(1表示成功 0表示失败)
* @throws SQLException
*/
public int updatePassword(Connection connection, int id, String password) throws SQLException {PreparedStatement preparedStatement = null;int updateRows = 0;if (connection != null){String sql = "update smbms_user set userPassword = ? where id = ?";preparedStatement = connection.prepareStatement(sql);Object[] params = {password, id};updateRows = BaseDao.update(connection, preparedStatement, params);BaseDao.closeResource(null, preparedStatement, null);}return updateRows;
}

3、UserServiceImp.java中添加方法

/**
* 根据用户id和密码修改用户密码
* @param id 用户id
* @param password 用户密码
* @return 返回true 或 false
*/
public boolean updatePassword(int id, String password) {Connection connection = null;boolean flag = false;try {connection = BaseDao.getConnection();if (userDao.updatePassword(connection, id, password) > 0)flag = true;} catch (SQLException e) {e.printStackTrace();}finally {BaseDao.closeResource(connection, null, null);}return flag;
}

4、UserServlet.java

package com.zcy.servlet.user;import com.alibaba.fastjson.JSONArray;
import com.mysql.jdbc.StringUtils;
import com.zcy.pojo.User;
import com.zcy.service.UserService;
import com.zcy.service.UserServiceImpl;
import com.zcy.util.Constants;import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;public class UserServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//从前端获取参数,根据参数执行对应方法String method = req.getParameter("method");if (method.equals("savepwd"))updatePassword(req,resp);else if (method.equals("pwdmodify"))pwdModify(req, resp);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doGet(req, resp);}//更新密码public void updatePassword(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {Object o = req.getSession().getAttribute(Constants.USER_SESSION);String newPassword = req.getParameter("newpassword");boolean flag = false;if (o != null && !StringUtils.isEmptyOrWhitespaceOnly(newPassword)){UserService userService = new UserServiceImpl();flag = userService.updatePassword(((User)o).getId(), newPassword);if (flag){//因为前端pwdmodify.jsp中留有一个message的位置,可以显示数据req.setAttribute("message", "密码修改成功,请重新用新密码登录");//移除用户Session,相当于自动注销req.getSession().removeAttribute(Constants.USER_SESSION);}elsereq.setAttribute("message", "密码修改失败");}elsereq.setAttribute("message", "新密码有问题");req.getRequestDispatcher("pwdmodify.jsp").forward(req,resp);}//验证旧密码,无需查询数据库,直接从当前session中的user对象获取public void pwdModify(HttpServletRequest req, HttpServletResponse resp){//从session中拿取用户对象Object o = req.getSession().getAttribute(Constants.USER_SESSION);//获取前端(Ajax部分)传过来的旧密码,并于user中的密码比对String oldPassword = req.getParameter("oldpassword");//用Map结果集作为响应,返回给前端(Ajax部分)Map<String, String> resultMap = new HashMap<String, String>();if (o == null){//session失效或过期时(真实网站的session会设置过期时间)resultMap.put("result", "sessionerror");}else if(StringUtils.isEmptyOrWhitespaceOnly(oldPassword)){//输入的旧密码为空resultMap.put("result", "error");}else {String userPassword = ((User)o).getUserPassword();//已登录用户的现在密码//比对输入的旧密码和session中用户密码if (oldPassword.equals(userPassword))resultMap.put("result", "true");elseresultMap.put("result", "false");}try {resp.setContentType("application/json");PrintWriter writer = resp.getWriter();//JSONArray 阿里巴巴的JSON工具类,将Map类转换为json(前端Ajax接受的是json格式)writer.write(JSONArray.toJSONString(resultMap));writer.flush();writer.close();}catch (IOException e){e.printStackTrace();}}
}

配合pwdmodify.js中的Ajax,看旧密码验证部分

oldpassword.on("blur",function(){$.ajax({type:"GET",url:path+"/jsp/user.do",data:{method:"pwdmodify",oldpassword:oldpassword.val()},dataType:"json",success:function(data){if(data.result == "true"){//旧密码正确validateTip(oldpassword.next(),{"color":"green"},imgYes,true);}else if(data.result == "false"){//旧密码输入不正确validateTip(oldpassword.next(),{"color":"red"},imgNo + " 原密码输入不正确",false);}else if(data.result == "sessionerror"){//当前用户session过期,请重新登录validateTip(oldpassword.next(),{"color":"red"},imgNo + " 当前用户session过期,请重新登录",false);}else if(data.result == "error"){//旧密码输入为空validateTip(oldpassword.next(),{"color":"red"},imgNo + " 请输入旧密码",false);}},error:function(data){//请求出错validateTip(oldpassword.next(),{"color":"red"},imgNo + " 请求错误",false);}});

5、注册UserServlet

<servlet><servlet-name>UserServlet</servlet-name><servlet-class>com.zcy.servlet.user.UserServlet</servlet-class>
</servlet>
<servlet-mapping><servlet-name>UserServlet</servlet-name><url-pattern>/jsp/user.do</url-pattern>
</servlet-mapping>

用户管理

先写 PageSupport.java 分页工具类

package com.zcy.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;}}
}

1、获取用户数量

1、UserDao.java添加方法

/**
* 根据用户名或角色类型 获取用户数量
* @param connection 连接参数
* @param userName 用户名
* @param userRole 用户角色类型
* @return 用户数量
*/
public int getUserCount(Connection connection, String userName, int userRole) throws SQLException;

2、UserDaoImpl.java添加方法

/*** 根据用户id和密码修改密码* @param connection 连接参数* @param userName 用户名* @param userRole 用户角色类型* @return 用户数量* @throws SQLException*/
public int getUserCount(Connection connection, String userName, int userRole) throws SQLException {PreparedStatement preparedStatement = null;ResultSet resultSet = null;int count = 0;//这里用int更好,Integer不合适,因为count必定不为nullif (connection != null){StringBuffer sql = new StringBuffer();sql.append("select count(1) as count from smbms_user u, smbms_role r where u.userRole = r.id");ArrayList<Object> list = new ArrayList<Object>();//存放参数if (!StringUtils.isNullOrEmpty(userName)){sql.append(" and u.userName like ?");list.add("%"+userName+"%");//like 模糊查询}//因为角色的值是 1 2 3if (userRole>0){sql.append(" and r.id = ?");list.add(userRole);}Object[] params = list.toArray();//输出完整SQLSystem.out.println("UserDaoImpl——>getUserCount:"+sql.toString());preparedStatement = connection.prepareStatement(sql.toString());resultSet = BaseDao.query(connection, preparedStatement, params);if (resultSet.next())count = resultSet.getInt("count");BaseDao.closeResource(null, preparedStatement, resultSet);}return count;}

3、UserService.java添加方法

/*** 根据用户名或用户角色类型获取用户数量* @param userName 用户名* @param userRole 用户角色类型* @return 用户数量*/
public int getUserCount(String userName, int userRole);

4、UserServiceImpl.java添加方法

/*** 根据用户名或用户角色类型获取用户数量* @param userName 用户名* @param userRole 用户角色类型* @return 用户数量*/public int getUserCount(String userName, int userRole) {Connection connection = null;int count = 0;try {connection = BaseDao.getConnection();count = userDao.getUserCount(connection, userName, userRole);} catch (SQLException e) {e.printStackTrace();}finally {BaseDao.closeResource(connection, null, null);}return count;}@Testpublic void test(){UserServiceImpl userService = new UserServiceImpl();int userCount = userService.getUserCount(null, 3);System.out.println(userCount);}

2、获取用户列表

1、UserDao.java添加方法

/*** 通过条件查询* @param connection 连接参数* @param userName 用户名* @param userRole 用户角色* @param currentPageNo 当前页* @param pageSize 页面大小* @return 用户列表*/public List<User> getUserList(Connection connection, String userName, int userRole,int currentPageNo, int pageSize) throws Exception;

2、UserDaoImpl.java添加方法

/*** 根据条件查询* @param connection 连接参数* @param userName 用户名* @param userRole 用户角色* @param currentPageNo 当前页* @param pageSize 页面大小* @return 用户列表* @throws Exception*/public List<User> getUserList(Connection connection, String userName,int userRole,int currentPageNo, int pageSize)throws Exception {PreparedStatement preparedStatement = null;ResultSet resultSet = null;List<User> userList = new ArrayList<User>();if(connection != null){StringBuffer sql = new StringBuffer();sql.append("select u.*, r.roleName as userRoleName from smbms_user u, smbms_role r where u.userRole = r.id");List<Object> list = new ArrayList<Object>();if(!StringUtils.isNullOrEmpty(userName)){sql.append(" and u.userName like ?");list.add("%"+userName+"%");}if(userRole > 0){sql.append(" and u.userRole = ?");list.add(userRole);}// 排序和分页// 分页:limit 开始下标, 页面大小// 假如每页3个数据,我想从第2页开始: 第一页 0 1 2, 第二页 3 4 5// 开始下标为 2 - 1 = 1, 1 * 3 = 3// limit 3, 3sql.append(" order by creationDate DESC limit ?,?");currentPageNo = (currentPageNo-1)*pageSize;list.add(currentPageNo);list.add(pageSize);Object[] params = list.toArray();System.out.println("UserDaoImpl——>getUserList:" + sql.toString());preparedStatement = connection.prepareStatement(sql.toString());resultSet = BaseDao.query(connection, preparedStatement, params);while(resultSet.next()){User user = new User();user.setId(resultSet.getInt("id"));user.setUserCode(resultSet.getString("userCode"));user.setUserName(resultSet.getString("userName"));user.setGender(resultSet.getInt("gender"));user.setBirthday(resultSet.getDate("birthday"));user.setPhone(resultSet.getString("phone"));user.setUserRole(resultSet.getInt("userRole"));user.setUserRoleName(resultSet.getString("userRoleName"));userList.add(user);}BaseDao.closeResource(null, preparedStatement, resultSet);}return userList;}

3、UserService.java添加方法

/*** 根据条件查询用户列表* @param userName 用户名* @param userRole 用户角色* @param currentPageNo 当前页号* @param pageSize 页面大小* @return 用户列表*/public List<User> getUserList(String userName, int userRole, int currentPageNo, int pageSize);

4、UserServiceImpl.java添加方法

public List<User> getUserList(String userName, int userRole, int currentPageNo, int pageSize) {Connection connection = null;List<User> users = null;System.out.println("UserServiceImpl——>getUserList:");System.out.println("userName:"+userName);System.out.println("userRole:"+userRole);System.out.println("currentPageNo:"+currentPageNo);System.out.println("pageSize:"+pageSize);System.out.println("-------------------------------");try {connection = BaseDao.getConnection();userDao.getUserList(connection, userName, userRole, currentPageNo, pageSize);} catch (Exception e) {e.printStackTrace();}finally {BaseDao.closeResource(connection, null, null);}return null;}

3、获取角色列表

为了职责更好统一,把角色的操作放在另一个包里,和POJO类对应。

1、RoleDao.java

package com.zcy.dao.role;import com.zcy.pojo.Role;import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;public interface RoleDao {/*** 角色列表是固定的,只有三个数据,系统管理员1、经理2、普通员工3* @param connection 连接参数* @return 角色列表*/public List<Role> getRoleList(Connection connection) throws SQLException;
}

2、RoleDaoImpl.java

package com.zcy.dao.role;import com.zcy.dao.BaseDao;
import com.zcy.pojo.Role;import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;public class RoleDaoImpl implements RoleDao {public List<Role> getRoleList(Connection connection) throws SQLException {PreparedStatement preparedStatement = null;ResultSet resultSet = null;ArrayList<Role> list = new ArrayList<Role>();if(connection != null){String sql = "select * from smbms_role";Object[] params = {};preparedStatement = connection.prepareStatement(sql);resultSet = BaseDao.query(connection, preparedStatement, params);while (resultSet.next()){Role role = new Role();role.setRoleName(resultSet.getString("roleName"));role.setId(resultSet.getInt("id"));role.setRoleCode(resultSet.getString("roleCode"));list.add(role);}BaseDao.closeResource(null, preparedStatement, resultSet);}return list;}
}

3、RoleService.java

package com.zcy.service.role;import com.zcy.pojo.Role;import java.util.List;public interface RoleService {//获取角色列表public List<Role> getRoleList();
}

4、RoleServiceImpl.java

package com.zcy.service.role;import com.zcy.dao.BaseDao;
import com.zcy.dao.role.RoleDao;
import com.zcy.dao.role.RoleDaoImpl;
import com.zcy.pojo.Role;import java.awt.image.RasterOp;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;public class RoleServiceImpl implements RoleService {//引入Daoprivate RoleDao roleDao;public RoleServiceImpl(){roleDao = new RoleDaoImpl();}public List<Role> getRoleList() {Connection connection = null;List<Role> roleList = null;try {connection = BaseDao.getConnection();roleList = roleDao.getRoleList(connection);} catch (SQLException e) {e.printStackTrace();}finally {BaseDao.closeResource(connection, null, null);}return roleList;}
}

5、显示前面的各种列表的Servlet

在UserServlet.java中增加方法 query

//反馈给前端 用户列表、角色列表、分页(重难点)public void query(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//获取用户前端的数据String queryUserName = req.getParameter("queryname");String temp = req.getParameter("queryUserRole");String pageIndex = req.getParameter("pageIndex");int queryUserRole = 0;//角色类型在数据库整型的,默认0,不代表任何角色UserServiceImpl userService = new UserServiceImpl();RoleServiceImpl roleService = new RoleServiceImpl();int pageSize = 5;//默认页面大小显示5个数据int currentPageNo = 1;//默认当前页为第一页//判断请求是否需要执行,根据参数的值判断if (queryUserName == null){//请求中未包含用户名参数,角色名设置为空queryUserName = "";}if (!StringUtils.isNullOrEmpty(temp)){//请求包含了角色参数,将字符串转为整型queryUserRole = new Integer(temp);}if (pageIndex != null){//请求中包含页码,表明想看某一页数据,设置当前页为想看的那一页currentPageNo = Integer.parseInt(pageIndex);}// 3. 为了实现分页,需要计算出当前页面、总页面、页面大小int totalCount = userService.getUserCount(queryUserName, queryUserRole);//用户总数//总页数支持PageSupport pageSupport = new PageSupport();pageSupport.setCurrentPageNo(currentPageNo);pageSupport.setPageSize(pageSize);pageSupport.setTotalCount(totalCount);int totalPageCount = pageSupport.getTotalPageCount();//总页数//控制首页和尾页,如果页面要小于1或者大于总页数,则进行限制if (currentPageNo < 1)currentPageNo = 1;else if (currentPageNo > totalPageCount)currentPageNo = totalPageCount;//获得用户列表数据和角色数据列表List<User> userList = userService.getUserList(queryUserName, queryUserRole, currentPageNo, pageSize);List<Role> roleList = roleService.getRoleList();//将数据放入requestreq.setAttribute("userList", userList);req.setAttribute("roleList", roleList);req.setAttribute("totalCount", totalCount);req.setAttribute("currentPageNo", currentPageNo);req.setAttribute("totalPageCount", totalPageCount);req.setAttribute("queryUserName", queryUserName);req.setAttribute("queryUserRole", queryUserRole);//返回前端,用请求转发,因为数据放在request中req.getRequestDispatcher("userlist.jsp").forward(req, resp);}

同时,修改doGet里的程序

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//从前端获取参数,根据参数执行对应方法String method = req.getParameter("method");if (method!=null && method.equals("savepwd"))this.updatePassword(req,resp);else if (method!=null && method.equals("pwdmodify"))this.pwdModify(req, resp);else if (method!=null && method.equals("query")){this.query(req, resp);}}

4、添加用户

1、UserDao.java添加方法

/*** 增加一个用户* @param connection* @param user* @return 操作成功的行数*/public int addUser(Connection connection, User user) throws SQLException;

2、UserDaoImpl.java添加方法

public int addUser(Connection connection, User user) throws SQLException {PreparedStatement preparedStatement = null;int updateRows = 0;if (connection != null){String sql = "insert into smbms_user" +" (userCode, userName, userPassword, gender, birthday, phone, address, userRole, creationDate, createdBy)" +"values (?,?,?,?,?,?,?,?,?,?)";preparedStatement = connection.prepareStatement(sql);Object[] params = {user.getUserCode(),user.getUserName(),user.getUserPassword(),user.getGender(),user.getBirthday(),  user.getPhone(),user.getAddress(), user.getUserRole(),user.getCreationDate(),user.getCreatedBy()};updateRows = BaseDao.update(connection, preparedStatement, params);BaseDao.closeResource(null, preparedStatement, null);}return updateRows;}

3、UserService.java添加方法

/*** 添加一个用户* @param user 用户对象* @return true 添加成功,false 添加失败*/public boolean addUser(User user);

4、UserServiceImpl.java添加方法

/*** 添加一个用户* @param user 用户对象* @return true 添加成功,false 添加失败*/public boolean addUser(User user) {Connection connection = null;boolean flag = false;try {connection = BaseDao.getConnection();connection.setAutoCommit(false);//关闭自动提交,开启事务管理int updateRows = userDao.addUser(connection, user);connection.commit();//提交if (updateRows > 0){flag = true;System.out.println("UserServiceImpl——>addUser:成功添加用户");}elseSystem.out.println("UserServiceImpl——>addUser:添加用户失败");} catch (Exception e) {e.printStackTrace();try {connection.rollback();System.out.println("UserServiceImpl——>addUser:回滚");} catch (SQLException ex) {ex.printStackTrace();}}finally {//Service层关闭connection连接BaseDao.closeResource(connection, null, null);}return flag;}

5、UserServlet.java添加方法

//添加用户public void add(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {String userCode = req.getParameter("userCode");String userName = req.getParameter("userName");String userPassword = req.getParameter("userPassword");String gender = req.getParameter("gender");String birthday = req.getParameter("birthday");String phone = req.getParameter("phone");String address = req.getParameter("address");String userRole = req.getParameter("userRole");User user = new User();user.setUserCode(userCode);user.setUserName(userName);user.setUserPassword(userPassword);user.setGender(Integer.parseInt(gender));try {user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));} catch (ParseException e) {e.printStackTrace();}user.setPhone(phone);user.setAddress(address);user.setUserRole(Integer.parseInt(userRole));user.setCreationDate(new Date());user.setCreatedBy(((User)req.getSession().getAttribute(Constants.USER_SESSION)).getId());UserServiceImpl userService = new UserServiceImpl();//添加成功,就直接重定向到查询页面显示数据;添加失败,则请求转发,重新添加。(请求转发能保留request的数据)if (userService.addUser(user))resp.sendRedirect(req.getContextPath()+"/jsp/user.do?method=query");elsereq.getRequestDispatcher("useradd.jsp").forward(req, resp);}

总结

项目的功能没有全部实现完,整个项目逻辑比较简单,主要是将之前学的巩固练手,其他的功能实现方法都是类似的。

百度网盘:https://pan.baidu.com/s/16fNpMkGeXZud-U58Z5y67g 提取码: q3eq

JavaWeb 开发 06 —— smbms项目实践相关推荐

  1. 基于STM32小熊派开发智慧路灯项目实践

    目录 一.引言 二.智慧路灯物联网架构介绍 1.感知层: 2.网络层: 3.平台层 4.应用层 三.开发环境 四.开发注意事项 五.学习网站(实践指南) 1.华为云实战训练营教学视频 2.智慧路灯项目 ...

  2. 【狂神说】JavaWeb笔记整理 | SMBMS项目 | 文件上传和邮件发送

    目录 JavaWeb 1.基本概念 1.1 概念 1.2 web应用程序: 1.3 静态web 1.4 动态web 2.web服务器 2.1 技术讲解 2.2 web 服务器 3. Tomcat 3. ...

  3. 基于fs_11c14开发板的项目实践

    fs_11c14是华清远见的一款开发板,主芯片是LPC111C4,这个芯片一共有48个管脚,其中2个晶振管脚,4个电源引脚,42个通用输入输出管脚.芯片手册可以在网上下载. LPC1114内部包含有c ...

  4. JavaWEB开发21——综合项目(图书商城)

    数据库 create database productstore character set utf8 collate utf8_bin;USE productstore; -- 用户表 CREATE ...

  5. 项目实践精解:ASP.NET应用开发

    前 言 作者从事软件设计开发工作十多年,最近才萌发了写书的想法.因为作者希望推广一种最有效的学习捷径,这就是Project-Driven Training,也就是用项目实践来带动理论学习的方法.基于此 ...

  6. Python爬虫开发与项目实践

    百度网盘 链接:https://pan.baidu.com/s/1D3T0SA4AOHaGisODxY11kQ 密码:u3yo 本教程详细介绍Python的爬虫开发与项目实践,从安装到文件操作到IO编 ...

  7. 项目实践精解:C#核心技术应用开发

    前 言 学习任何技术都要从基础开始,这本书就是讲解C#核心技术的基础教材.读者如果简单调研一下就不难发现,市面上最多的就是这类C#基础类教材.那么,我们还有没有必要再多写一本没有特色.枯燥乏味的书呢? ...

  8. 基于JDBC的JavaWeb开发项目之——网上教务系统

    基于JDBC的JavaWeb开发项目之--网上教务系统 在这个文章里,我会详细的解释JavaWeb其中的一个框架--MVC框架来完成网上教务系统这一个项目.这个项目是使用JDBC去连接数据库,使用了J ...

  9. web前端开发技术实验与实践(第三版)储久良编著 项目12 设计简易网站导航

    web前端开发技术实验与实践(第三版)储久良编著 项目12 设计简易网站导航 实训三  项目12 设计简易网站导航 一.页面文字素材: 序号 网站名称 URL 1 百  度 http://www.ba ...

最新文章

  1. 从浏览器发展史读懂user-agent
  2. 聊聊 MySql 索引那些事儿
  3. C语言/C++基础知识
  4. Redis Cluster 集群模式原理和动态扩容
  5. google圣诞节彩蛋
  6. python之cookbook-day03
  7. 日结问题解决思路和方式
  8. 硬件电路基础(2)RF 一些概念
  9. golang map转json的顺序问题
  10. 推荐10款最佳的App安全测试工具
  11. SOUI控件的自绘和消息处理
  12. Android流媒体播放器介绍
  13. bugku之密码ok解题思路
  14. c语言爱心代码我爱你,C语言告白代码,一闪一闪亮晶晶~
  15. 微信扫描二维码实现下载app文件
  16. Windows自带虚拟机的使用方法
  17. 一起来学习Java浮点类型
  18. 基于OpenCV的摄像头人脸检测
  19. 如何在安卓计算机里边隐藏游戏,安卓手机如何隐藏应用程序,来看看吧
  20. Google-Guava(Utilites)

热门文章

  1. 3.8、集线器与交换机的区别
  2. IDEA最牛配置,众享丝滑
  3. 胡侃学习(理论)计算机
  4. C++类和对象:友元内部类
  5. Ubuntu下的基本知识点(一)
  6. 单词发音软件测试自学,一定要告诉孩子:每天30分钟,用这三个方法学英语,想不考好都难!...
  7. JVM分析指令解析-jps/jinfo/jstat/jstack/jmap/jcmd
  8. 散列函数c语言实现,哈希表的C语言实现
  9. Java实现QQ邮箱验证激活 Java简单发送邮箱
  10. 服务器发送wifi信号,改变WIFI无线路由信号弱的解决方案:利用发送噪音