赞
踩
注:项目中首页、登录页面样式均来自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.工具包:
- package com.stx.util;
-
- import java.sql.*;
-
- public class JDBCUtil {
- private static Connection connection = null;
- private static Statement statement = null;
- private static ResultSet resultSet = null;
-
- static {
- register();
- getConnection();
- }
-
- //注册驱动
- public static void register(){
- try {
- //oracle的驱动 mysql.jdbc.driver.xx
- Class.forName("oracle.jdbc.driver.OracleDriver");
- System.out.println("转载驱动完成");
- }catch(Exception e) {
- e.printStackTrace();
- }
- }
-
- //建立连接
- public static void getConnection(){
- try {
- // jdbc协议 jdbc:oracle:子版本:@数据库端信息 ip:端口号:数据库名
- String url = "jdbc:oracle:thin:@localhost:1521:orcl1";
- connection = DriverManager.getConnection(url, "scott", "tiger");
- System.out.println("获取连接完毕");
- }catch (Exception e){
- e.printStackTrace();
- }
- }
-
- //操作数据
- //1.查询
- public static ResultSet query(String sql){
- try {
- if (connection == null) {
- getConnection();
- }
- if (statement == null) {
- statement = connection.createStatement();
- }
- statement = connection.createStatement();
- resultSet = statement.executeQuery(sql);
- }catch (Exception e){
- e.printStackTrace();
- }
- return resultSet;
- }
-
- //2.更新
- public static int update(String sql){
- int result = -1;
- try {
- if (connection == null) {
- getConnection();
- }
- if (statement == null) {
- statement = connection.createStatement();
- }
- result = statement.executeUpdate(sql);
- }catch (Exception e){
- e.printStackTrace();
- }
- return result;
- }
-
- //释放资源
- public static void release(){
- try {
- if (resultSet != null) {
- resultSet.close();
- resultSet=null;
- System.out.println("关闭结果集");
- }
- if (statement != null) {
- statement.close();
- statement=null;
- System.out.println("关闭执行语句对象");
- }
- if (connection != null) {
- connection.close();//先结果集、statement 、connection 反方向
- connection = null;
- System.out.println("关闭链接");
- }
- } catch (SQLException throwables) {
- throwables.printStackTrace();
- }
- System.out.println("释放资源完毕");
- }
- }

***注意:端口号、账户、密码设置成自己的,大部分端口号为”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配置首页,以及错误页面
- <!--配置首页-->
- <welcome-file-list>
- <welcome-file>
- hello.html
- </welcome-file>
- </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,确保服务器进去就是此页面)
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>学生管理系统</title>
- <style>
- body{
- background-image: url("sbpk.jpg");
- background-size: cover;
- background-attachment: fixed;
- display: flex;
- justify-content: center;
- }
- .a{
- position: relative;
- top: 180px;
- width: 500px;
- height: 120px;
- border: solid 10px #fff;
- box-shadow: 0 0 70px rgb(190,40,210);
- display: flex;
- justify-content: center;
- align-items: center;
- /* 设置鼠标移上去时变成小手形状 */
- cursor: pointer;
- }
- .a::after{
- content: '';
- position: absolute;
- width: 500px;
- height: 120px;
- box-shadow: 0 0 5px rgba(190,40,210);
- background-color: rgba(100,30,225,.4);
- }
- .a:hover{
- animation: a 1.5s;
- }
- @keyframes a{
- 0%,34%,68%,100%{
- border: solid 10px #fff;
- box-shadow: 0 0 70px rgb(190,40,210);
- }
- 17%,51%,85%{
- border: solid 10px rgba(255,0,0,.5);
- box-shadow: 0 0 90px rgba(255,0,0,.8);
- }
- }
- .b,.b::before{
- z-index: 999;
- color: #fff;
- position: absolute;
- font-size: 65px;
- font-weight: 900;
- /* 设置字体间距 */
- letter-spacing: 12px;
- }
- .b::before{
- content: 'welcome!';
- text-shadow: -5px -5px 0px rgb(211,250,9),5px 5px 0px rgb(25,10,240);
- /* 使用缩放的方式创建可见显示取余,括号里的四个值分别是top,right,bottom,left */
- clip-path: inset(100% 0px 0px 0px);
-
- }
- .a:hover .b::before{
- /* steps设置逐帧动画,值越小越卡顿 */
- animation: move 1.25s steps(2);
- }
- /* 这是制造混乱的位置和高宽,可以自行改变,随机的 */
- @keyframes move{
- 0%{
- clip-path:inset(80% 0px 0px 0px);
- transform:translate(-20px,-10px)
- }
- 10%{
- clip-path:inset(10% 0px 85% 0px);
- transform:translate(10px,10px)
- }
- 20%{
- clip-path:inset(80% 0px 0px 0px);
- transform:translate(-10px,10px)
- }
- 30%{
- clip-path:inset(10% 0px 85% 0px);
- transform:translate(0px,5px)
- }
- 40%{
- clip-path:inset(50% 0px 30% 0px);
- transform:translate(-5px,0px)
- }
- 50%{
- clip-path:inset(10% 0px 30% 0px);
- transform:translate(5px,0px)
- }
- 60%{
- clip-path:inset(40% 0px 30% 0px);
- transform:translate(5px,10px)
- }
- 70%{
- clip-path:inset(50% 0px 30% 0px);
- transform:translate(-10px,10px)
- }
- 80%{
- clip-path:inset(80% 0px 5% 0px);
- transform:translate(20px,-10px)
- }
- 90%{
- clip-path:inset(80% 0px 0px 0px);
- transform:translate(-10px,0px)
- }
- 100%{
- clip-path:inset(80% 0px 0px 0px);
- transform:translate(0px,0px)
- }
- }
- </style>
- </head>
- <body>
- <div class="a">
- <div class="b"><span>
- welcome!
- </span>
- </div>
- <div style="margin-top: 200px">
- <a href="javascript:void(0);" onclick="goToLogin()">进入</a>
- </div>
- <script>
- // 定义跳转函数
- function goToLogin() {
- window.location.href = "login.jsp";
- }
- Math.floor
- </script>
- </div>
- </body>
- </html>

