当前位置:   article > 正文

基于java EE——学生管理系统(超详细,0基础也可)_javaee学生管理系统

javaee学生管理系统

注:项目中首页、登录页面样式均来自bilibili——山羊の前端小窝

jIDEA版本2024最新版

一、项目简介

该项目是一个简单的学生管理系统是一种基于计算机技术实现的学生信息管理工具,能够方便地对学生信息进行录入、查询、修改和删除。该项目基于 JavaEE编写,使用 javaEE和web框架支持,和 oracle 数据库,实现了以上所述的主要功能。

二、项目采用技术

oracle 数据库,WEB技术,Javascript,html,css等。

三、功能需求分析

1.学生信息管理:包括学生姓名、学号、性别等信息。

2.学生查询:管理员可以查询学生的学号、姓名、性别。

3.基本功能:通过数据库实现学生信息的增删改查。

4.注册功能:实现账号注册,登录等功能。

四、项目结构

五、效果演示

(一)欢迎页面

(二)登录/注册页

(三)主页

(四)具体查询页

(五)添加页

六、前期准备

(一)tomcat下载安装及配置教程

确保自己下载了tomcat以及配置,详细如下:

原文链接:https://blog.csdn.net/weixin_47700137/article/details/116055222

(二)oracle 数据库创建数据库表

1.创建账号密码表(账号密码以及学生表可以放到一起,但是不建议)

2.创建创建学生表(项目中只有ID/NAME/AGE有用到,其他可以不用)

(三)JDBC工具包以及驱动配置

1.工具包:

  1. package com.stx.util;
  2. import java.sql.*;
  3. public class JDBCUtil {
  4. private static Connection connection = null;
  5. private static Statement statement = null;
  6. private static ResultSet resultSet = null;
  7. static {
  8. register();
  9. getConnection();
  10. }
  11. //注册驱动
  12. public static void register(){
  13. try {
  14. //oracle的驱动 mysql.jdbc.driver.xx
  15. Class.forName("oracle.jdbc.driver.OracleDriver");
  16. System.out.println("转载驱动完成");
  17. }catch(Exception e) {
  18. e.printStackTrace();
  19. }
  20. }
  21. //建立连接
  22. public static void getConnection(){
  23. try {
  24. // jdbc协议 jdbc:oracle:子版本:@数据库端信息 ip:端口号:数据库名
  25. String url = "jdbc:oracle:thin:@localhost:1521:orcl1";
  26. connection = DriverManager.getConnection(url, "scott", "tiger");
  27. System.out.println("获取连接完毕");
  28. }catch (Exception e){
  29. e.printStackTrace();
  30. }
  31. }
  32. //操作数据
  33. //1.查询
  34. public static ResultSet query(String sql){
  35. try {
  36. if (connection == null) {
  37. getConnection();
  38. }
  39. if (statement == null) {
  40. statement = connection.createStatement();
  41. }
  42. statement = connection.createStatement();
  43. resultSet = statement.executeQuery(sql);
  44. }catch (Exception e){
  45. e.printStackTrace();
  46. }
  47. return resultSet;
  48. }
  49. //2.更新
  50. public static int update(String sql){
  51. int result = -1;
  52. try {
  53. if (connection == null) {
  54. getConnection();
  55. }
  56. if (statement == null) {
  57. statement = connection.createStatement();
  58. }
  59. result = statement.executeUpdate(sql);
  60. }catch (Exception e){
  61. e.printStackTrace();
  62. }
  63. return result;
  64. }
  65. //释放资源
  66. public static void release(){
  67. try {
  68. if (resultSet != null) {
  69. resultSet.close();
  70. resultSet=null;
  71. System.out.println("关闭结果集");
  72. }
  73. if (statement != null) {
  74. statement.close();
  75. statement=null;
  76. System.out.println("关闭执行语句对象");
  77. }
  78. if (connection != null) {
  79. connection.close();//先结果集、statement 、connection 反方向
  80. connection = null;
  81. System.out.println("关闭链接");
  82. }
  83. } catch (SQLException throwables) {
  84. throwables.printStackTrace();
  85. }
  86. System.out.println("释放资源完毕");
  87. }
  88. }

***注意:端口号、账户、密码设置成自己的,大部分端口号为”jdbc:oracle:thin:@localhost:1521:orcl”,此处的orcl后面没有1 ***

***在项目中的位置如下:***

2.将驱动包放到tomact的bin目录下,启动tomacat自动调用驱动(我这里的版本为ojdbc14)

找到tomcat目录里的bin目录

将驱动包直接拖到bin目录下,没有的可以去下载一个,可以从这里下载ojdbc14.jar下载_ojdbc14.jar最新版下载[驱动包软件]-下载之家

七、项目实现

(一)创建项目

1.创建一个java项目

2.点击文件,打开项目结构

3.点击模块,点击web

4.导入tomact依赖

5.点击工件,点击web应用程序:展开型,点击基于模块

6.配置tomcat,点击编辑配置

点击+号,找到tomcat服务器,点击本地

点击部署,导入工件

导入工件点击+工件名

设置上下文为 /点击确认

7.配置首页

点击web.xml配置首页,以及错误页面

  1. <!--配置首页-->
  2. <welcome-file-list>
  3. <welcome-file>
  4. hello.html
  5. </welcome-file>
  6. </welcome-file-list>

点击web,创建一个hello.html和404.html,添加一个一级标题hello

7.启动tomcat跑起来的页面,现在就可以愉快的开始写了

(二)项目代码

我们这里按照层级关系来,首先是首页——注册——登录——主界面(学生列表、添加学生)——查看学生信息——修改学生信息——删除学生信息

1.首页

准备工作:

在src里面建包com.stx为包名,controller为控制器主要写页面逻辑,filter为过滤器为了校验,util为工具包,放工具类,JDBCUtil就是放在里面。

以下的所有jsp和html页面均放在web下面:

涉及到的图片资源:(注意命名)

