这是我学完JavaWeb后做的期末大作业,是一个用户管理系统,包括登录注册功能,对于列表的增、删、改、查功能,由于我也是参考的网上大佬的的代码,之后进行了一些修改,完成的这个新手项目,于是我也把这个项目源码放在这里供大家参考,同时也对这次学习做一个记录。
首先感谢大佬们的文章帮助,我把所参考的文章原文链接放在下面:
【Java学习】JSP + Servlet + JDBC + Mysql 实现增删改查_Tellsea的博客-CSDN博客_java jsp 实现增删改查
使用JSP+Servlet+MySQL实现登录注册功能【详细代码】_邵奈一的博客-CSDN博客
Eclipse IDE for Enterprise Java Developers Version: 2020-12 (4.18.0)
MySQL workbench: 8.0.29
Tomcat: 9.0
JDBC jar包:在Eclipse中使用JDBC连接MySQL(mysql-connector-java-8.0.28版本)_鸭巴子嘎嘎嘎的博客-CSDN博客_eclipse配置jdbc连接mysql
JSTL jar包以及引用语句:JSP 标准标签库(JSTL) | 菜鸟教程
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
jQuery引用以及下载网站:https://www.jq22.com/jquery-info122#google_vignette
Bootstrap v3 引用以及网站:Bootstrap v3 中文文档 · Bootstrap 是最受欢迎的 HTML、CSS 和 JavaScript 框架,用于开发响应式布局、移动设备优先的 WEB 项目。 | Bootstrap 中文网
这里以mysql连接包举例,其他的类似,目录结构中其他两个包都是JSTL所用到的,我就导入了这三个包,都在上面的目录文件结构中列出了。
index1.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%String path=request.getContextPath(); %>用户管理系统 /index1">首页 /userInfoSave">添加用户 /userInfoList">用户列表欢迎!
这是Tang的用户管理系统,使用了 JSP, JavaServlet, JDBC, MySQL, jQuery以及Bootstrap框架,基于MVC模式开发。
更多
IndexServlet.java
package Tang.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 首页控制器 * @author TZQ * */ @WebServlet("/index1") @SuppressWarnings("serial") public class IndexServlet extends HttpServlet { protected void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException{ req.getRequestDispatcher("/Index1.jsp").forward(req,resp); } protected void doPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException{ //req.getRequestDispatcher(req.getContextPath()+"index.jsp"); this.doGet(req, resp); } }
MysqlUtils.java
package Tang.utils; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.List; import Tang.service.LoginInfoService; import Tang.service.UserInfoService; import Tang.service.impl.LoginInfoServiceImpl; import Tang.service.impl.UserInfoServiceImpl; import Tang.entity.LoginInfo; import Tang.entity.UserInfo; /** * MySQL连接工具类 * @author TZQ * */ public class MysqlUtils { private static String url="jdbc:mysql://localhost:3306/javaweb"; //连接地址 private static String userName="root"; //连接用户名 private static String password="tzq"; //连接密码 private static Connection conn=null; //连接驱动 public static Connection getConnection() { if(conn==null) { try { //com.mysql.jdbc.Driver是 mysql-connector-java 5版本中的 //com.mysql.cj.jdbc.Driver是 mysql-connector-java 6版本及以上中的 Class.forName("com.mysql.cj.jdbc.Driver"); conn=DriverManager.getConnection(url,userName,password); } catch(ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return conn; } //测试 public static void main(String[] args) { System.out.println(getConnection()); LoginInfoService loginInfoService=new LoginInfoServiceImpl(); LoginInfo user=new LoginInfo(); user.setAccount("1"); user.setPassword("2"); loginInfoService.register(user); String account="1"; String password="2"; LoginInfo user1=loginInfoService.login(account, password); System.out.println(user1.toString()); // UserInfoService userInfoService=new UserInfoServiceImpl(); // UserInfo entity1=new UserInfo(); // entity1.setName("芳华"); // entity1.setPassword("rr36988"); // entity1.setEmail("fh3236@123.com"); // entity1.setAddress("天津"); // userInfoService.saveUserInfo(entity1); // // // Listlist=userInfoService.userInfoList(); // list.forEach(entity ->{ // System.out.println(entity); // }); } }
UserInfo.java
package Tang.entity; /** * 用户实体类,也可以叫做bean * @author TZQ * */ public class UserInfo { private int id; private String name; private String password; private String email; private String address; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Override public String toString() { return "UserInfo [id=" + id + ", name=" + name + ", password=" + password + ", email=" + email + ", address=" + address + "]"; } }
UserInfoService.java
package Tang.service; import java.util.List; import Tang.entity.UserInfo; /** * 用户接口 * @author TZQ * */ public interface UserInfoService { //接口只写方法特征,而不实现,方法记得加括号否则会成为变量并报错"not have been initialized",未被初始化 //查询所有用户 ListuserInfoList(); //新增用户 void saveUserInfo(UserInfo entity); //根据id查询用户 UserInfo getUserInfoById(int id); //根据id更新用户 void updateUserInfoById(UserInfo entity); //根据id删除用户 void deleteUserInfoById(int id); }
UserInfoServiceImpl.java
package Tang.service.impl; import Tang.service.UserInfoService; import java.util.List; import Tang.dao.UserInfoDao; import Tang.entity.UserInfo; /** * 用户接口实现类 * @author TZQ * */ public class UserInfoServiceImpl implements UserInfoService { public ListuserInfoList(){ return UserInfoDao.userInfoList(); } @Override public void saveUserInfo(UserInfo entity) { UserInfoDao.saveUserInfo(entity); //调用dao层的相关方法 } @Override public UserInfo getUserInfoById(int id) { return UserInfoDao.getUserInfoById(id); } @Override public void updateUserInfoById(UserInfo entity) { UserInfoDao.updateUserInfoById(entity); } @Override public void deleteUserInfoById(int id) { UserInfoDao.deleteUserInfoById(id); } }
UserInfoDao.java
package Tang.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import Tang.entity.UserInfo; import Tang.utils.MysqlUtils; /** * 用户数据交互层 * @author TZQ * */ public class UserInfoDao { public static ListuserInfoList() { List list=new ArrayList<>(); Connection conn=MysqlUtils.getConnection(); String sql="select * from user_info;"; try { PreparedStatement pStatement=conn.prepareStatement(sql); ResultSet resultSet=pStatement.executeQuery(); UserInfo entity=null; while(resultSet.next()) { entity=new UserInfo(); entity.setId(resultSet.getInt("id")); entity.setName(resultSet.getString("name")); entity.setPassword(resultSet.getString("password")); entity.setEmail(resultSet.getString("email")); entity.setAddress(resultSet.getString("address")); list.add(entity); } resultSet.close(); //避免造成性能浪费 pStatement.close(); } catch (SQLException e) { e.printStackTrace(); } return list; } public static void saveUserInfo(UserInfo entity) { //添加用户的sql语句 String sql="insert into user_info(name,password,email,address) values(?,?,?,?);"; Connection conn=MysqlUtils.getConnection(); //得到数据库连接 try { PreparedStatement pStatement=conn.prepareStatement(sql); //使用预处理方法执行sql语句 //从实体类实例中得到相关数据并设置到sql语句的相关位置 pStatement.setString(1, entity.getName()); pStatement.setString(2, entity.getPassword()); pStatement.setString(3, entity.getEmail()); pStatement.setString(4, entity.getAddress()); int count=pStatement.executeUpdate(); //执行sql语句 pStatement.close(); //执行完成后执行该close方法,避免资源浪费 } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static UserInfo getUserInfoById(int id) { String sql="select U.id, U.name, U.password, U.email, U.address from user_info U where U.id= "+id+";"; Connection conn=MysqlUtils.getConnection(); UserInfo entity=null; try { PreparedStatement pStatement=conn.prepareStatement(sql); ResultSet resultSet=pStatement.executeQuery(); while(resultSet.next()) { entity=new UserInfo(); entity.setId(resultSet.getInt("id")); entity.setName(resultSet.getString("name")); entity.setPassword(resultSet.getString("password")); entity.setEmail(resultSet.getString("email")); entity.setAddress(resultSet.getString("address")); } resultSet.close(); //避免造成性能浪费 pStatement.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return entity; } public static void updateUserInfoById(UserInfo entity) { String sql="update user_info set name=?,password=?,email=?,address=? where id=?;"; Connection conn=MysqlUtils.getConnection(); try { PreparedStatement pStatement=conn.prepareStatement(sql); pStatement.setString(1, entity.getName()); pStatement.setString(2, entity.getPassword()); pStatement.setString(3, entity.getEmail()); pStatement.setString(4, entity.getAddress()); pStatement.setInt(5, entity.getId()); pStatement.executeUpdate(); pStatement.close(); } catch (SQLException e) { e.printStackTrace(); } } public static void deleteUserInfoById(int id) { String sql="delete from user_info where id="+id+";"; Connection conn=MysqlUtils.getConnection(); try { PreparedStatement pStatement=conn.prepareStatement(sql); pStatement.executeUpdate(); pStatement.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
UserInfoListServlet.java
package Tang.servlet; import java.io.IOException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import Tang.entity.UserInfo; import Tang.service.UserInfoService; import Tang.service.impl.UserInfoServiceImpl; /** * 用户列表控制器 * @author TZQ * MVC(视图层View,服务层Service,持久层Dao) *控制层(Servlet)->接口层(Service)->接口层实现类(ServiceImpL)->数据交互层(Dao) */ @WebServlet("/userInfoList") @SuppressWarnings("serial") public class UserInfoListServlet extends HttpServlet { protected void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException{ this.doPost(req, resp); } protected void doPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException{ //查询出所有用户 UserInfoService userInfoService=new UserInfoServiceImpl(); Listlist=userInfoService.userInfoList(); req.setAttribute("userInfoList", list); req.getRequestDispatcher("/user_info_list.jsp").forward(req, resp); } }
user_info_list.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%String path=request.getContextPath(); %>用户列表 /index1">首页 /userInfoSave">添加用户 /userInfoList">用户列表
序号 | 姓名 | 密码 | 邮箱 | 地址 | |
---|---|---|---|---|---|
${status.index+1} | ${entity.name } | ${entity.password } | ${entity.email } | ${entity.address } | /userInfoUpdate?id=${entity.id}">修改 /userInfoDelete?id=${entity.id}">删除 |
UserInfoSaveServlet.java
package Tang.servlet; import java.io.IOException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import Tang.entity.UserInfo; import Tang.service.UserInfoService; import Tang.service.impl.UserInfoServiceImpl; /** *新增用户控制器 * @author TZQ * */ @WebServlet("/userInfoSave") @SuppressWarnings("serial") public class UserInfoSaveServlet extends HttpServlet { protected void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException{ req.getRequestDispatcher("/user_info_save.jsp").forward(req, resp); } protected void doPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException{ //新增用户 //req.getParameter方法从前端页面的name标签中拿到用户输入的数据,getBytes("ISO-8859-1"),"UTF-8"解决乱码问题 String name=new String(req.getParameter("name").getBytes("ISO-8859-1"),"UTF-8"); String password=req.getParameter("password"); String email=req.getParameter("email"); String address=new String(req.getParameter("address").getBytes("ISO-8859-1"),"UTF-8"); //实例化一个用户对象,使用set方法将输入的数据设置给这个对象 UserInfo entity=new UserInfo(); entity.setName(name); entity.setPassword(password); entity.setEmail(email); entity.setAddress(address); UserInfoService userInfoService=new UserInfoServiceImpl(); userInfoService.saveUserInfo(entity); //调用接口中的方法 req.getRequestDispatcher("/userInfoList").forward(req, resp); //转发跳转 //resp.sendRedirect("/userInfoList"); //转发重定向 } }
user_info_save.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%String path=request.getContextPath(); %>添加用户 /index1">首页 /userInfoSave">添加用户 /userInfoList">用户列表
UserInfoUpdateServlet.java
package Tang.servlet; import java.io.IOException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import Tang.entity.UserInfo; import Tang.service.UserInfoService; import Tang.service.impl.UserInfoServiceImpl; /** * 修改用户控制器 * @author TZQ * */ @WebServlet("/userInfoUpdate") @SuppressWarnings("serial") public class UserInfoUpdateServlet extends HttpServlet { protected void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException{ //查询需要编辑的信息 UserInfoService userInfoService=new UserInfoServiceImpl(); UserInfo entity=userInfoService.getUserInfoById(Integer.parseInt(req.getParameter("id"))); req.setAttribute("entity", entity); req.getRequestDispatcher("/user_info_update.jsp").forward(req, resp); } protected void doPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException{ int id=Integer.parseInt(req.getParameter("id")); String name=new String(req.getParameter("name").getBytes("ISO-8859-1"),"UTF-8"); //解决乱码问题 String password=req.getParameter("password"); String email=req.getParameter("email"); String address=new String(req.getParameter("address").getBytes("ISO-8859-1"),"UTF-8"); UserInfo entity=new UserInfo(); entity.setId(id); entity.setName(name); entity.setPassword(password); entity.setEmail(email); entity.setAddress(address); UserInfoService userInfoService=new UserInfoServiceImpl(); userInfoService.updateUserInfoById(entity); req.getRequestDispatcher("/userInfoList").forward(req, resp); //resp.sendRedirect("/UserManagementTang/WebContent/user_info_update.jsp"); //转发重定向 } }
user_info_update.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%String path=request.getContextPath(); %>更新用户 /index1">首页 /userInfoSave">添加用户 /userInfoList">用户列表
UserInfoDeleteServlet.java
package Tang.servlet; import java.io.IOException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import Tang.entity.UserInfo; import Tang.service.UserInfoService; import Tang.service.impl.UserInfoServiceImpl; /** * 用户删除控制器 * @author TZQ * */ @WebServlet("/userInfoDelete") @SuppressWarnings("serial") public class UserInfoDeleteServlet extends HttpServlet { protected void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException{ this.doPost(req, resp); } protected void doPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException{ //根据id删除 UserInfoService userInfoService=new UserInfoServiceImpl(); userInfoService.deleteUserInfoById(Integer.parseInt(req.getParameter("id"))); req.getRequestDispatcher("/userInfoList").forward(req, resp); //resp.sendRedirect("/userInfoList"); //转发重定向 } }
LoginInfo.java
package Tang.entity; /** * 注册登录实体类 * @author TZQ * */ public class LoginInfo { private String account; private String password; public String getAccount() { return account; } public void setAccount(String account) { this.account = account; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override public String toString() { return "LoginInfo [account=" + account + ", password=" + password + "]"; } }
LoginInfoService.java
package Tang.service; import Tang.entity.LoginInfo; /** * 登录接口 * @author TZQ * */ public interface LoginInfoService { LoginInfo login(String account, String password); void register(LoginInfo user); }
LoginInfoServiceImpl.java
package Tang.service.impl; import Tang.dao.LoginInfoDao; import Tang.entity.LoginInfo; import Tang.service.LoginInfoService; /** * 登录接口实现类 * @author TZQ * */ public class LoginInfoServiceImpl implements LoginInfoService { @Override public LoginInfo login(String account, String password) { return LoginInfoDao.login(account,password); } @Override public void register(LoginInfo user) { LoginInfoDao.register(user); } }
LoginInfoDao.java
package Tang.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import Tang.entity.LoginInfo; import Tang.utils.MysqlUtils; /** * 登录功能类 * @author TZQ * */ public class LoginInfoDao { public static LoginInfo login(String account, String password) { String sql="select * from login_info where account="+"'"+account+"'"+" and password="+"'"+password+"'"+";"; Connection conn=MysqlUtils.getConnection(); LoginInfo user=new LoginInfo(); try { PreparedStatement pStatement=conn.prepareStatement(sql); ResultSet resultSet=pStatement.executeQuery(); if(resultSet.next()) { user.setAccount(resultSet.getString("account")); user.setPassword(resultSet.getString("password")); System.out.println(user+"登录成功!"); } else { System.out.println("用户名或密码错误!"); } resultSet.close(); pStatement.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return user; } public static void register(LoginInfo user) { String sql="insert into login_info(account,password) values(?,?);"; Connection conn=MysqlUtils.getConnection(); try { PreparedStatement pStatement=conn.prepareStatement(sql); pStatement.setString(1, user.getAccount()); pStatement.setString(2, user.getPassword()); pStatement.executeUpdate(); pStatement.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
LoginServlet.java
package Tang.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import Tang.entity.LoginInfo; import Tang.service.LoginInfoService; import Tang.service.impl.LoginInfoServiceImpl; /** * 登录控制器 * @author TZQ * */ @WebServlet("/login") @SuppressWarnings("serial") public class LoginServlet extends HttpServlet { protected void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException{ req.getRequestDispatcher("/login.jsp").forward(req,resp); } protected void doPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException{ String account= req.getParameter("account"); String password= req.getParameter("password"); LoginInfoService loginInfoService=new LoginInfoServiceImpl(); LoginInfo user=loginInfoService.login(account, password); if(user.getAccount()!=null) { req.getRequestDispatcher("/index1").forward(req,resp); } else { //这句话的意思,是让浏览器用utf8来解析返回的数据 resp.setHeader("Content-type", "text/html;charset=UTF-8"); //这句话的意思,是告诉servlet用UTF-8转码 resp.setCharacterEncoding("UTF-8"); //实现弹窗功能 PrintWriter out=resp.getWriter(); out.print(""); out.flush(); out.close(); } } }
login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%String path=request.getContextPath(); %>还没有账号? /register">注册登录页面 用户登录 用户管理系统
RegisterServlet.java
package Tang.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import Tang.entity.LoginInfo; import Tang.service.LoginInfoService; import Tang.service.impl.LoginInfoServiceImpl; /** * 注册控制器 * @author TZQ * */ @WebServlet("/register") @SuppressWarnings("serial") public class RegisterServlet extends HttpServlet { protected void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException{ req.getRequestDispatcher("/register.jsp").forward(req,resp); } protected void doPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException{ String account= req.getParameter("account"); String password= req.getParameter("password"); LoginInfoService loginInfoService=new LoginInfoServiceImpl(); LoginInfo user=new LoginInfo(); user.setAccount(account); user.setPassword(password); loginInfoService.register(user); req.getRequestDispatcher("/login.jsp").forward(req,resp); } }
register.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%String path=request.getContextPath(); %>用户注册 用户注册 用户管理系统注册
每个人的配置环境不一样遇到的问题也不一样,不是说代码原封不动的复制过去就能运行,遇到问题先百度。上面的代码还是建议跟着Tellsea大佬的教学视频敲一遍,原文链接已经在开头给出。