2.注册
(1)创建一个注册的页面:register.jsp
- <%--
- Created by IntelliJ IDEA.
- User: 25822
- Date: 2024/5/8
- Time: 下午4:07
- To change this template use File | Settings | File Templates.
- --%>
- <%@ page contentType="text/html;charset=UTF-8" language="java" %>
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>登录</title>
- <style>
- body{
- /* 设置背景渐变 */
- background-image: linear-gradient(to left,
- #9c88ff,#3cadeb);
- display: flex;
- justify-content: center;
- }
- .a{
- position:relative;
- top: 100px;
- width: 1100px;
- height: 550px;
- box-shadow: 0 5px 15px rgba(0,0,0,.8);
- display: flex;
- }
- .b{
- width: 800px;
- height: 550px;
- background-image: url("201515-158211451517f1.jpg");
- /* 让图片适应大小 */
- background-size: cover;
- }
- .c{
- width: 300px;
- height: 550px;
- background-color: white;
- display: flex;
- justify-content: center;
- align-items: center;
- }
- .d{
- width: 250px;
- height: 500px;
- }
- .d h1{
- font: 900 30px '';
- }
- .e{
- width: 230px;
- margin: 20px 0;
- outline: none;
- border: 0;
- padding: 10px;
- border-bottom: 3px solid rgb(80,80,170);
- font: 900 16px '';
- }
- .f{
- float: right;
- margin: 10px 0;
- }
- .g{
- position: absolute;
- margin: 20px;
- bottom: 40px;
- display: block;
- width: 200px;
- height: 60px;
- font: 900 30px '';
- text-decoration: none;
- line-height: 50px;
- border-radius: 30px;
- background-image: linear-gradient(to left,
- #9c88ff,#3cadeb);
- text-align: center;
- }
- </style>
- </head>
- <body>
- <form action="/register" method="post">
- <div class="a">
- <div class="b"></div>
- <div class="c">
- <div class="d">
- <h1>Login/Register</h1>
- <input type="text" name="username1" class="e" placeholder="用户名">
- <input type="password" name="password" class="e" placeholder="密码">
- <input type="password" name="password" class="e" placeholder="确认密码">
- <input type="submit" class="g" value="确认注册">
- </div>
- </div>
- </div>
- </form>
- </body>
- </html>

(2)创建一个注册的servlet:RegisterServlet
- package com.stx.controller;
-
- import com.stx.util.JDBCUtil;
-
- 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 java.io.IOException;
- //通过注解注册路径
- @WebServlet("/register")
- public class RegisterServlet extends HttpServlet {
- @Override
- protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- req.setCharacterEncoding("utf-8");
- req.getRequestDispatcher("register.jsp").forward(req, resp);
- }
-
- @Override
- protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- req.setCharacterEncoding("utf-8");
- //接受提交的数据
- String username = req.getParameter("username1");
- String password = req.getParameter("password");
- System.out.println(username);
- //更新到数据库
- JDBCUtil.update("INSERT INTO register (name,password) VALUES ('" + username + "', '" + password + "')");
-
- //跳转到列表页面
- //需要存数据到request对象,用forward
- //req.getRequestDispatcher("/studentlist").forward(req, resp);
- //不需要带数据跳转,可以用sendRedirect response对象是新的
- resp.sendRedirect("/login.jsp");
- }
- }