首先为主页面添加样式:hello.html(上面已经创建过了,建议可以设置成jsp,确保服务器进去就是此页面)

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>学生管理系统</title>
  7. <style>
  8. body{
  9. background-image: url("sbpk.jpg");
  10. background-size: cover;
  11. background-attachment: fixed;
  12. display: flex;
  13. justify-content: center;
  14. }
  15. .a{
  16. position: relative;
  17. top: 180px;
  18. width: 500px;
  19. height: 120px;
  20. border: solid 10px #fff;
  21. box-shadow: 0 0 70px rgb(190,40,210);
  22. display: flex;
  23. justify-content: center;
  24. align-items: center;
  25. /* 设置鼠标移上去时变成小手形状 */
  26. cursor: pointer;
  27. }
  28. .a::after{
  29. content: '';
  30. position: absolute;
  31. width: 500px;
  32. height: 120px;
  33. box-shadow: 0 0 5px rgba(190,40,210);
  34. background-color: rgba(100,30,225,.4);
  35. }
  36. .a:hover{
  37. animation: a 1.5s;
  38. }
  39. @keyframes a{
  40. 0%,34%,68%,100%{
  41. border: solid 10px #fff;
  42. box-shadow: 0 0 70px rgb(190,40,210);
  43. }
  44. 17%,51%,85%{
  45. border: solid 10px rgba(255,0,0,.5);
  46. box-shadow: 0 0 90px rgba(255,0,0,.8);
  47. }
  48. }
  49. .b,.b::before{
  50. z-index: 999;
  51. color: #fff;
  52. position: absolute;
  53. font-size: 65px;
  54. font-weight: 900;
  55. /* 设置字体间距 */
  56. letter-spacing: 12px;
  57. }
  58. .b::before{
  59. content: 'welcome!';
  60. text-shadow: -5px -5px 0px rgb(211,250,9),5px 5px 0px rgb(25,10,240);
  61. /* 使用缩放的方式创建可见显示取余,括号里的四个值分别是toprightbottomleft */
  62. clip-path: inset(100% 0px 0px 0px);
  63. }
  64. .a:hover .b::before{
  65. /* steps设置逐帧动画,值越小越卡顿 */
  66. animation: move 1.25s steps(2);
  67. }
  68. /* 这是制造混乱的位置和高宽,可以自行改变,随机的 */
  69. @keyframes move{
  70. 0%{
  71. clip-path:inset(80% 0px 0px 0px);
  72. transform:translate(-20px,-10px)
  73. }
  74. 10%{
  75. clip-path:inset(10% 0px 85% 0px);
  76. transform:translate(10px,10px)
  77. }
  78. 20%{
  79. clip-path:inset(80% 0px 0px 0px);
  80. transform:translate(-10px,10px)
  81. }
  82. 30%{
  83. clip-path:inset(10% 0px 85% 0px);
  84. transform:translate(0px,5px)
  85. }
  86. 40%{
  87. clip-path:inset(50% 0px 30% 0px);
  88. transform:translate(-5px,0px)
  89. }
  90. 50%{
  91. clip-path:inset(10% 0px 30% 0px);
  92. transform:translate(5px,0px)
  93. }
  94. 60%{
  95. clip-path:inset(40% 0px 30% 0px);
  96. transform:translate(5px,10px)
  97. }
  98. 70%{
  99. clip-path:inset(50% 0px 30% 0px);
  100. transform:translate(-10px,10px)
  101. }
  102. 80%{
  103. clip-path:inset(80% 0px 5% 0px);
  104. transform:translate(20px,-10px)
  105. }
  106. 90%{
  107. clip-path:inset(80% 0px 0px 0px);
  108. transform:translate(-10px,0px)
  109. }
  110. 100%{
  111. clip-path:inset(80% 0px 0px 0px);
  112. transform:translate(0px,0px)
  113. }
  114. }
  115. </style>
  116. </head>
  117. <body>
  118. <div class="a">
  119. <div class="b"><span>
  120. welcome!
  121. </span>
  122. </div>
  123. <div style="margin-top: 200px">
  124. <a href="javascript:void(0);" onclick="goToLogin()">进入</a>
  125. </div>
  126. <script>
  127. // 定义跳转函数
  128. function goToLogin() {
  129. window.location.href = "login.jsp";
  130. }
  131. Math.floor
  132. </script>
  133. </div>
  134. </body>
  135. </html>

2.注册

