*资源在文末
1 环境简介环境:
JDK 1.8apache-tomcat-9.0.59apache-maven-3.8.4IntelliJ IDEA 2021.1.2 x64 2 初始配置 2.1 web.xml 初始配置
2.2 pow.xml 依赖
javax.servlet
javax.servlet-api
4.0.1
provided
javax.servlet.jsp
javax.servlet.jsp-api
2.3.3
provided
mysql
mysql-connector-java
5.1.49
javax.servlet.jsp.jstl
jstl-api
1.2
taglibs
standard
1.1.2
com.alibaba
fastjson
1.2.79
2.3 tomcat 配置
3 实体类
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-7t7dIuMh-1648281331549)(C:UsersFlameAppDataRoamingTyporatypora-user-imagesimage-20220322131702441.png)]
User 实体类
package com.bailugansan.pojo;
import java.util.Date;
public class User {
private Integer id;
private String userCode;
private String userName;
private String userPassword;
private Integer gender;
private Date birthday;
private String phone;
private String address;
private Integer userRole;
private Integer createdBy;
private Date creationDate;
private Integer modifyBy;
private Date modifyDate;
public User() {
}
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;
}
}
4 基础公共类
4.1 数据库配置文件
driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/smbms?userUnicode=true&characterEncoding=utf-8 username=root password=4.2 数据库基础公共类
package com.bailugansan.util;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
// 数据库基础公共类
public class DbUtil {
private static String driver;
private static String url;
private static String username;
private static String password;
// 静态代码块,类加载的时候在连接阶段就初始化了
static{
Properties properties = new Properties();
// 获取类加载器
ClassLoader classLoader = DbUtil.class.getClassLoader();
// 获取数据库配置文件的输入流
InputStream resourceAsStream = classLoader.getResourceAsStream("db.properties");
try {
properties.load(resourceAsStream);
} catch (IOException e) {
e.printStackTrace();
}
driver = properties.getProperty("driver");
url = properties.getProperty("url");
username = properties.getProperty("username");
password = properties.getProperty("password");
}
// 获取数据库连接
public static Connection getConn(){
Connection connection = null;
try {
// 加载驱动
Class.forName(driver);
// 获取连接
connection = DriverManager.getConnection(url, username, password);
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
return connection;
}
// 查询公共方法
// 参数全部提取出来方便统一关闭
public static ResultSet execute(Connection conn, String sql, Object[] params, ResultSet resultSet, PreparedStatement preparedStatement){
try {
// 获取预编语句
preparedStatement = conn.prepareStatement(sql);
// 填充占位符
for (int i = 0; i < params.length; i++) {
// 占位符从 1 开始
preparedStatement.setObject(i+1, params[i]);
}
// 执行
resultSet = preparedStatement.executeQuery(sql);
} catch (SQLException e) {
e.printStackTrace();
}
return resultSet;
}
// 增删改公共方法
public static int update(Connection conn, String sql, Object[] params, int result, PreparedStatement preparedStatement){
try {
preparedStatement = conn.prepareStatement(sql);
// 填充占位符
for (int i = 0; i < params.length; i++) {
// 占位符从 1 开始
preparedStatement.setObject(i+1, params[i]);
}
result = preparedStatement.executeUpdate(sql);
} catch (SQLException e) {
e.printStackTrace();
}
return result;
}
// 关闭连接,释放资源
public static boolean closeConn(Connection conn, PreparedStatement prep, ResultSet resu){
boolean flag = true;
try {
if(conn != null){
conn.close();
// GC 回收
conn = null;
}
if(prep != null){
prep.close();
prep = null;
}
if(resu != null){
resu.close();
resu = null;
}
} catch (SQLException e) {
e.printStackTrace();
flag = false;
}
return flag;
}
}
5 过滤器
5.1 字符集过滤器
package com.bailugansan.filter;
import javax.servlet.*;
import java.io.IOException;
public class CharacterEncodingFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
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);
}
@Override
public void destroy() {
}
}
6 登录模块
6.1 登录功能
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
UserServiceImpl userService = new UserServiceImpl();
String userCode = req.getParameter("userCode");
String userPassword = req.getParameter("userPassword");
User user = userService.login(userCode, userPassword);
System.out.println(user);
if(user != null){
// 给登录成功的用户发放 Session
req.getSession().setAttribute(Constants.USER_SESSION, user);
// 重定向,转跳到登录后的页面
resp.sendRedirect("jsp/frame.jsp");
} else{
req.setAttribute("error", "用户名或密码错误");
req.getRequestDispatcher("login.jsp").forward(req, resp);
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
6.2 登录注销
public class LoginoutServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 移除用户 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);
}
}
6.3 登录拦截
package com.bailugansan.filter;
import com.bailugansan.pojo.User;
import com.bailugansan.util.Constants;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class SysFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse resp = (HttpServletResponse) response;
// 获取登录对象中 Session 中存放的 User 对象
User user = (User)req.getSession().getAttribute(Constants.USER_SESSION);
if(user == null){
resp.sendRedirect(req.getContextPath()+"/error.jsp");
}
chain.doFilter(request, response);
}
@Override
public void destroy() {
}
}
7 密码修改
7.1 旧密码验证
public class PwdServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String method = req.getParameter("method");
// Servlet 复用
if(method != null && "check".equals(method)){
checkPwd(req, resp);
} else {
pwdModify(req, resp);
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
// 修改密码
protected void pwdModify(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Object o = req.getSession().getAttribute(Constants.USER_SESSION);
String newpassword = req.getParameter("newpassword");
if(o != null && !StringUtils.isNullOrEmpty(newpassword)){
UserService userService = new UserServiceImpl();
boolean updateResult = userService.pwdModify(((User) o).getId(), newpassword);
if(updateResult){ // 成功则删除 Session 并退出登录
req.setAttribute("message","修改成功,请重新登录");
req.getSession().removeAttribute(Constants.USER_SESSION);
try {
resp.sendRedirect(req.getContextPath()+"/login.jsp");
} catch (IOException e) {
e.printStackTrace();
}
} else {
System.out.println(111);
req.setAttribute("message", "修改失败,请重试");
resp.sendRedirect(req.getContextPath()+"/jsp/pwdmodify.jsp");
}
}
}
// 验证旧密码
protected void checkPwd(HttpServletRequest req, HttpServletResponse resp) throws IOException {
Object o = req.getSession().getAttribute(Constants.USER_SESSION);
String oldpassword = req.getParameter("oldpassword");
Map resultMap = new HashMap();
if(o == null ){ // Session 失效或者过期
resultMap.put("result", "sessionerror");
} else if(StringUtils.isNullOrEmpty(oldpassword)){ // 输入旧密码为空
resultMap.put("result", "error");
} else {
String userPassword = ((User) o).getUserPassword();
if(userPassword.equals(oldpassword)){ // 校验正确
resultMap.put("result", "true");
} else {
resultMap.put("result", "false");
}
}
resp.setContentType("application/json");
PrintWriter writer = resp.getWriter();
writer.write(JSONArray.toJSONString(resultMap));
writer.flush();
writer.close();
}
}
8 用户管理
这里只实现了用户查询
9 部分注意事项 9.1 乱码问题如果设置了 charset=“utf-8" 无效
或 js 修改无效
可以尝试清除浏览器缓再看看,ctrl + F5
9.2 项目完成度该项目完成的功能:
登录、登录注销密码修改用户查询部分 10 静态资源及源码
Gitee 链接