注册的账户密码通过from表单的post方法提交到RegisterServlet,再在RegisterServlet通过JDBC的工具类把值新增到数据库中,然后跳转到login.jsp页面即登录页面
3.登录
(1)创建一个登录的jsp:login.jsp
-
- <%@ page contentType="text/html;charset=UTF-8" language="java" %>
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>登录</title>
- <style>
- body{
- /* 设置背景渐变 */
- background-image: linear-gradient(to left,
- #9c88ff,#3cadeb);
- display: flex;
- justify-content: center;
- }
- .a{
- position:relative;
- top: 100px;
- width: 1100px;
- height: 550px;
- box-shadow: 0 5px 15px rgba(0,0,0,.8);
- display: flex;
- }
- .b{
- width: 800px;
- height: 550px;
- background-image: url("201515-158211451517f1.jpg");
- /* 让图片适应大小 */
- background-size: cover;
- }
- .c{
- width: 300px;
- height: 550px;
- background-color: white;
- display: flex;
- justify-content: center;
- align-items: center;
- }
- .d{
- width: 250px;
- height: 500px;
- }
- .d h1{
- font: 900 30px '';
- }
- .e{
- width: 230px;
- margin: 20px 0;
- outline: none;
- border: 0;
- padding: 10px;
- border-bottom: 3px solid rgb(80,80,170);
- font: 900 16px '';
- }
- .f{
- float: right;
- margin: 10px 0;
- }
- .g{
- position: absolute;
- margin: 20px;
- bottom: 40px;
- display: block;
- width: 200px;
- height: 60px;
- font: 900 30px '';
- text-decoration: none;
- line-height: 50px;
- border-radius: 30px;
- background-image: linear-gradient(to left,
- #9c88ff,#3cadeb);
- text-align: center;
- }
- </style>
- <title>Login Page</title>
- </head>
- <body>
- <form action="/login" method="post">
- <div class="a">
- <div class="b"></div>
- <div class="c">
- <div class="d">
- <h1>Login/Register</h1>
- <input type="text" name="username" class="e" placeholder="用户名">
- <input type="password" name="password" class="e" placeholder="密码">
- <a href="javascript:void(0);" onclick="goToLogin()" class="f">点击注册</a>
- <a href="#" class="f">忘记密码?</a>
- <input type="submit" class="g" onClick="return validateForm();"/>
- </div>
- </div>
- </div>
- </form>
- <script>
- // 页面加载完成后检查errorMsg是否存在,并弹出警告框
- window.onload = function() {
- var errorMsg = getQueryVariable('errorMsg');
- if (errorMsg) {
- alert(errorMsg);
- }
- };
- // 函数:从URL查询字符串中获取指定参数的值
- function getQueryVariable(variable) {
- var query = window.location.search.substring(1);
- var vars = query.split("&");
- for (var i=0;i<vars.length;i++) {
- var pair = vars[i].split("=");
- if(pair[0] == variable){return pair[1];}
- }
- return(false);
- }
- //跳转注册
- function goToLogin() {
- window.location.href = "register.jsp";
- };
- // 定义表单验证和提交函数
- function validateForm() {
- var username = document.getElementsByName('username')[0].value;
- var password = document.getElementsByName('password')[0].value;
-
- // 前端验证
- if(username.trim() === '') {
- alert('用户名不能为空!');
- return false;
- }
- if(password.trim() === '') {
- alert('密码不能为空!');
- return false;
- }
- // 如果验证通过,手动提交表单
- document.getElementById('loginForm').submit();
- }
- </script>
- </body>
- </html>

对密码进行一些简单的验证,用户名和密码不能为空,并且账号或密码错误时会弹出来error
(2)创建一个LoginServlet
- package com.stx.controller;
- import com.stx.util.JDBCUtil;
- 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 javax.servlet.http.HttpSession;
- import java.io.IOException;
- import java.net.URLEncoder;
- import java.sql.ResultSet;
- import java.sql.SQLException;
-
- @WebServlet("/login")
- public class LoginServlet extends HttpServlet {
- @Override
- protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- super.doGet(req, resp);
- }
-
- @Override
- protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- req.setCharacterEncoding("utf-8");
- String username = req.getParameter("username");
- String password = req.getParameter("password");
- String sql = "select * from register where name='"+username+"' and password='"+password+"'";
- System.out.println(sql);
- ResultSet query = JDBCUtil.query(sql);
- try {
- if (query.next()) {
- // 登录成功,转发到主页
- req.getRequestDispatcher("home.jsp").forward(req, resp);
- } else {
- // 登录失败,设置错误信息并重定向回登录页面,附带错误信息参数
- String errorMsgEncoded = URLEncoder.encode("error", "UTF-8");
- resp.sendRedirect(req.getContextPath() + "/login.jsp?errorMsg=" + errorMsgEncoded);
- }
- } catch (SQLException e) {
- throw new RuntimeException(e);
- }
- //解决乱码
- resp.setContentType("text/html");
- // req.setCharacterEncoding("utf-8");
- // //业务逻辑 判断校验登录密码
- // String username = req.getParameter("username");
- // String password = req.getParameter("password");
- // String html ="<html lang=\"en\">\n" +
- // "<head>\n" +
- // " <meta charset=\"UTF-8\">\n" +
- // " <title>Title</title>\n" +
- // "</head>\n" +
- // "<body>\n" +
- // "<h1>why</h1>\n" +
- // "</body>\n" +
- // "</html>";
- // //数据库查找比对
- // if (username.equals("admin") && password.equals("123")) {
- String name = "尊贵的管理员";
- // // resp.getWriter().write(html);
- //
- // //session 生命周期
- // //1.用户浏览器窗口关闭,会话结束
- // //2.会话有效期 设置有效期过了 数据清空
- HttpSession session = req.getSession();
- session.setMaxInactiveInterval(3600);//默认半小时,单位是秒
- //获取session来保存会话数据 request
- session.setAttribute("user", name);
-
- // //转发到前端页面
- // //request
- // //数据存进去,在jsp页面再取出来
- // req.setAttribute("name", name);//存 键值对 数据 到 requset对象
- // //数据通过requset对象 转发到前端jsp页面
- // req.getRequestDispatcher("home.jsp").forward(req, resp);
- // }
-
- }
- }