(1)创建一个注册的页面:register.jsp

  1. <%--
  2. Created by IntelliJ IDEA.
  3. User: 25822
  4. Date: 2024/5/8
  5. Time: 下午4:07
  6. To change this template use File | Settings | File Templates.
  7. --%>
  8. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
  9. <!DOCTYPE html>
  10. <html lang="en">
  11. <head>
  12. <meta charset="UTF-8">
  13. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  14. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  15. <title>登录</title>
  16. <style>
  17. body{
  18. /* 设置背景渐变 */
  19. background-image: linear-gradient(to left,
  20. #9c88ff,#3cadeb);
  21. display: flex;
  22. justify-content: center;
  23. }
  24. .a{
  25. position:relative;
  26. top: 100px;
  27. width: 1100px;
  28. height: 550px;
  29. box-shadow: 0 5px 15px rgba(0,0,0,.8);
  30. display: flex;
  31. }
  32. .b{
  33. width: 800px;
  34. height: 550px;
  35. background-image: url("201515-158211451517f1.jpg");
  36. /* 让图片适应大小 */
  37. background-size: cover;
  38. }
  39. .c{
  40. width: 300px;
  41. height: 550px;
  42. background-color: white;
  43. display: flex;
  44. justify-content: center;
  45. align-items: center;
  46. }
  47. .d{
  48. width: 250px;
  49. height: 500px;
  50. }
  51. .d h1{
  52. font: 900 30px '';
  53. }
  54. .e{
  55. width: 230px;
  56. margin: 20px 0;
  57. outline: none;
  58. border: 0;
  59. padding: 10px;
  60. border-bottom: 3px solid rgb(80,80,170);
  61. font: 900 16px '';
  62. }
  63. .f{
  64. float: right;
  65. margin: 10px 0;
  66. }
  67. .g{
  68. position: absolute;
  69. margin: 20px;
  70. bottom: 40px;
  71. display: block;
  72. width: 200px;
  73. height: 60px;
  74. font: 900 30px '';
  75. text-decoration: none;
  76. line-height: 50px;
  77. border-radius: 30px;
  78. background-image: linear-gradient(to left,
  79. #9c88ff,#3cadeb);
  80. text-align: center;
  81. }
  82. </style>
  83. </head>
  84. <body>
  85. <form action="/register" method="post">
  86. <div class="a">
  87. <div class="b"></div>
  88. <div class="c">
  89. <div class="d">
  90. <h1>Login/Register</h1>
  91. <input type="text" name="username1" class="e" placeholder="用户名">
  92. <input type="password" name="password" class="e" placeholder="密码">
  93. <input type="password" name="password" class="e" placeholder="确认密码">
  94. <input type="submit" class="g" value="确认注册">
  95. </div>
  96. </div>
  97. </div>
  98. </form>
  99. </body>
  100. </html>

(2)创建一个注册的servlet:RegisterServlet

  1. package com.stx.controller;
  2. import com.stx.util.JDBCUtil;
  3. import javax.servlet.ServletException;
  4. import javax.servlet.annotation.WebServlet;
  5. import javax.servlet.http.HttpServlet;
  6. import javax.servlet.http.HttpServletRequest;
  7. import javax.servlet.http.HttpServletResponse;
  8. import java.io.IOException;
  9. //通过注解注册路径
  10. @WebServlet("/register")
  11. public class RegisterServlet extends HttpServlet {
  12. @Override
  13. protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  14. req.setCharacterEncoding("utf-8");
  15. req.getRequestDispatcher("register.jsp").forward(req, resp);
  16. }
  17. @Override
  18. protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  19. req.setCharacterEncoding("utf-8");
  20. //接受提交的数据
  21. String username = req.getParameter("username1");
  22. String password = req.getParameter("password");
  23. System.out.println(username);
  24. //更新到数据库
  25. JDBCUtil.update("INSERT INTO register (name,password) VALUES ('" + username + "', '" + password + "')");
  26. //跳转到列表页面
  27. //需要存数据到request对象,用forward
  28. //req.getRequestDispatcher("/studentlist").forward(req, resp);
  29. //不需要带数据跳转,可以用sendRedirect response对象是新的
  30. resp.sendRedirect("/login.jsp");
  31. }
  32. }

注册的账户密码通过from表单的post方法提交到RegisterServlet,再在RegisterServlet通过JDBC的工具类把值新增到数据库中,然后跳转到login.jsp页面即登录页面

3.登录

(1)创建一个登录的jsp:login.jsp

  1. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
  2. <!DOCTYPE html>
  3. <html lang="en">
  4. <head>
  5. <meta charset="UTF-8">
  6. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  7. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  8. <title>登录</title>
  9. <style>
  10. body{
  11. /* 设置背景渐变 */
  12. background-image: linear-gradient(to left,
  13. #9c88ff,#3cadeb);
  14. display: flex;
  15. justify-content: center;
  16. }
  17. .a{
  18. position:relative;
  19. top: 100px;
  20. width: 1100px;
  21. height: 550px;
  22. box-shadow: 0 5px 15px rgba(0,0,0,.8);
  23. display: flex;
  24. }
  25. .b{
  26. width: 800px;
  27. height: 550px;
  28. background-image: url("201515-158211451517f1.jpg");
  29. /* 让图片适应大小 */
  30. background-size: cover;
  31. }
  32. .c{
  33. width: 300px;
  34. height: 550px;
  35. background-color: white;
  36. display: flex;
  37. justify-content: center;
  38. align-items: center;
  39. }
  40. .d{
  41. width: 250px;
  42. height: 500px;
  43. }
  44. .d h1{
  45. font: 900 30px '';
  46. }
  47. .e{
  48. width: 230px;
  49. margin: 20px 0;
  50. outline: none;
  51. border: 0;
  52. padding: 10px;
  53. border-bottom: 3px solid rgb(80,80,170);
  54. font: 900 16px '';
  55. }
  56. .f{
  57. float: right;
  58. margin: 10px 0;
  59. }
  60. .g{
  61. position: absolute;
  62. margin: 20px;
  63. bottom: 40px;
  64. display: block;
  65. width: 200px;
  66. height: 60px;
  67. font: 900 30px '';
  68. text-decoration: none;
  69. line-height: 50px;
  70. border-radius: 30px;
  71. background-image: linear-gradient(to left,
  72. #9c88ff,#3cadeb);
  73. text-align: center;
  74. }
  75. </style>
  76. <title>Login Page</title>
  77. </head>
  78. <body>
  79. <form action="/login" method="post">
  80. <div class="a">
  81. <div class="b"></div>
  82. <div class="c">
  83. <div class="d">
  84. <h1>Login/Register</h1>
  85. <input type="text" name="username" class="e" placeholder="用户名">
  86. <input type="password" name="password" class="e" placeholder="密码">
  87. <a href="javascript:void(0);" onclick="goToLogin()" class="f">点击注册</a>
  88. <a href="#" class="f">忘记密码?</a>
  89. <input type="submit" class="g" onClick="return validateForm();"/>
  90. </div>
  91. </div>
  92. </div>
  93. </form>
  94. <script>
  95. // 页面加载完成后检查errorMsg是否存在,并弹出警告框
  96. window.onload = function() {
  97. var errorMsg = getQueryVariable('errorMsg');
  98. if (errorMsg) {
  99. alert(errorMsg);
  100. }
  101. };
  102. // 函数:从URL查询字符串中获取指定参数的值
  103. function getQueryVariable(variable) {
  104. var query = window.location.search.substring(1);
  105. var vars = query.split("&");
  106. for (var i=0;i<vars.length;i++) {
  107. var pair = vars[i].split("=");
  108. if(pair[0] == variable){return pair[1];}
  109. }
  110. return(false);
  111. }
  112. //跳转注册
  113. function goToLogin() {
  114. window.location.href = "register.jsp";
  115. };
  116. // 定义表单验证和提交函数
  117. function validateForm() {
  118. var username = document.getElementsByName('username')[0].value;
  119. var password = document.getElementsByName('password')[0].value;
  120. // 前端验证
  121. if(username.trim() === '') {
  122. alert('用户名不能为空!');
  123. return false;
  124. }
  125. if(password.trim() === '') {
  126. alert('密码不能为空!');
  127. return false;
  128. }
  129. // 如果验证通过,手动提交表单
  130. document.getElementById('loginForm').submit();
  131. }
  132. </script>
  133. </body>
  134. </html>

对密码进行一些简单的验证,用户名和密码不能为空,并且账号或密码错误时会弹出来error

(2)创建一个LoginServlet

  1. package com.stx.controller;
  2. import com.stx.util.JDBCUtil;
  3. import javax.servlet.ServletException;
  4. import javax.servlet.annotation.WebServlet;
  5. import javax.servlet.http.HttpServlet;
  6. import javax.servlet.http.HttpServletRequest;
  7. import javax.servlet.http.HttpServletResponse;
  8. import javax.servlet.http.HttpSession;
  9. import java.io.IOException;
  10. import java.net.URLEncoder;
  11. import java.sql.ResultSet;
  12. import java.sql.SQLException;
  13. @WebServlet("/login")
  14. public class LoginServlet extends HttpServlet {
  15. @Override
  16. protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  17. super.doGet(req, resp);
  18. }
  19. @Override
  20. protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  21. req.setCharacterEncoding("utf-8");
  22. String username = req.getParameter("username");
  23. String password = req.getParameter("password");
  24. String sql = "select * from register where name='"+username+"' and password='"+password+"'";
  25. System.out.println(sql);
  26. ResultSet query = JDBCUtil.query(sql);
  27. try {
  28. if (query.next()) {
  29. // 登录成功,转发到主页
  30. req.getRequestDispatcher("home.jsp").forward(req, resp);
  31. } else {
  32. // 登录失败,设置错误信息并重定向回登录页面,附带错误信息参数
  33. String errorMsgEncoded = URLEncoder.encode("error", "UTF-8");
  34. resp.sendRedirect(req.getContextPath() + "/login.jsp?errorMsg=" + errorMsgEncoded);
  35. }
  36. } catch (SQLException e) {
  37. throw new RuntimeException(e);
  38. }
  39. //解决乱码
  40. resp.setContentType("text/html");
  41. // req.setCharacterEncoding("utf-8");
  42. // //业务逻辑 判断校验登录密码
  43. // String username = req.getParameter("username");
  44. // String password = req.getParameter("password");
  45. // String html ="<html lang=\"en\">\n" +
  46. // "<head>\n" +
  47. // " <meta charset=\"UTF-8\">\n" +
  48. // " <title>Title</title>\n" +
  49. // "</head>\n" +
  50. // "<body>\n" +
  51. // "<h1>why</h1>\n" +
  52. // "</body>\n" +
  53. // "</html>";
  54. // //数据库查找比对
  55. // if (username.equals("admin") && password.equals("123")) {
  56. String name = "尊贵的管理员";
  57. // // resp.getWriter().write(html);
  58. //
  59. // //session 生命周期
  60. // //1.用户浏览器窗口关闭,会话结束
  61. // //2.会话有效期 设置有效期过了 数据清空
  62. HttpSession session = req.getSession();
  63. session.setMaxInactiveInterval(3600);//默认半小时,单位是秒
  64. //获取session来保存会话数据 request
  65. session.setAttribute("user", name);
  66. // //转发到前端页面
  67. // //request
  68. // //数据存进去,在jsp页面再取出来
  69. // req.setAttribute("name", name);//存 键值对 数据 到 requset对象
  70. // //数据通过requset对象 转发到前端jsp页面
  71. // req.getRequestDispatcher("home.jsp").forward(req, resp);
  72. // }
  73. }
  74. }

同样,login.jsp通过表单提交到LoginServlet,在里面进行校验,首先从数据库里面查询账号和密码相对于的值,如果有则通过验证,转发到主页即home.jsp,登录失败,设置错误信息并重定向回登录页面,附带错误信息参数。

4.主页