同样,login.jsp通过表单提交到LoginServlet,在里面进行校验,首先从数据库里面查询账号和密码相对于的值,如果有则通过验证,转发到主页即home.jsp,登录失败,设置错误信息并重定向回登录页面,附带错误信息参数。
4.主页
(1)首先创建一个home.jsp设置主页的样式
- <%--
- Created by IntelliJ IDEA.
- User: 25822
- Date: 2024/5/7
- Time: 下午8:38
- To change this template use File | Settings | File Templates.
- --%>
- <%@ page contentType="text/html;charset=UTF-8" language="java" %>
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>学生管理系统</title>
- <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" />
- <style>
- * {
- box-sizing: border-box;
- margin: 0;
- padding: 0;
- }
-
- body {
- font-family: 'Segoe UI', Arial, sans-serif;
- line-height: 1.6;
- color: #333;
- background-color: #f8f9fa;
- }
-
- .container {
- max-width: 1200px;
- margin: 0 auto;
- padding: 20px;
- height: 100%;
- }
-
- header {
- background-color: #007bff;
- color: white;
- padding: 20px;
- display: flex;
- justify-content: space-between;
- align-items: center;
- }
-
- header a {
- color: white;
- text-decoration: none;
- transition: color 0.3s ease;
- }
-
- header a:hover {
- color: rgba(255, 255, 255, 0.8);
- }
-
- nav ul {
- list-style-type: none;
- padding: 0;
- }
-
- nav li {
- margin-bottom: 10px;
- }
-
- nav a {
- display: block;
- padding: 10px 20px;
- text-decoration: none;
- color: #333;
- background-color: #e9ecef;
- border-radius: 5px;
- transition: background-color 0.3s ease;
- }
-
- nav a:hover, nav a.active {
- background-color: #007bff;
- color: white;
- }
-
- .main-content {
- display: flex;
- margin-top: 30px;
- margin-left: 250px;
- }
-
- .sidebar {
- width: 20%;
- min-width: 250px;
- border-right: 1px solid #dee2e6;
- }
-
- .content-area {
- width: 100%;
- height: 100%;
- }
-
- iframe {
- width: 100%;
- border: none;
- height: 500px;
- }
-
- footer {
- background-color: #007bff;
- color: white;
- text-align: center;
- padding: 20px;
- margin-top: 30px;
- }
-
- @media (max-width: 768px) {
- .main-content {
- flex-direction: column;
- }
-
- .sidebar, .content-area {
- width: 100%;
- border: none;
- margin-bottom: 20px;
- }
- }
- </style>
- </head>
- <body>
- <div class="container">
- <header>
- <h1>学生管理系统</h1>
- <a href="logout" class="logout-link">退出 <i class="fas fa-sign-out-alt"></i></a>
- </header>
-
- <nav class="sidebar">
- <ul>
- <li><a href="studentlist" target="contentFrame" class="active">学生列表</a></li>
- <li><a href="studentadd" target="contentFrame">添加学生</a></li>
- </ul>
- </nav>
-
- <div class="main-content">
- <div class="content-area">
- <iframe name="contentFrame" id="contentFrame"></iframe>
- </div>
- </div>
- <footer>版权所有 © 2024 学生管理系统</footer>
- </div>
-
- <script>
- // JavaScript to handle active link state if needed
- document.querySelectorAll('nav a').forEach(link => {
- link.addEventListener('click', function() {
- document.querySelectorAll('nav a').forEach(l => l.classList.remove('active'));
- this.classList.add('active');
- });
- });
- </script>
- </body>
- </html>