(1)首先创建一个home.jsp设置主页的样式

  1. <%--
  2. Created by IntelliJ IDEA.
  3. User: 25822
  4. Date: 2024/5/7
  5. Time: 下午8:38
  6. To change this template use File | Settings | File Templates.
  7. --%>
  8. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
  9. <!DOCTYPE html>
  10. <html lang="en">
  11. <head>
  12. <meta charset="UTF-8">
  13. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  14. <title>学生管理系统</title>
  15. <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.0/css/all.min.css" integrity="sha384-KyZXEAg3QhqLMpG8r+Knujsl5/1L_dstPt3HV5HzF6Gvk/e3s2qWwVWq6Qc0ZuH+" crossorigin="anonymous" />
  16. <style>
  17. * {
  18. box-sizing: border-box;
  19. margin: 0;
  20. padding: 0;
  21. }
  22. body {
  23. font-family: 'Segoe UI', Arial, sans-serif;
  24. line-height: 1.6;
  25. color: #333;
  26. background-color: #f8f9fa;
  27. }
  28. .container {
  29. max-width: 1200px;
  30. margin: 0 auto;
  31. padding: 20px;
  32. height: 100%;
  33. }
  34. header {
  35. background-color: #007bff;
  36. color: white;
  37. padding: 20px;
  38. display: flex;
  39. justify-content: space-between;
  40. align-items: center;
  41. }
  42. header a {
  43. color: white;
  44. text-decoration: none;
  45. transition: color 0.3s ease;
  46. }
  47. header a:hover {
  48. color: rgba(255, 255, 255, 0.8);
  49. }
  50. nav ul {
  51. list-style-type: none;
  52. padding: 0;
  53. }
  54. nav li {
  55. margin-bottom: 10px;
  56. }
  57. nav a {
  58. display: block;
  59. padding: 10px 20px;
  60. text-decoration: none;
  61. color: #333;
  62. background-color: #e9ecef;
  63. border-radius: 5px;
  64. transition: background-color 0.3s ease;
  65. }
  66. nav a:hover, nav a.active {
  67. background-color: #007bff;
  68. color: white;
  69. }
  70. .main-content {
  71. display: flex;
  72. margin-top: 30px;
  73. margin-left: 250px;
  74. }
  75. .sidebar {
  76. width: 20%;
  77. min-width: 250px;
  78. border-right: 1px solid #dee2e6;
  79. }
  80. .content-area {
  81. width: 100%;
  82. height: 100%;
  83. }
  84. iframe {
  85. width: 100%;
  86. border: none;
  87. height: 500px;
  88. }
  89. footer {
  90. background-color: #007bff;
  91. color: white;
  92. text-align: center;
  93. padding: 20px;
  94. margin-top: 30px;
  95. }
  96. @media (max-width: 768px) {
  97. .main-content {
  98. flex-direction: column;
  99. }
  100. .sidebar, .content-area {
  101. width: 100%;
  102. border: none;
  103. margin-bottom: 20px;
  104. }
  105. }
  106. </style>
  107. </head>
  108. <body>
  109. <div class="container">
  110. <header>
  111. <h1>学生管理系统</h1>
  112. <a href="logout" class="logout-link">退出 <i class="fas fa-sign-out-alt"></i></a>
  113. </header>
  114. <nav class="sidebar">
  115. <ul>
  116. <li><a href="studentlist" target="contentFrame" class="active">学生列表</a></li>
  117. <li><a href="studentadd" target="contentFrame">添加学生</a></li>
  118. </ul>
  119. </nav>
  120. <div class="main-content">
  121. <div class="content-area">
  122. <iframe name="contentFrame" id="contentFrame"></iframe>
  123. </div>
  124. </div>
  125. <footer>版权所有 &copy; 2024 学生管理系统</footer>
  126. </div>
  127. <script>
  128. // JavaScript to handle active link state if needed
  129. document.querySelectorAll('nav a').forEach(link => {
  130. link.addEventListener('click', function() {
  131. document.querySelectorAll('nav a').forEach(l => l.classList.remove('active'));
  132. this.classList.add('active');
  133. });
  134. });
  135. </script>
  136. </body>
  137. </html>

主页只是一个页面,不需要逻辑,则不需要创建servlet,但是主页需要通过超链接跳到学生列表和添加学生的页面,还需要退出,退出则到登录页面,如下图:

我们这里先写退出的逻辑:LogoutServlet

  1. package com.stx.controller;
  2. import javax.servlet.ServletException;
  3. import javax.servlet.annotation.WebServlet;
  4. import javax.servlet.http.HttpServlet;
  5. import javax.servlet.http.HttpServletRequest;
  6. import javax.servlet.http.HttpServletResponse;
  7. import javax.servlet.http.HttpSession;
  8. import java.io.IOException;
  9. @WebServlet("/logout")
  10. public class LogoutServlet extends HttpServlet {
  11. @Override
  12. protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  13. req.setCharacterEncoding("utf-8");
  14. //退出系统 清空session
  15. HttpSession session = req.getSession();
  16. //session.removeAttribute("uesr");//删除指定数据
  17. session.invalidate();//直接失效
  18. //跳转到登录页面
  19. resp.sendRedirect("/login.jsp");
  20. }
  21. @Override
  22. protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  23. super.doPost(req, resp);
  24. }
  25. }

5.学生列表

(1)首先创建一个学生列表的jsp页面:studentlist.jsp

  1. <%@ page import="com.stx.controller.Student" %>
  2. <%@ page import="java.util.List" %>
  3. <%--
  4. Created by IntelliJ IDEA.
  5. User: 25822
  6. Date: 2024/5/7
  7. Time: 下午8:41
  8. To change this template use File | Settings | File Templates.
  9. --%>
  10. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
  11. <meta charset="UTF-8">
  12. <html>
  13. <head>
  14. <title>Title</title>
  15. <style>
  16. table {
  17. border: 1px solid black;
  18. border-collapse: collapse;
  19. }
  20. th, td {
  21. border: 1px solid black;
  22. }
  23. </style>
  24. <script>
  25. function confirmDelete(id) {
  26. if (confirm("是否确认删除id为" + id + "的记录?")) {
  27. // 确认删除,使用window.location.href进行页面跳转来执行删除操作
  28. window.location.href = "studentdelete?id=" + id;
  29. }
  30. }
  31. </script>
  32. </head>
  33. <body>
  34. <%
  35. List list = (List)request.getAttribute("list");
  36. %>
  37. <table cellpadding="1" cellspacing="0" width="500px" align="center">
  38. <caption>学生数据</caption>
  39. <th bgcolor="#ffc0cb">姓名</th>
  40. <th>年龄</th>
  41. <th>ID</th>
  42. <th>操作</th>
  43. <!--jsp代码可以打断包含html代码-->
  44. <%
  45. for (int i = 0; i < list.size(); i++){
  46. Student student = (Student)list.get(i);
  47. %>
  48. <tr>
  49. <td align="center" height="40px"><%= student.getName() %></td>
  50. <td align="center" height="40px"><%= student.getAge() %></td>
  51. <td align="center" height="40px"><%= student.getId() %></td>
  52. <td align="center" height="40px">
  53. <!-- 使用JavaScript函数confirmDelete来处理删除确认 -->
  54. <a href="#" onclick="confirmDelete('<%= student.getId()%>')">删除</a>
  55. <a href="studentview?id=<%= student.getId()%>">查看</a>
  56. <a href="studentmodify?id=<%= student.getId()%>">修改</a>
  57. </td>
  58. </tr>
  59. <%
  60. }
  61. %>
  62. </table>
  63. </body>
  64. </html>