主页只是一个页面,不需要逻辑,则不需要创建servlet,但是主页需要通过超链接跳到学生列表和添加学生的页面,还需要退出,退出则到登录页面,如下图:
我们这里先写退出的逻辑:LogoutServlet
- package com.stx.controller;
-
- 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 javax.servlet.http.HttpSession;
- import java.io.IOException;
-
- @WebServlet("/logout")
- public class LogoutServlet extends HttpServlet {
- @Override
- protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- req.setCharacterEncoding("utf-8");
- //退出系统 清空session
- HttpSession session = req.getSession();
- //session.removeAttribute("uesr");//删除指定数据
- session.invalidate();//直接失效
- //跳转到登录页面
- resp.sendRedirect("/login.jsp");
- }
-
- @Override
- protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- super.doPost(req, resp);
- }
- }

5.学生列表
(1)首先创建一个学生列表的jsp页面:studentlist.jsp
- <%@ page import="com.stx.controller.Student" %>
- <%@ page import="java.util.List" %>
- <%--
- Created by IntelliJ IDEA.
- User: 25822
- Date: 2024/5/7
- Time: 下午8:41
- To change this template use File | Settings | File Templates.
- --%>
- <%@ page contentType="text/html;charset=UTF-8" language="java" %>
- <meta charset="UTF-8">
- <html>
-
- <head>
- <title>Title</title>
- <style>
- table {
- border: 1px solid black;
- border-collapse: collapse;
- }
- th, td {
- border: 1px solid black;
- }
- </style>
- <script>
- function confirmDelete(id) {
- if (confirm("是否确认删除id为" + id + "的记录?")) {
- // 确认删除,使用window.location.href进行页面跳转来执行删除操作
- window.location.href = "studentdelete?id=" + id;
- }
- }
- </script>
- </head>
- <body>
- <%
- List list = (List)request.getAttribute("list");
- %>
- <table cellpadding="1" cellspacing="0" width="500px" align="center">
- <caption>学生数据</caption>
- <th bgcolor="#ffc0cb">姓名</th>
- <th>年龄</th>
- <th>ID</th>
- <th>操作</th>
- <!--jsp代码可以打断包含html代码-->
- <%
- for (int i = 0; i < list.size(); i++){
- Student student = (Student)list.get(i);
- %>
- <tr>
- <td align="center" height="40px"><%= student.getName() %></td>
- <td align="center" height="40px"><%= student.getAge() %></td>
- <td align="center" height="40px"><%= student.getId() %></td>
- <td align="center" height="40px">
- <!-- 使用JavaScript函数confirmDelete来处理删除确认 -->
- <a href="#" onclick="confirmDelete('<%= student.getId()%>')">删除</a>
- <a href="studentview?id=<%= student.getId()%>">查看</a>
- <a href="studentmodify?id=<%= student.getId()%>">修改</a>
- </td>
- </tr>
- <%
- }
- %>
- </table>
- </body>
- </html>

列表页面上会包含删除,具体学生信息的查看和修改,我们这里先完成整个学生列表的显示。
(2)创建一个StudentServlet,用于从数据库拿去数据并显示到studentlist.jsp页面之上
- package com.stx.controller;
-
- import com.stx.util.JDBCUtil;
-
- import java.io.IOException;
- import java.sql.ResultSet;
- import java.util.ArrayList;
- 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;
-
-
- @WebServlet("/studentlist")
- public class StudentServlet extends HttpServlet {
- @Override
- protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- req.setCharacterEncoding("utf-8");
-
- //改用filter过滤器,全局校验
- //判断用户是否登录过 通过sesseion取登录之后存数据
- // HttpSession session = req.getSession();
- // String name = (String) session.getAttribute("user");//返回的是object,需要强转
- // if (name == null) {
- // //要么没有登录,要么超时了
- // //需要重新登录,跳转到登录页面,可以通过转发即:
- // //req.getRequestDispatcher("studentlist.jsp").forward(req, resp);
- // //也可以页面重定向 让用户重新发出请求(相当于浏览器重新访问):
- // resp.sendRedirect("/login.jsp");
- // return;
- // }
-
- //获取数据库的数据
- ResultSet resultSet = JDBCUtil.query("select * from student");
- List<Student> list = null;
- try {
- //数据封装到集合里面去,返回给前端jsp页面
- list = new ArrayList();
- while (resultSet.next()) {
- Student student = new Student();
- student.setName(resultSet.getString("name"));
- student.setAge(resultSet.getInt("age"));
- student.setId(resultSet.getString("Id"));
- list.add(student);
- }
- System.out.println("获取的数据:" + list.size());
- } catch (Exception e) {
- // 处理异常,至少打印出来,实际应用中应该有更详细的日志记录
- e.printStackTrace();
- }
- //存到resqust对象
- req.setAttribute("list", list);
- //转发到jsp
- req.getRequestDispatcher("studentlist.jsp").forward(req, resp);
- }
-
- @Override
- protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- super.doPost(req, resp);
- }
- }

这里不仅需要存取到数据库,还需要存到学生列表里,方便取出,列表提供了丰富的API(如迭代、添加、删除等操作),使得在后续的业务处理中,可以方便地遍历和操作这些数据。
(3)创建一个student类
- package com.stx.controller;
-
- public class Student {
- public String name;
- public int age;
- public String id;
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public int getAge() {
- return age;
- }
-
- public void setAge(int age) {
- this.age = age;
- }
-
- public String getId() {
- return id;
- }
-
- public void setId(String id) {
- this.id = id;
- }
- }

此时页面上已经有学生数据,如下,我们再完成查看,删除和修改的功能
6.查看学生信息
(1)创建一个studentlist.jsp页面,用来显示学生具体信息,我这里只有名字,年龄和ID想要更多可以自己加一下
- <%@ page import="com.stx.controller.Student" %>
- <%--
- Created by IntelliJ IDEA.
- User: 25822
- Date: 2024/5/7
- Time: 下午8:44
- To change this template use File | Settings | File Templates.
- --%>
- <%@ page contentType="text/html;charset=UTF-8" language="java" %>
- <html>
- <head>
- <title>Title</title>
- <style>
- table {
- border: 1px solid black;
- border-collapse: collapse;
- }
- th, td {
- border: 1px solid black;
- }
- </style>
- </head>
- <body>
- <% Student student = (Student) request.getAttribute("student");%>
- <table cellpadding="1" cellspacing="0" width="500px" align="center">
- <caption>学生数据</caption>
- <th bgcolor="#ffc0cb">姓名</th>
- <th>年龄</th>
- <th>ID</th>
- <!--jsp代码可以打断包含html代码-->
- <tr>
- <td align="center" height="40px"><%= student.getName() %></td>
- <td align="center" height="40px"><%= student.getAge() %></td>
- <td align="center" height="40px"><%= student.getId() %></td>
- </tr>
- </table><br>
- <!--返回上一层页面-->
- <input type="button" value="返回" onclick="history.back()">
- </body>
- </html>

(2)创建一个StudentVServlet用于从数据库提取数据,并返回给前端页面
- package com.stx.controller;
-
- import com.stx.util.JDBCUtil;
-
- 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 java.io.IOException;
- import java.sql.ResultSet;
-
- @WebServlet("/studentview")
- public class StudentViewServlet extends HttpServlet {
- @Override
- protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- req.setCharacterEncoding("utf-8");
- //获取学生数据
- String id = req.getParameter("id");
- ResultSet resultSet = JDBCUtil.query("select * from student where id =" +id);
- try {
- //数据封装到集合里面去,返回给前端jsp页面
- if (resultSet.next()) {
- Student student = new Student();
- student.setName(resultSet.getString("name"));
- student.setAge(resultSet.getInt("age"));
- student.setId(resultSet.getString("id"));
- req.setAttribute("student", student);//查询出来的对象,存到request对象
- }
- } catch (Exception e) {
- // 处理异常,至少打印出来,实际应用中应该有更详细的日志记录
- e.printStackTrace();
- }
- req.getRequestDispatcher("studentview.jsp").forward(req, resp);
- }
-
- @Override
- protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- super.doPost(req, resp);
- }
- }