列表页面上会包含删除,具体学生信息的查看和修改,我们这里先完成整个学生列表的显示。

(2)创建一个StudentServlet,用于从数据库拿去数据并显示到studentlist.jsp页面之上

  1. package com.stx.controller;
  2. import com.stx.util.JDBCUtil;
  3. import java.io.IOException;
  4. import java.sql.ResultSet;
  5. import java.util.ArrayList;
  6. import java.util.List;
  7. import javax.servlet.ServletException;
  8. import javax.servlet.annotation.WebServlet;
  9. import javax.servlet.http.HttpServlet;
  10. import javax.servlet.http.HttpServletRequest;
  11. import javax.servlet.http.HttpServletResponse;
  12. @WebServlet("/studentlist")
  13. public class StudentServlet extends HttpServlet {
  14. @Override
  15. protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  16. req.setCharacterEncoding("utf-8");
  17. //改用filter过滤器,全局校验
  18. //判断用户是否登录过 通过sesseion取登录之后存数据
  19. // HttpSession session = req.getSession();
  20. // String name = (String) session.getAttribute("user");//返回的是object,需要强转
  21. // if (name == null) {
  22. // //要么没有登录,要么超时了
  23. // //需要重新登录,跳转到登录页面,可以通过转发即:
  24. // //req.getRequestDispatcher("studentlist.jsp").forward(req, resp);
  25. // //也可以页面重定向 让用户重新发出请求(相当于浏览器重新访问):
  26. // resp.sendRedirect("/login.jsp");
  27. // return;
  28. // }
  29. //获取数据库的数据
  30. ResultSet resultSet = JDBCUtil.query("select * from student");
  31. List<Student> list = null;
  32. try {
  33. //数据封装到集合里面去,返回给前端jsp页面
  34. list = new ArrayList();
  35. while (resultSet.next()) {
  36. Student student = new Student();
  37. student.setName(resultSet.getString("name"));
  38. student.setAge(resultSet.getInt("age"));
  39. student.setId(resultSet.getString("Id"));
  40. list.add(student);
  41. }
  42. System.out.println("获取的数据:" + list.size());
  43. } catch (Exception e) {
  44. // 处理异常,至少打印出来,实际应用中应该有更详细的日志记录
  45. e.printStackTrace();
  46. }
  47. //存到resqust对象
  48. req.setAttribute("list", list);
  49. //转发到jsp
  50. req.getRequestDispatcher("studentlist.jsp").forward(req, resp);
  51. }
  52. @Override
  53. protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  54. super.doPost(req, resp);
  55. }
  56. }

这里不仅需要存取到数据库,还需要存到学生列表里,方便取出,列表提供了丰富的API(如迭代、添加、删除等操作),使得在后续的业务处理中,可以方便地遍历和操作这些数据。

(3)创建一个student类

  1. package com.stx.controller;
  2. public class Student {
  3. public String name;
  4. public int age;
  5. public String id;
  6. public String getName() {
  7. return name;
  8. }
  9. public void setName(String name) {
  10. this.name = name;
  11. }
  12. public int getAge() {
  13. return age;
  14. }
  15. public void setAge(int age) {
  16. this.age = age;
  17. }
  18. public String getId() {
  19. return id;
  20. }
  21. public void setId(String id) {
  22. this.id = id;
  23. }
  24. }

此时页面上已经有学生数据,如下,我们再完成查看,删除和修改的功能

6.查看学生信息

(1)创建一个studentlist.jsp页面,用来显示学生具体信息,我这里只有名字,年龄和ID想要更多可以自己加一下

  1. <%@ page import="com.stx.controller.Student" %>
  2. <%--
  3. Created by IntelliJ IDEA.
  4. User: 25822
  5. Date: 2024/5/7
  6. Time: 下午8:44
  7. To change this template use File | Settings | File Templates.
  8. --%>
  9. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
  10. <html>
  11. <head>
  12. <title>Title</title>
  13. <style>
  14. table {
  15. border: 1px solid black;
  16. border-collapse: collapse;
  17. }
  18. th, td {
  19. border: 1px solid black;
  20. }
  21. </style>
  22. </head>
  23. <body>
  24. <% Student student = (Student) request.getAttribute("student");%>
  25. <table cellpadding="1" cellspacing="0" width="500px" align="center">
  26. <caption>学生数据</caption>
  27. <th bgcolor="#ffc0cb">姓名</th>
  28. <th>年龄</th>
  29. <th>ID</th>
  30. <!--jsp代码可以打断包含html代码-->
  31. <tr>
  32. <td align="center" height="40px"><%= student.getName() %></td>
  33. <td align="center" height="40px"><%= student.getAge() %></td>
  34. <td align="center" height="40px"><%= student.getId() %></td>
  35. </tr>
  36. </table><br>
  37. <!--返回上一层页面-->
  38. <input type="button" value="返回" onclick="history.back()">
  39. </body>
  40. </html>

(2)创建一个StudentVServlet用于从数据库提取数据,并返回给前端页面

  1. package com.stx.controller;
  2. import com.stx.util.JDBCUtil;
  3. import javax.servlet.ServletException;
  4. import javax.servlet.annotation.WebServlet;
  5. import javax.servlet.http.HttpServlet;
  6. import javax.servlet.http.HttpServletRequest;
  7. import javax.servlet.http.HttpServletResponse;
  8. import java.io.IOException;
  9. import java.sql.ResultSet;
  10. @WebServlet("/studentview")
  11. public class StudentViewServlet extends HttpServlet {
  12. @Override
  13. protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  14. req.setCharacterEncoding("utf-8");
  15. //获取学生数据
  16. String id = req.getParameter("id");
  17. ResultSet resultSet = JDBCUtil.query("select * from student where id =" +id);
  18. try {
  19. //数据封装到集合里面去,返回给前端jsp页面
  20. if (resultSet.next()) {
  21. Student student = new Student();
  22. student.setName(resultSet.getString("name"));
  23. student.setAge(resultSet.getInt("age"));
  24. student.setId(resultSet.getString("id"));
  25. req.setAttribute("student", student);//查询出来的对象,存到request对象
  26. }
  27. } catch (Exception e) {
  28. // 处理异常,至少打印出来,实际应用中应该有更详细的日志记录
  29. e.printStackTrace();
  30. }
  31. req.getRequestDispatcher("studentview.jsp").forward(req, resp);
  32. }
  33. @Override
  34. protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  35. super.doPost(req, resp);
  36. }
  37. }

7.修改学生信息

(1)创建一个studentmodify.jsp页面用于向后端提交修改后的值

  1. <%@ page import="com.stx.controller.Student" %>
  2. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
  3. <!-- 省略其他头部信息 -->
  4. </html>
  5. <head>
  6. <title>Title</title>
  7. <meta charset="UTF-8">
  8. </head>
  9. <body>
  10. <% Student student = (Student) request.getAttribute("student");%>
  11. <form action="/studentmodify" method="post" onsubmit="return checkContent()">
  12. <table>
  13. <tr>
  14. <td><label for="name">姓名:</label></td>
  15. <td><input type="text" id="name" name="name" value="<%= student.getName() %>" onfocus="checkName()"></td>
  16. </tr>
  17. <tr>
  18. <td><label for="age">年龄:</label></td>
  19. <td><input type="text" id="age" name="age" value="<%= student.getAge() %>" onfocus="checkAge()"></td>
  20. </tr>
  21. <tr>
  22. <td><label for="id">ID:</label></td>
  23. <td><input type="text" id="id" name="id" value="<%= student.getId() %>" onfocus="checkId()"></td>
  24. </tr>
  25. </table><br>
  26. <input type="submit" value="提交">
  27. <input type="reset" value="重置">
  28. </form>
  29. <script>
  30. function checkContent() {
  31. // 实现整体验证逻辑
  32. return true; // 返回true允许提交,false阻止提交
  33. }
  34. function checkName() {
  35. // 实现姓名验证逻辑
  36. }
  37. function checkAge() {
  38. // 实现年龄验证逻辑
  39. }
  40. function checkId() {
  41. // 实现ID验证逻辑
  42. }
  43. </script>
  44. </body>
  45. </html>

(2)创建一个StudentUpdateServlet用于接受前端数据,并通过JDBC工具类修改,更新到数据库

  1. package com.stx.controller;
  2. import com.stx.util.JDBCUtil;
  3. import javax.servlet.ServletException;
  4. import javax.servlet.annotation.WebServlet;
  5. import javax.servlet.http.HttpServlet;
  6. import javax.servlet.http.HttpServletRequest;
  7. import javax.servlet.http.HttpServletResponse;
  8. import javax.servlet.http.HttpSession;
  9. import java.io.IOException;
  10. import java.sql.ResultSet;
  11. @WebServlet("/studentmodify")
  12. public class StudentUpdateServlet extends HttpServlet {
  13. @Override
  14. protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  15. req.setCharacterEncoding("utf-8");
  16. //改用filter过滤器,全局校验
  17. // HttpSession session = req.getSession();
  18. // String name = (String) session.getAttribute("user");//返回的是object,需要强转
  19. // if (name == null) {
  20. // //要么没有登录,要么超时了
  21. // //需要重新登录,跳转到登录页面,可以通过转发即:
  22. // //req.getRequestDispatcher("studentlist.jsp").forward(req, resp);
  23. // //也可以页面重定向 让用户重新发出请求(相当于浏览器重新访问):
  24. // resp.sendRedirect("/login.jsp");
  25. // return;
  26. // }
  27. //获取学生数据
  28. String id = req.getParameter("id");
  29. ResultSet resultSet = JDBCUtil.query("select * from student where id =" +id);
  30. try {
  31. //数据封装到集合里面去,返回给前端jsp页面
  32. if (resultSet.next()) {
  33. Student student = new Student();
  34. student.setName(resultSet.getString("name"));
  35. student.setAge(resultSet.getInt("age"));
  36. student.setId(resultSet.getString("id"));
  37. req.setAttribute("student", student);//查询出来的对象,存到request对象
  38. }
  39. } catch (Exception e) {
  40. // 处理异常,至少打印出来,实际应用中应该有更详细的日志记录
  41. e.printStackTrace();
  42. }
  43. req.getRequestDispatcher("studentmodify.jsp").forward(req, resp);
  44. }
  45. @Override
  46. protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  47. req.setCharacterEncoding("utf-8");
  48. //接受提交的数据
  49. String id = req.getParameter("id");
  50. String name = req.getParameter("name");
  51. String age = req.getParameter("age");
  52. //更新到数据库
  53. String sql = "update student set name='"+name+"',age='"+age+"',id='"+id+"' where id="+id;
  54. JDBCUtil.update(sql);
  55. //跳转到列表页面
  56. //需要存数据到request对象,用forward
  57. // req.getRequestDispatcher("/studentlist").forward(req, resp);
  58. //不需要带数据跳转,可以用sendRedirect response对象是新的
  59. resp.sendRedirect("/studentlist");
  60. }
  61. }

8.删除学生信息

删除信息不需要前端页面,只需要在学生列表上面直接删除

创建一个StudentDeleteServlet

  1. package com.stx.controller;
  2. import com.stx.util.JDBCUtil;
  3. import javax.servlet.ServletException;
  4. import javax.servlet.annotation.WebServlet;
  5. import javax.servlet.http.HttpServlet;
  6. import javax.servlet.http.HttpServletRequest;
  7. import javax.servlet.http.HttpServletResponse;
  8. import java.io.IOException;
  9. @WebServlet("/studentdelete")
  10. public class StudentDeleteServlet extends HttpServlet {
  11. @Override
  12. protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  13. //删除逻辑
  14. String id = req.getParameter("id");
  15. JDBCUtil.update("delete from student where id="+id);
  16. //跳转到列表页面
  17. resp.sendRedirect("/studentlist");
  18. }
  19. @Override
  20. protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  21. }
  22. }