7.修改学生信息
(1)创建一个studentmodify.jsp页面用于向后端提交修改后的值
- <%@ page import="com.stx.controller.Student" %>
- <%@ page contentType="text/html;charset=UTF-8" language="java" %>
- <!-- 省略其他头部信息 -->
- </html>
- <head>
- <title>Title</title>
- <meta charset="UTF-8">
- </head>
- <body>
- <% Student student = (Student) request.getAttribute("student");%>
- <form action="/studentmodify" method="post" onsubmit="return checkContent()">
- <table>
- <tr>
- <td><label for="name">姓名:</label></td>
- <td><input type="text" id="name" name="name" value="<%= student.getName() %>" onfocus="checkName()"></td>
- </tr>
- <tr>
- <td><label for="age">年龄:</label></td>
- <td><input type="text" id="age" name="age" value="<%= student.getAge() %>" onfocus="checkAge()"></td>
- </tr>
- <tr>
- <td><label for="id">ID:</label></td>
- <td><input type="text" id="id" name="id" value="<%= student.getId() %>" onfocus="checkId()"></td>
- </tr>
- </table><br>
- <input type="submit" value="提交">
- <input type="reset" value="重置">
- </form>
-
-
- <script>
- function checkContent() {
- // 实现整体验证逻辑
- return true; // 返回true允许提交,false阻止提交
- }
-
- function checkName() {
- // 实现姓名验证逻辑
- }
-
- function checkAge() {
- // 实现年龄验证逻辑
- }
-
- function checkId() {
- // 实现ID验证逻辑
- }
- </script>
- </body>
- </html>

(2)创建一个StudentUpdateServlet用于接受前端数据,并通过JDBC工具类修改,更新到数据库
- package com.stx.controller;
-
- import com.stx.util.JDBCUtil;
-
- 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 javax.servlet.http.HttpSession;
- import java.io.IOException;
- import java.sql.ResultSet;
-
- @WebServlet("/studentmodify")
- public class StudentUpdateServlet extends HttpServlet {
- @Override
- protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- req.setCharacterEncoding("utf-8");
-
- //改用filter过滤器,全局校验
- // HttpSession session = req.getSession();
- // String name = (String) session.getAttribute("user");//返回的是object,需要强转
- // if (name == null) {
- // //要么没有登录,要么超时了
- // //需要重新登录,跳转到登录页面,可以通过转发即:
- // //req.getRequestDispatcher("studentlist.jsp").forward(req, resp);
- // //也可以页面重定向 让用户重新发出请求(相当于浏览器重新访问):
- // resp.sendRedirect("/login.jsp");
- // return;
- // }
-
- //获取学生数据
- String id = req.getParameter("id");
- ResultSet resultSet = JDBCUtil.query("select * from student where id =" +id);
- try {
- //数据封装到集合里面去,返回给前端jsp页面
- if (resultSet.next()) {
- Student student = new Student();
- student.setName(resultSet.getString("name"));
- student.setAge(resultSet.getInt("age"));
- student.setId(resultSet.getString("id"));
- req.setAttribute("student", student);//查询出来的对象,存到request对象
- }
- } catch (Exception e) {
- // 处理异常,至少打印出来,实际应用中应该有更详细的日志记录
- e.printStackTrace();
- }
- req.getRequestDispatcher("studentmodify.jsp").forward(req, resp);
- }
-
- @Override
- protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- req.setCharacterEncoding("utf-8");
- //接受提交的数据
- String id = req.getParameter("id");
- String name = req.getParameter("name");
- String age = req.getParameter("age");
- //更新到数据库
- String sql = "update student set name='"+name+"',age='"+age+"',id='"+id+"' where id="+id;
- JDBCUtil.update(sql);
-
- //跳转到列表页面
- //需要存数据到request对象,用forward
- // req.getRequestDispatcher("/studentlist").forward(req, resp);
- //不需要带数据跳转,可以用sendRedirect response对象是新的
- resp.sendRedirect("/studentlist");
- }
- }

8.删除学生信息
删除信息不需要前端页面,只需要在学生列表上面直接删除
创建一个StudentDeleteServlet
- package com.stx.controller;
-
- import com.stx.util.JDBCUtil;
-
- 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 java.io.IOException;
- @WebServlet("/studentdelete")
- public class StudentDeleteServlet extends HttpServlet {
- @Override
- protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- //删除逻辑
- String id = req.getParameter("id");
- JDBCUtil.update("delete from student where id="+id);
- //跳转到列表页面
- resp.sendRedirect("/studentlist");
- }
-
- @Override
- protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- }
- }

9.最后添加学生
(1)创建一个添加页面studentadd.jsp
- <%@ page import="com.stx.controller.Student" %>
- <%--
- Created by IntelliJ IDEA.
- User: 25822
- Date: 2024/5/8
- Time: 上午11:47
- To change this template use File | Settings | File Templates.
- --%>
- <%@ page contentType="text/html;charset=UTF-8" language="java" %>
-
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <style>
- .content-area {
- display: flex;
- justify-content: center;
- align-items: center;
- flex-direction: column;
- height: 100%;
- padding: 20px;
- }
- form {
- width: 100%;
- max-width: 400px; /* 限制表单最大宽度,适应不同屏幕 */
- padding: 20px;
- background-color: #ffffff;
- border-radius: 5px;
- box-shadow: 0 0 10px rgba(0,0,0,0.1);
- }
- </style>
- </head>
- <body>
- <div class="main-content">
- <div class="content-area">
- <form action="/studentadd" method="post" onsubmit="return checkContent()">
- <table>
- <tr>
- <td><label for="name">姓名:</label></td>
- <td><input type="text" id="name" name="name" onfocus="checkName()"></td>
- </tr>
- <tr>
- <td><label for="age">年龄:</label></td>
- <td><input type="text" id="age" name="age" onfocus="checkAge()"></td>
- </tr>
- <tr>
- <td><label for="id">ID:</label></td>
- <td><input type="text" id="id" name="id" onfocus="checkId()"></td>
- </tr>
- </table><br>
- <input type="submit" value="提交">
- <input type="reset" value="重置">
- </form>
- </div>
- </div>
- <script>
- </script>
- </body>
- </html>

(2)创建StudentAddServlet,把数据插入到数据库
- package com.stx.controller;
-
- import com.stx.util.JDBCUtil;
-
- 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 java.io.IOException;
- @WebServlet("/studentadd")
- public class StudentAddServlet extends HttpServlet {
- @Override
- protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- req.getRequestDispatcher("studentadd.jsp").forward(req, resp);
- }
-
- @Override
- protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- req.setCharacterEncoding("utf-8");
- //接受提交的数据
- String id = req.getParameter("id");
- String name = req.getParameter("name");
- String age = req.getParameter("age");
- //更新到数据库
- JDBCUtil.update("INSERT INTO student (id, age, name) VALUES ('" + id + "', '" + age + "', '" + name + "')");
-
- //跳转到列表页面
- //需要存数据到request对象,用forward
- // req.getRequestDispatcher("/studentlist").forward(req, resp);
- //不需要带数据跳转,可以用sendRedirect response对象是新的
- resp.sendRedirect("/studentlist");
- }
- }

10.最后设置过滤器,避免直接跳过登录页面直接进入到学生列表里面,完善登录功能
在filter的包里面,创建过滤器
- package com.stx.filter;
-
- import javax.servlet.*;
- import javax.servlet.annotation.WebFilter;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import javax.servlet.http.HttpSession;
- import java.io.IOException;
- //过滤哪些地址
- @WebFilter("/*")
- public class LoginFilter implements Filter {//接口
- @Override
- public void init(FilterConfig filterConfig) throws ServletException {
-
- }
-
- @Override
- public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
- HttpServletRequest req = (HttpServletRequest) servletRequest;
- HttpServletResponse resp = (HttpServletResponse) servletResponse;
- //过滤器的逻辑控制方法
- //判断所有需要登录的地址,用户是否已经正常登录
- //判断用户是否登录过 通过session 取登录之后的存数据
- //判断后台数据操作才需要 判断是否登录
- //URI和URL区别 /login.jsp http://localhost:8080/login.html
- String uri = req.getRequestURI();
- String url = req.getRequestURL().toString();
- System.out.println(url);
- //取上下文路径
- //排除掉不需要的地址
- if (!uri.equals("/")&&!url.contains("login")&&!url.contains("register")) {//登录页面不需要校验
- HttpSession session = req.getSession(); // 这里也应使用request,而非req
- String name = (String) session.getAttribute("user"); // 返回的是Object,需要强转
- if (name == null) {
- // 要么没有登录,要么超时了
- // 需要重新登录,跳转到登录页面,可以通过转发即:
- // request.getRequestDispatcher("studentlist.jsp").forward(request, response);
- // 也可以页面重定向 让用户重新发出请求(相当于浏览器重新访问):
- //要取完整的项目部署路径
- resp.sendRedirect("/login.jsp");
- return;
- }
-
- }
- filterChain.doFilter(servletRequest, servletResponse);
-
- }
- @Override
- public void destroy() {
-
- }
- }

过滤掉除了登录页面之外的所有页面,如果直接进入,则会转发到登录页面,至此一个简单的学生管理系统,基本功能实
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。