9.最后添加学生

(1)创建一个添加页面studentadd.jsp

  1. <%@ page import="com.stx.controller.Student" %>
  2. <%--
  3. Created by IntelliJ IDEA.
  4. User: 25822
  5. Date: 2024/5/8
  6. Time: 上午11:47
  7. To change this template use File | Settings | File Templates.
  8. --%>
  9. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
  10. <!DOCTYPE html>
  11. <html lang="en">
  12. <head>
  13. <meta charset="UTF-8">
  14. <style>
  15. .content-area {
  16. display: flex;
  17. justify-content: center;
  18. align-items: center;
  19. flex-direction: column;
  20. height: 100%;
  21. padding: 20px;
  22. }
  23. form {
  24. width: 100%;
  25. max-width: 400px; /* 限制表单最大宽度,适应不同屏幕 */
  26. padding: 20px;
  27. background-color: #ffffff;
  28. border-radius: 5px;
  29. box-shadow: 0 0 10px rgba(0,0,0,0.1);
  30. }
  31. </style>
  32. </head>
  33. <body>
  34. <div class="main-content">
  35. <div class="content-area">
  36. <form action="/studentadd" method="post" onsubmit="return checkContent()">
  37. <table>
  38. <tr>
  39. <td><label for="name">姓名:</label></td>
  40. <td><input type="text" id="name" name="name" onfocus="checkName()"></td>
  41. </tr>
  42. <tr>
  43. <td><label for="age">年龄:</label></td>
  44. <td><input type="text" id="age" name="age" onfocus="checkAge()"></td>
  45. </tr>
  46. <tr>
  47. <td><label for="id">ID:</label></td>
  48. <td><input type="text" id="id" name="id" onfocus="checkId()"></td>
  49. </tr>
  50. </table><br>
  51. <input type="submit" value="提交">
  52. <input type="reset" value="重置">
  53. </form>
  54. </div>
  55. </div>
  56. <script>
  57. </script>
  58. </body>
  59. </html>

(2)创建StudentAddServlet,把数据插入到数据库

  1. package com.stx.controller;
  2. import com.stx.util.JDBCUtil;
  3. import javax.servlet.ServletException;
  4. import javax.servlet.annotation.WebServlet;
  5. import javax.servlet.http.HttpServlet;
  6. import javax.servlet.http.HttpServletRequest;
  7. import javax.servlet.http.HttpServletResponse;
  8. import java.io.IOException;
  9. @WebServlet("/studentadd")
  10. public class StudentAddServlet extends HttpServlet {
  11. @Override
  12. protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  13. req.getRequestDispatcher("studentadd.jsp").forward(req, resp);
  14. }
  15. @Override
  16. protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  17. req.setCharacterEncoding("utf-8");
  18. //接受提交的数据
  19. String id = req.getParameter("id");
  20. String name = req.getParameter("name");
  21. String age = req.getParameter("age");
  22. //更新到数据库
  23. JDBCUtil.update("INSERT INTO student (id, age, name) VALUES ('" + id + "', '" + age + "', '" + name + "')");
  24. //跳转到列表页面
  25. //需要存数据到request对象,用forward
  26. // req.getRequestDispatcher("/studentlist").forward(req, resp);
  27. //不需要带数据跳转,可以用sendRedirect response对象是新的
  28. resp.sendRedirect("/studentlist");
  29. }
  30. }

10.最后设置过滤器,避免直接跳过登录页面直接进入到学生列表里面,完善登录功能

在filter的包里面,创建过滤器

  1. package com.stx.filter;
  2. import javax.servlet.*;
  3. import javax.servlet.annotation.WebFilter;
  4. import javax.servlet.http.HttpServletRequest;
  5. import javax.servlet.http.HttpServletResponse;
  6. import javax.servlet.http.HttpSession;
  7. import java.io.IOException;
  8. //过滤哪些地址
  9. @WebFilter("/*")
  10. public class LoginFilter implements Filter {//接口
  11. @Override
  12. public void init(FilterConfig filterConfig) throws ServletException {
  13. }
  14. @Override
  15. public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
  16. HttpServletRequest req = (HttpServletRequest) servletRequest;
  17. HttpServletResponse resp = (HttpServletResponse) servletResponse;
  18. //过滤器的逻辑控制方法
  19. //判断所有需要登录的地址,用户是否已经正常登录
  20. //判断用户是否登录过 通过session 取登录之后的存数据
  21. //判断后台数据操作才需要 判断是否登录
  22. //URI和URL区别 /login.jsp http://localhost:8080/login.html
  23. String uri = req.getRequestURI();
  24. String url = req.getRequestURL().toString();
  25. System.out.println(url);
  26. //取上下文路径
  27. //排除掉不需要的地址
  28. if (!uri.equals("/")&&!url.contains("login")&&!url.contains("register")) {//登录页面不需要校验
  29. HttpSession session = req.getSession(); // 这里也应使用request,而非req
  30. String name = (String) session.getAttribute("user"); // 返回的是Object,需要强转
  31. if (name == null) {
  32. // 要么没有登录,要么超时了
  33. // 需要重新登录,跳转到登录页面,可以通过转发即:
  34. // request.getRequestDispatcher("studentlist.jsp").forward(request, response);
  35. // 也可以页面重定向 让用户重新发出请求(相当于浏览器重新访问):
  36. //要取完整的项目部署路径
  37. resp.sendRedirect("/login.jsp");
  38. return;
  39. }
  40. }
  41. filterChain.doFilter(servletRequest, servletResponse);
  42. }
  43. @Override
  44. public void destroy() {
  45. }
  46. }

过滤掉除了登录页面之外的所有页面,如果直接进入,则会转发到登录页面,至此一个简单的学生管理系统,基本功能实

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/776733
推荐阅读
相关标签
  

闽ICP备14008679号