0


JavaWeb实现学生管理系统

JavaWeb实现学生管理系统

一、项目介绍

该项目是基于JavaWeb实现的学生管理系统,使用maven进行管理jar包,能够对学生信息进行增删改查,分页查询,以及实现管理员的注册、登录
数据库:MySQL
开发工具:idea
开发环境:jdk 1.8 + tomcat

二、项目结构

在这里插入图片描述在这里插入图片描述

三、前期准备

1.配置maven环境,在pom.xml配置文件中配置项目所依赖的jar包

    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.21</version>
    </dependency>

    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.0.1</version>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.2</version>
      <scope>provided</scope>
    </dependency>

2.在MySql数据库中,创建登录注册表login和学生信息表student

(1)登录注册表login

在这里插入图片描述

(2)学生信息表student

在这里插入图片描述

(3)创建数据表代码

SET NAMES utf-8;
CREATE DATABASE studentManager;
USE studentManager;
CREATE TABLE student
(
  sno INT PRIMARY KEY,
  sname VARCHAR(20) NOT NULL,
  sex CHAR(4) ,
  age INT DEFAULT 20,
  phone VARCHAR(30) 
);

INSERT INTO student VALUES(1001,'jack','男',23,'13389076524');
INSERT INTO student VALUES(1002,'rose','女',23,'18760987543');
INSERT INTO student VALUES(1003,'tom','男',23,'13389067823');
INSERT INTO student VALUES(1004,'王麻子','男',23,'13560738947');
INSERT INTO student VALUES(1005,'大麻子','男',23,'18899067532');

INSERT INTO student VALUES(1006,'小麻子','男',23,'15678634789');
INSERT INTO student VALUES(1007,'老麻子','男',23,'12199834572');
INSERT INTO student VALUES(1008,'张三','男',23,'15533098843');
INSERT INTO student VALUES(1009,'长萨珊','女',23,'12209835679');
INSERT INTO student VALUES(1010,'李四','女',23,'15509087635');

INSERT INTO student VALUES(1011,'王五','男',23,'15788679043');
INSERT INTO student VALUES(1012,'赵六','女',23,'12489034506');
INSERT INTO student VALUES(1013,'刘二','男',23,'13560596743');

CREATE TABLE login
(
  uid INT PRIMARY KEY,
  pwd VARCHAR(20) NOT NULL,
);

INSERT INTO login VALUES(1, '1234');
INSERT INTO login VALUES(2, '2222');
INSERT INTO login VALUES(3, '6688');

3.配置tocamt

在这里插入图片描述在这里插入图片描述

四、代码实现

1.JSP界面实现

(1)首页-登录界面 (index.jsp)

<%@ page language="java" contentType="text/html; charset=utf-8"  pageEncoding="utf-8"%>
<!DOCTYPEhtml><html><head><title>学生信息管理平台</title><style>.titleDiv{height: 85px;color:white;padding-top: 30px;font-size: 50px;padding-left: 30px;font-family: 隶书;}.mainDiv{width: 899px;height: 500px;border: 4px rgb(237, 237, 237) solid;border-radius: 5px;background-image:url("输入你要的图片链接!");margin: auto;margin-top: 50px;}.loginDiv{height: 220px;width: 260px;padding:50px;background-color:rgba(255,255,255,0.9);border-radius:25px;border:1px #bdbdbd solid;opacity:0.9;float: right;margin-right: 100px
        }.name{font-size: 25px;}a{font-size:15px;color:#59c2c5;padding-left:20px;}.item{height:60px;}.item input{line-height:40px;width:245px;border:none;border-bottom: 1px solid #59c2c5;margin-bottom: 20px;margin-top: 10px;}.login-btn{display:block;width:255px;height:50px;color:#fff;background:#59c2c5;font-size:16px;line-height:30px;text-align:center;border-radius:10px;border:none;margin-bottom: 20px;margin-top: 10px;}</style></head><body><divclass="mainDiv"><divclass="titleDiv">学生信息管理平台</div><formaction="LoginServlet"method="post"><divclass="loginDiv"><divclass="name">
            用户登录 <ahref="register.jsp"> 立即注册</a></div><divclass=item><inputtype="text"name="uid"placeholder="用户名"/></div><divclass=item><inputtype="password"name="pwd"placeholder="密码"/></div><inputtype="submit"class="login-btn"value="登 录"/>
        <%
            if(session.getAttribute("loginErrorMessage") != null){

                String loginErrorMessage = (String)session.getAttribute("loginErrorMessage");
                out.print(loginErrorMessage);
            }
        %>
        <%
            String register = (String) request.getAttribute("register");
            if (register!= null) {
                if (register.equals("reg")) {
                    out.println("注册成功, 请登录!");
                }
            }
        %>
    </div></form></div></body></html>

(2)用户注册界面 (register.jsp)

<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<!DOCTYPEhtml><html><head><title>注册账号</title><style>.mainDiv{width: 899px;height: 500px;border: 4px rgb(237, 237, 237) solid;border-radius: 5px;background-image:url("输入你要的图片链接!");margin: auto;margin-top: 50px;}.titleDiv{height: 85px;color:white;padding-top: 30px;font-size: 50px;padding-left: 30px;font-family: 隶书;}.registerDiv{height: 220px;width: 260px;padding:50px;background-color:rgba(255,255,255,0.9);border-radius:25px;border:1px #bdbdbd solid;opacity:0.9;float: right;margin-right: 100px
        }.name{font-size: 25px;}.item{height:60px;}.item input{line-height:40px;width:245px;border:none;border-bottom: 1px solid #59c2c5;margin-bottom: 20px;margin-top: 10px;}.btn{display:block;width:255px;height:50px;color:#fff;background:#59c2c5;font-size:16px;line-height:30px;text-align:center;border-radius:10px;border:none;margin-top: 10px;}a{font-size:18px;padding-left:200px;padding-bottom: 50px;color:#59c2c5;}</style></head></head><body><divclass="mainDiv"><divclass="titleDiv">学生信息管理平台</div><formaction="RegisterServlet"><divclass="registerDiv"><divclass="name">用户注册</div><divclass="item"><inputtype="text"name="uid"placeholder="账号"/></div><divclass="item"><inputtype="password"name="pwd"placeholder="密码"/></div><inputtype="submit"class="btn"value="注册"/><ahref="index.jsp">返回</a></div></form></div></body></html>

(3)登录成功-主界面 (main.jsp)

<%@ page language="java" contentType="text/html; charset=utf-8"  pageEncoding="utf-8"%>
<%@ page import="com.stu.po.Student" %>
<!DOCTYPEhtml><html><head><title>学生信息管理平台</title><style>.titleDiv{height: 85px;color:white;padding-top: 30px;font-size: 50px;padding-left: 30px;font-family: 隶书;}.mainDiv{width: 899px;height: 500px;border: 4px rgb(237, 237, 237) solid;border-radius: 5px;background-image:url("https://img1.baidu.com/it/u=4271373647,1745018175&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500");margin: auto;margin-top: 50px;background-size: auto;}.Navigation{width: 899px;height: 200px;background-color:#59c2c5;opacity:0.8;text-align: center;line-height: 200px;font-family: 楷体;}a{font-size:30px;color:whitesmoke;padding-left:20px;text-decoration: none;}a:hover{color: blue;font-family: 隶书;}</style></head><body><divclass="mainDiv"><divclass="titleDiv">欢迎进入学生信息管理平台</div>
    <%
        if(session.getAttribute("login") == null) {
            session.setAttribute("loginErrorMessage", "您必须先登录才能访问主页!");
            response.sendRedirect("index.jsp");
        }
    %>
    <divclass="Navigation"><ahref="addStudent.jsp">添加学生</a><ahref="ShowStudentsByPageServlet">分页查询</a><ahref="ShowAllStudentsServlet">查看所有学生信息</a><ahref="QuitServlet">退出登录</a></div></div></body></html>

(4)添加学生界面 (addStudent.jsp)

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPEhtml><html><head><title>添加学生信息</title><style>.titleDiv{height: 2px;color:white;padding-top: 12px;font-size: 50px;padding-left: 30px;font-family: 隶书;}.mainDiv{width: 899px;height: 500px;border: 4px rgb(237, 237, 237) solid;border-radius: 5px;background-image:url("图片链接");margin: auto;margin-top: 50px;background-size: auto;}.addDiv{height: 380px;width: 260px;padding:50px;background-color:rgba(255,255,255,0.9);border-radius:25px;border:1px #bdbdbd solid;opacity:0.9;float: right;margin-right: 80px
        }.name{font-size: 20px;}.item{height:60px;}.item input{line-height:40px;width:245px;border:none;border-bottom: 1px solid #59c2c5;margin-bottom: 20px;margin-top: 10px;}.btn{display:block;width:255px;height:50px;color:#fff;background:#59c2c5;font-size:16px;line-height:30px;text-align:center;border-radius:10px;border:none;margin-top: 10px;}a{font-size:18px;padding-left:200px;padding-bottom: 50px;color:#59c2c5;}</style></head><body><divclass="mainDiv"><divclass="titleDiv">学生信息管理平台</div><formaction="AddServlet"><divclass="addDiv"><divclass="name">添加学生信息</div><divclass="item"><inputtype="text"name="sno"placeholder="学号"/></div><divclass="item"><inputtype="text"name="sname"placeholder="姓名"/></div><divclass="item"><inputtype="text"name="sex"placeholder="性别"/></div><divclass="item"><inputtype="text"name="age"placeholder="年龄"/></div><divclass="item"><inputtype="text"name="phone"placeholder="电话"/></div><inputtype="submit"class="btn"value="添加"/><ahref="main.jsp">返回</a></div></form></div></div></body></html>

(5)分页查询界面(showAllStudentByPageNo.jsp)

<%@ page import="com.stu.po.Student" %>
<%@ page import="java.util.List" %>
<%@ page import="com.stu.po.Page" %>
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<!DOCTYPEhtml><html><head><title>学生信息管理平台</title><style>.mainDiv{width: 900px;height: 550px;border: 4px rgb(237, 237, 237) solid;border-radius: 5px;background-image:url("图片链接");margin: auto;background-size: auto;}.titleDiv{height: 20px;color:white;padding-top: 30px;font-size: 50px;padding-left: 30px;font-family: 隶书;}.showStudentDiv{background-size: cover;width:700px;height:500px;margin: auto;margin-top: 50px;}.item{height:40px;border-radius:15px;}.item a{background-color: lightgrey;text-decoration: none;font-size:15px;color:black;border-radius:3px;}.item input{width: 20px;text-align: center;}table{width:100%;border-collapse:collapse;background-color:rgba(255,255,255,0.9);opacity: 0.8;}table body{display: block;height:300px;overflow-y: scroll;}table td{border:1px solid #A6A6A6;height:30px;width: 300px;text-align: center;font-size: 15px;}table th{height:30px;border:1px solid #A6A6A6;}</style></head><body><divclass="mainDiv"><divclass="titleDiv">分页查询学生信息</div><divclass="showStudentDiv"><tableborder="2"cellspacing="0"><tr><th><h3>学号</h3></th><th><h3>姓名</h3></th><th><h3>性别</h3></th><th><h3>年龄</h3></th><th><h3>电话</h3></th></tr>
        <%
          Page page1 = (Page)request.getAttribute("page1");

          for(Student student:page1.getStudent()){

        %>
            <tr><td><%=student.getSno() %></td><td><%=student.getSname() %></td><td><%=student.getSex() %></td><td><%=student.getAge() %></td><td><%=student.getPhone() %></td></tr>
          <%
            }
          %>
      </table>

      <%
        if(page1.getCurrentPage()==page1.getTotalPage()){
      %>
        <divclass= item><ahref="ShowStudentsByPageServlet?currentPage=0">首页</a><ahref="ShowStudentsByPageServlet?currentPage=<%=page1.getCurrentPage()-1%>">上一页</a><inputtype="text"name="currentPage"value="<%=page1.getTotalPage()+1%>"/></div>
      <%
      } else if(page1.getCurrentPage()==0){
      %>
        <divclass= item><inputtype="text"name="currentPage"value="1"/><ahref="ShowStudentsByPageServlet?currentPage=<%=page1.getCurrentPage()+1%>">下一页</a><ahref="ShowStudentsByPageServlet?currentPage=<%=page1.getTotalPage()%>">尾页</a></div>
      <%
      } else{
      %>
        <divclass= item><ahref="ShowStudentsByPageServlet?currentPage=0">首页</a><ahref="ShowStudentsByPageServlet?currentPage=<%=page1.getCurrentPage()-1%>">上一页</a><inputtype="text"name="currentPage"value="<%=page1.getCurrentPage()+1%>"/><ahref="ShowStudentsByPageServlet?currentPage=<%=page1.getCurrentPage()+1%>">下一页</a><ahref="ShowStudentsByPageServlet?currentPage=<%=page1.getTotalPage()%>">尾页</a></div>
      <%
        }
      %>

      <ahref="main.jsp">返回</a></div></div></body></html>

(6)查看所有学生信息界面

<%@ page language="java" contentType="text/html; charset=utf-8"  pageEncoding="utf-8"%>
<%@ page import="com.stu.po.Student" %>
<%@ page import="java.util.List" %>
<!DOCTYPEhtml><html><head><title>学生信息管理平台</title><style>.mainDiv{width: 900px;height: 700px;border: 4px rgb(237, 237, 237) solid;border-radius: 5px;background-image:url("图片链接");margin: auto;background-size: auto;}.titleDiv{height: 20px;color:white;padding-top: 30px;font-size: 50px;padding-left: 30px;font-family: 隶书;}.showStudentDiv{background-size: cover;width:700px;height:500px;margin: auto;margin-top: 50px;}.item{height:40px;border-radius:15px;}.item a{background-color: lightgrey;text-decoration: none;font-size:15px;color:black;border-radius:3px;}table{width:100%;border-collapse:collapse;background-color:rgba(255,255,255,0.9);opacity: 0.8;}table body{display: block;height:300px;overflow-y: scroll;}table td{border:1px solid #A6A6A6;height:30px;width: 300px;text-align: center;font-size: 15px;}table th{height:30px;border:1px solid #A6A6A6;}</style></head><body><divclass="mainDiv"><divclass="titleDiv">查看所有学生信息</div><divclass="showStudentDiv"><tableborder="2"cellspacing="0"><tr><th><h3>学号</h3></th><th><h3>姓名</h3></th><th><h3>性别</h3></th><th><h3>年龄</h3></th><th><h3>电话</h3></th><th><h3>操作</h3></th></tr>
            <%

                List<Student> allStudents = (List<Student>)session.getAttribute("allStudents");
                for (int i = 0; i < allStudents.size(); i++) {
                    Student s  = allStudents.get(i);
            %>
            <tr><td><%=s.getSno() %></td><td><%=s.getSname() %></td><td><%=s.getSex() %></td><td><%=s.getAge() %></td><td><%=s.getPhone() %></td><td><ahref="DeleteServlet?sno=<%=s.getSno() %>">删除</a><ahref="QueryStudentBySnoServlet?sno=<%=s.getSno()%>">修改</a></td></tr>
            <%
                }
            %>
        </table><ahref="main.jsp">返回</a></div></div></body></html>

(7) 修改学生界面 (updateStudent.jsp)

<%@ page language="java" contentType="text/html; charset=utf-8"  pageEncoding="utf-8"%>
<%@ page import="com.stu.po.Student" %>
<!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><metahttp-equiv="X-UA-Compatible"content="IE=edge"><metaname="viewport"content="width=device-width, initial-scale=1.0"><title>修改学生信息</title><style>.titleDiv{height: 20px;color:white;padding-top: 30px;font-size: 50px;padding-left: 30px;font-family: 隶书;}.mainDiv{width: 899px;height: 500px;border: 4px rgb(237, 237, 237) solid;border-radius: 5px;background-image:url("https://img1.baidu.com/it/u=4271373647,1745018175&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500");margin: auto;margin-top: 50px;background-size: auto;}.updateDiv{height: 340px;width: 260px;padding:50px;background-color:rgba(255,255,255,0.9);border-radius:25px;border:1px #bdbdbd solid;opacity:0.9;float: right;margin-right: 100px
        }.name{font-size: 25px;}.item{height:60px;}.item input{line-height:40px;width:245px;border:none;border-bottom: 1px solid #59c2c5;margin-bottom: 20px;margin-top: 10px;}.btn{display:block;width:255px;height:50px;color:#fff;background:#59c2c5;font-size:16px;line-height:30px;text-align:center;border-radius:10px;border:none;margin-top: 10px;}a{font-size:18px;padding-right:100px;padding-bottom: 50px;}</style></head><body><divclass="mainDiv"><divclass="titleDiv">学生信息管理平台</div><formaction="UpdateServlet">
        <%
            Student s =(Student)request.getAttribute("student");
        %>
        <divclass="updateDiv"><divclass="name">修改学生信息</div><inputtype="hidden"name="sno"value="<%=s.getSno()%>"/><divclass="item"><inputtype="text"name="sname"placeholder="姓名"value="<%=s.getSname()%>"/></div><divclass="item"><inputtype="text"name="sex"placeholder="性别"value="<%=s.getSex()%>"/></div><divclass="item"><inputtype="text"name="age"placeholder="年龄"value="<%=s.getAge()%>"/></div><divclass="item"><inputtype="text"name="phone"placeholder="电话"value="<%=s.getPhone()%>"/></div><inputtype="submit"class="btn"value="修改"/><ahref="showAllStudents.jsp">返回</a></div></form></div></div></body></html>

2.JavaBean实体类封装数据

(1)学生信息类 (Student.java)

packagecom.stu.po;publicclassStudent{//这是一个实体类,javabeanprivateint sno;privateString sname;privateString sex;privateint age;privateString phone;publicStudent(int sno,String sname,String sex,int age,String phone){this.sno = sno;this.sname = sname;this.sex = sex;this.age = age;this.phone = phone;}publicStudent(){}publicintgetSno(){return sno;}publicvoidsetSno(int sno){this.sno = sno;}publicStringgetSname(){return sname;}publicvoidsetSname(String sname){this.sname = sname;}publicStringgetSex(){return sex;}publicvoidsetSex(String sex){this.sex = sex;}publicintgetAge(){return age;}publicvoidsetAge(int age){this.age = age;}publicStringgetPhone(){return phone;}publicvoidsetPhone(String phone){this.phone = phone;}}

(2)分页帮助类 (Page.java)

packagecom.stu.po;importjava.util.List;//分页帮助类publicclassPage{privateint currentPage;//当前页面privateint pageSize;//一页有多少条数据privateint totalCount;//一共有多少条数据privateint totalPage;//一共有多少页privateList<Student> student;publicPage(){}publicPage(int currentPage,int pageSize,int totalCount,int totalPage,List<Student> student){this.currentPage = currentPage;this.pageSize = pageSize;this.totalCount = totalCount;this.totalPage = totalPage;this.student = student;}publicintgetCurrentPage(){return currentPage;}publicvoidsetCurrentPage(int currentPage){this.currentPage = currentPage;}publicintgetPageSize(){return pageSize;}publicvoidsetPageSize(int pageSize){this.pageSize = pageSize;}publicintgetTotalCount(){return totalCount;}publicvoidsetTotalCount(int totalCount){this.totalCount = totalCount;}publicintgetTotalPage(){return totalPage;}publicvoidsetTotalPage(int totalPage){this.totalPage = totalPage;}publicList<Student>getStudent(){return student;}publicvoidsetStudent(List<Student> student){this.student = student;}}

(3)JDBC工具类 (DBTools.java)

packagecom.stu.utils;publicinterfaceDBTools{publicstaticfinalStringDRIVER_CLASS="com.mysql.jdbc.Driver";publicstaticfinalStringCONN_STR="jdbc:mysql://localhost:3306/studentmanager?userSSL=false&serverTimezone=Asia/Shanghai";publicstaticfinalStringUSRENAME="root";publicstaticfinalStringPWD="123456";}

3.三层架构

(1)表示层servlet

① 用户登录表示层 (LoginServlet.java)

packagecom.stu.servlet;importjava.io.IOException;importjavax.servlet.ServletException;importjavax.servlet.annotation.WebServlet;importjavax.servlet.http.HttpServlet;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importjavax.servlet.http.HttpSession;importcom.stu.po.Student;importcom.stu.service.StudentService;importcom.stu.service.StudentServiceImpl;@WebServlet("/LoginServlet")publicclassLoginServletextendsHttpServlet{@OverrideprotectedvoiddoGet(HttpServletRequest req,HttpServletResponse resp)throwsServletException,IOException{this.doPost(req, resp);}@OverrideprotectedvoiddoPost(HttpServletRequest request,HttpServletResponse response)throwsServletException,IOException{StudentService service =newStudentServiceImpl();HttpSession session = request.getSession();if(session.getAttribute("loginErrorMessage")!=null){
            session.invalidate();}String uid = request.getParameter("uid");String pwd = request.getParameter("pwd");int _uid =Integer.parseInt(uid);boolean result = service.login(_uid, pwd);if(result){
            session.setAttribute("login","log");
            response.sendRedirect("main.jsp");}else{
            response.sendRedirect("index.jsp");}}}

② 用户注册表示层 (RegisterServlet.java)

packagecom.stu.servlet;importjava.io.IOException;importjavax.servlet.ServletException;importjavax.servlet.annotation.WebServlet;importjavax.servlet.http.HttpServlet;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importjavax.servlet.http.HttpSession;importcom.stu.po.Student;importcom.stu.service.StudentService;importcom.stu.service.StudentServiceImpl;@WebServlet("/RegisterServlet")publicclassRegisterServletextendsHttpServlet{@OverrideprotectedvoiddoGet(HttpServletRequest req,HttpServletResponse resp)throwsServletException,IOException{this.doPost(req, resp);}@OverrideprotectedvoiddoPost(HttpServletRequest request,HttpServletResponse response)throwsServletException,IOException{StudentService service =newStudentServiceImpl();String uid = request.getParameter("uid");String pwd = request.getParameter("pwd");int _uid =Integer.parseInt(uid);boolean result = service.addLogin(_uid,pwd);if(!result){
            request.setAttribute("register","reg");
            request.getRequestDispatcher("index.jsp").forward(request, response);}else{
            request.getRequestDispatcher("register.jsp").forward(request, response);}}}

③ 分页查询表示层 (ShowStudentsByPageServlet.java)

packagecom.stu.servlet;importjava.io.IOException;importjava.util.List;importjavax.servlet.ServletException;importjavax.servlet.annotation.WebServlet;importjavax.servlet.http.HttpServlet;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importjavax.servlet.http.HttpSession;importcom.stu.po.Page;importcom.stu.po.Student;importcom.stu.service.StudentService;importcom.stu.service.StudentServiceImpl;@WebServlet("/ShowStudentsByPageServlet")publicclassShowStudentsByPageServletextendsHttpServlet{@OverrideprotectedvoiddoGet(HttpServletRequest request,HttpServletResponse response)throwsServletException,IOException{StudentServiceService=newStudentServiceImpl();int count =Service.getTotalCount();Page page =newPage();String currentPage = request.getParameter("currentPage");if(currentPage ==null){
            currentPage ="0";}int _currentPage =Integer.parseInt(currentPage);
        page.setCurrentPage(_currentPage);int totalCount =Service.getTotalCount();
        page.setTotalCount(totalCount);int pageSize =5;int totalPage =(totalCount / pageSize)+1;
        page.setTotalPage(totalPage+1);

        page.setPageSize(pageSize);List<Student> student =Service.queryStudentsByPageNo(_currentPage, pageSize);
        page.setStudent(student);

        request.setAttribute("page1", page);
        request.getRequestDispatcher("showAllStudentsByPageNo.jsp").forward(request, response);}}

④ 查询所学生信息表示层 (ShowAllStudentsServlet.java)

packagecom.stu.servlet;importjava.io.IOException;importjava.util.List;importjavax.servlet.ServletException;importjavax.servlet.annotation.WebServlet;importjavax.servlet.http.HttpServlet;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importjavax.servlet.http.HttpSession;importcom.stu.po.Student;importcom.stu.service.StudentService;importcom.stu.service.StudentServiceImpl;@WebServlet("/ShowAllStudentsServlet")publicclassShowAllStudentsServletextendsHttpServlet{@OverrideprotectedvoiddoGet(HttpServletRequest request,HttpServletResponse response)throwsServletException,IOException{StudentService service =newStudentServiceImpl();HttpSession  session =   request.getSession();List<Student> allStudents = service.getAllStudents();
        session.setAttribute("allStudents", allStudents);
        response.sendRedirect("showAllStudents.jsp");}}

⑤ 添加学生表示层 (AddServlet.java)

packagecom.stu.servlet;importcom.stu.po.Student;importcom.stu.service.StudentService;importcom.stu.service.StudentServiceImpl;importjavax.servlet.ServletException;importjavax.servlet.annotation.WebServlet;importjavax.servlet.http.HttpServlet;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importjavax.servlet.http.HttpSession;importjava.io.IOException;@WebServlet("/AddServlet")publicclassAddServletextendsHttpServlet{@OverrideprotectedvoiddoGet(HttpServletRequest req,HttpServletResponse resp)throwsServletException,IOException{this.doPost(req, resp);}@OverrideprotectedvoiddoPost(HttpServletRequest request,HttpServletResponse response)throwsServletException,IOException{StudentService service =newStudentServiceImpl();String sno  = request.getParameter("sno");String sname  = request.getParameter("sname");String sex  = request.getParameter("sex");String age  = request.getParameter("age");String phone  = request.getParameter("phone");int _sno =0;if(sno !=null||"".equals(sno)){
            _sno =Integer.parseInt(sno);}int _age =0;if(age !=null||"".equals(age)){
            _age =Integer.parseInt(age);}Student s =newStudent(_sno, sname, sex, _age, phone);int result = service.addStudent(s);HttpSession session = request.getSession();
        session.setAttribute("student","stu");
        response.sendRedirect("main.jsp");}}

⑥ 删除学生表示层 (DeleteServlet.java)

packagecom.stu.servlet;importcom.stu.po.Student;importcom.stu.service.StudentService;importcom.stu.service.StudentServiceImpl;importjavax.servlet.ServletException;importjavax.servlet.annotation.WebServlet;importjavax.servlet.http.HttpServlet;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importjava.io.IOException;@WebServlet("/DeleteServlet")publicclassDeleteServletextendsHttpServlet{protectedvoiddoGet(HttpServletRequest request,HttpServletResponse response)throwsServletException,IOException{//1.获取snoString sno = request.getParameter("sno");int _sno =0;if(sno !=null&&!"".equals(sno)){
            _sno =Integer.parseInt(sno);}//2.执行删除StudentService service =newStudentServiceImpl();Student stu = service.deleteStudent(_sno);//3.跳转到列表页
        request.setAttribute("stu", stu);
        request.getRequestDispatcher("ShowAllStudentsServlet").forward(request,response);}}

⑦ 根据学号查询学生信息表示层 (QueryStudentBySnoSevlet.java)

packagecom.stu.servlet;importcom.stu.po.Student;importcom.stu.service.StudentService;importcom.stu.service.StudentServiceImpl;importjavax.servlet.ServletException;importjavax.servlet.annotation.WebServlet;importjavax.servlet.http.HttpServlet;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importjava.io.IOException;@WebServlet("/QueryStudentBySnoServlet")publicclassQueryStudentBySnoServletextendsHttpServlet{@OverrideprotectedvoiddoGet(HttpServletRequest request,HttpServletResponse response)throwsServletException,IOException{//获取sno;String sno = request.getParameter("sno");int _sno =0;if(sno !=null&&!"".equals(sno)){
            _sno =Integer.parseInt(sno);}//2.查询学生数据StudentService service =newStudentServiceImpl();Student student = service.queryStudentBySno(_sno);//3.显示数据//存数据
        request.setAttribute("student", student);//跳转
        request.getRequestDispatcher("updateStudent.jsp").forward(request,response);}}

⑧ 修改学生信息表示层 (UpdateServlet.java)

packagecom.stu.servlet;importcom.stu.po.Student;importcom.stu.service.StudentService;importcom.stu.service.StudentServiceImpl;importjavax.servlet.ServletException;importjavax.servlet.annotation.WebServlet;importjavax.servlet.http.HttpServlet;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importjavax.servlet.http.HttpSession;importjava.io.IOException;importjava.util.List;@WebServlet("/UpdateServlet")publicclassUpdateServletextendsHttpServlet{protectedvoiddoGet(HttpServletRequest request,HttpServletResponse resp)throwsServletException,IOException{String sno = request .getParameter("sno");String sname  = request.getParameter("sname");String sex  = request.getParameter("sex");String age  = request.getParameter("age");String phone  = request.getParameter("phone");int _sno =0;if(sno !=null&&!"".equals(sno)){
            _sno =Integer.parseInt(sno);}int _age =0;if(age !=null&&!"".equals(age)){
            _age =Integer.parseInt(age);}Student stu =newStudent(_sno, sname, sex, _age, phone);StudentService service =newStudentServiceImpl();
        service.updateStudentBySno(_sno,stu);//3.跳转界面
        request.getRequestDispatcher("ShowAllStudentsServlet").forward(request, resp);}}

⑨ 退出登录表示层 (QuitServlet.java)

packagecom.stu.servlet;importjava.io.IOException;importjavax.servlet.ServletException;importjavax.servlet.annotation.WebServlet;importjavax.servlet.http.HttpServlet;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importjavax.servlet.http.HttpSession;@WebServlet("/QuitServlet")publicclassQuitServletextendsHttpServlet{@OverrideprotectedvoiddoGet(HttpServletRequest request,HttpServletResponse resp)throwsServletException,IOException{HttpSession  session =   request.getSession();
        session.invalidate();//清空session对象中的所有属性数据内容
        resp.sendRedirect("index.jsp");}}

(2)业务逻辑层service

① Service接口(StudentService.java)

packagecom.stu.service;importjava.util.List;importcom.stu.po.Student;publicinterfaceStudentService{//service表示业务逻辑层,定义的每一个方法实际上对应的就是用户的一个需求(请求)publicbooleanlogin(int uid,String pwd);publicbooleanaddLogin(int uid,String pwd);publicList<Student>getAllStudents();publicList<Student>queryStudentsByPageNo(int current,int pageSize);publicStudentdeleteStudent(int sno);publicStudentqueryStudentBySno(int sno);publicintupdateStudentBySno(int sno,Student stu);publicintgetTotalCount();publicintaddStudent(Student student);}

② 接口的实现类(StudentServiceImpl.java)

packagecom.stu.service;importjava.util.List;importcom.stu.dao.StudentDao;importcom.stu.dao.StudentDaoImpl;importcom.stu.po.Student;publicclassStudentServiceImplimplementsStudentService{StudentDao dao =newStudentDaoImpl();//登陆@Overridepublicbooleanlogin(int uid,String pwd){return dao.login(uid, pwd);}// 注册@OverridepublicbooleanaddLogin(int uid,String pwd){return dao.addLogin(uid, pwd);}// 查询所有学生@OverridepublicList<Student>getAllStudents(){return dao.getAllStudents();}// 分页查询@OverridepublicList<Student>queryStudentsByPageNo(int current,int pageSize){return dao.queryStudentByPage(current,pageSize);}// 删除学生@OverridepublicStudentdeleteStudent(int sno){return dao.deleteStudent(sno);}// 修改学生信息,要先根据学号查询学生信息publicStudentqueryStudentBySno(int sno){return dao.queryStudentBySno(sno);}//更改学生信息publicintupdateStudentBySno(int sno,Student stu){return dao.updateStudentBySno(sno,stu);}//查询总条数@OverridepublicintgetTotalCount(){return dao.getTotalCount();}@OverridepublicintaddStudent(Student student){return dao.addStudent(student);}}

(3)数据访问层dao

① 接口(StudentDao.java)

packagecom.stu.dao;importjava.util.List;importcom.stu.po.Student;publicinterfaceStudentDao{publicbooleanlogin(int uid ,String pwd);publicbooleanaddLogin(int uid,String pwd);publicList<Student>getAllStudents();publicList<Student>queryStudentByPage(int currentPage,int pageSize);publicStudentdeleteStudent(int sno);publicStudentqueryStudentBySno(int sno);publicintupdateStudentBySno(int sno,Student stu);//查询总数据数publicintgetTotalCount();publicintaddStudent(Student student);}

② 接口的实现类(StudentDaoImpl.java)

packagecom.stu.dao;importjava.sql.Connection;importjava.sql.DriverManager;importjava.sql.ResultSet;importjava.sql.SQLException;importjava.sql.Statement;importjava.util.ArrayList;importjava.util.List;importcom.stu.po.Student;importcom.stu.utils.DBTools;publicclassStudentDaoImplimplementsStudentDao{Connection conn =null;// 连接对象Statement st =null;// 语句对象ResultSet rs =null;// 结果集合对象@Overridepublicbooleanlogin(int uid,String pwd){// 在这里需要连接数据库,根据int sno, String pwd这两个参数来查询student表// jdbc// 1:配置环境,下载数据库连接驱动jar文件,拷贝到项目中来// 2:加载驱动,根据驱动创建数据库的连接对象try{Class.forName(DBTools.DRIVER_CLASS);// 加载驱动

            conn =DriverManager.getConnection(DBTools.CONN_STR,DBTools.USRENAME,DBTools.PWD);// 3:执行sql语句,完成对数据库中表的数据的增删该查。必须创建一个语句对象(执行sql语句的)
            st = conn.createStatement();int count =0;String sqlStr ="select * from login where uid ="+ uid +" and pwd = '"+ pwd +"'";

            rs = st.executeQuery(sqlStr);while(rs.next()){
                count++;}if(count>0)returntrue;elsereturnfalse;}catch(ClassNotFoundException e){
            e.printStackTrace();}catch(SQLException e){
            e.printStackTrace();}returnfalse;}@OverridepublicList<Student>getAllStudents(){try{Class.forName(DBTools.DRIVER_CLASS);// 加载驱动

            conn =DriverManager.getConnection(DBTools.CONN_STR,DBTools.USRENAME,DBTools.PWD);// 3:执行sql语句,完成对数据库中表的数据的增删该查。必须创建一个语句对象(执行sql语句的)
            st = conn.createStatement();String sqlStr ="select * from student";

            rs = st.executeQuery(sqlStr);List<Student> allStudents =newArrayList<Student>();while(rs.next()){int _sno = rs.getInt(1);String _sname = rs.getString(2);String _sex = rs.getString(3);int _age = rs.getInt(4);String _phone = rs.getString(5);Student s =newStudent(_sno, _sname, _sex, _age, _phone);
                allStudents.add(s);}return allStudents;}catch(ClassNotFoundException e){
            e.printStackTrace();}catch(SQLException e){
            e.printStackTrace();}returnnull;}publicList<Student>queryStudentByPage(int current,int pageSize){try{Class.forName(DBTools.DRIVER_CLASS);// 加载驱动

            conn =DriverManager.getConnection(DBTools.CONN_STR,DBTools.USRENAME,DBTools.PWD);// 3:执行sql语句,完成对数据库中表的数据的增删该查。必须创建一个语句对象(执行sql语句的)
            st = conn.createStatement();int startPosition = current * pageSize;String sqlStr ="select * from student limit "+ startPosition +","+ pageSize;
            rs = st.executeQuery(sqlStr);List<Student> allStudents =newArrayList<Student>();while(rs.next()){int _sno = rs.getInt(1);String _sname = rs.getString(2);String _sex = rs.getString(3);int _age = rs.getInt(4);String _phone = rs.getString(5);Student s =newStudent(_sno, _sname, _sex, _age, _phone);
                allStudents.add(s);}return allStudents;}catch(ClassNotFoundException e){
            e.printStackTrace();}catch(SQLException e){
            e.printStackTrace();}returnnull;}publicintgetTotalCount(){//查询总数据数try{Class.forName(DBTools.DRIVER_CLASS);// 加载驱动

            conn =DriverManager.getConnection(DBTools.CONN_STR,DBTools.USRENAME,DBTools.PWD);// 3:执行sql语句,完成对数据库中表的数据的增删该查。必须创建一个语句对象(执行sql语句的)
            st = conn.createStatement();String sql ="select count(*) from student";
            rs = st.executeQuery(sql);while(rs.next()){int totalCount = rs.getInt(1);}}catch(Exception e){
            e.printStackTrace();}return0;}@OverridepublicintaddStudent(Student student){try{Class.forName(DBTools.DRIVER_CLASS);// 加载驱动

            conn =DriverManager.getConnection(DBTools.CONN_STR,DBTools.USRENAME,DBTools.PWD);
            st = conn.createStatement();String sqlStr ="insert into student values("+student.getSno()+",'"+ student.getSname()+"','"+ student.getSex()+"',"+student.getAge()+",'"+student.getPhone()+"')";System.out.println(sqlStr);int result = st.executeUpdate(sqlStr);}catch(ClassNotFoundException e){
            e.printStackTrace();}catch(SQLException e){
            e.printStackTrace();}return0;}@OverridepublicbooleanaddLogin(int uid,String pwd){try{Class.forName(DBTools.DRIVER_CLASS);// 加载驱动

            conn =DriverManager.getConnection(DBTools.CONN_STR,DBTools.USRENAME,DBTools.PWD);
            st = conn.createStatement();String sqlStr ="insert into login values("+ uid +",'"+ pwd +"')";int result = st.executeUpdate(sqlStr);}catch(ClassNotFoundException e){
            e.printStackTrace();}catch(SQLException e){
            e.printStackTrace();}returnfalse;}@OverridepublicStudentdeleteStudent(int sno){try{Class.forName(DBTools.DRIVER_CLASS);// 加载驱动
            conn =DriverManager.getConnection(DBTools.CONN_STR,DBTools.USRENAME,DBTools.PWD);
            st = conn.createStatement();String sqlStr ="delete from student where sno = "+ sno;System.out.println(sqlStr);int result = st.executeUpdate(sqlStr);}catch(Exception e){
            e.printStackTrace();}returnnull;}@OverridepublicStudentqueryStudentBySno(int sno){try{Class.forName(DBTools.DRIVER_CLASS);// 加载驱动

            conn =DriverManager.getConnection(DBTools.CONN_STR,DBTools.USRENAME,DBTools.PWD);

            st = conn.createStatement();String sqlStr ="select * from student where sno = "+ sno;
            rs = st.executeQuery(sqlStr);if(rs.next()){int _sno = rs.getInt(1);String _sname = rs.getString(2);String _sex = rs.getString(3);int _age = rs.getInt(4);String _phone = rs.getString(5);Student s =newStudent(_sno, _sname, _sex, _age, _phone);return s;}}catch(Exception e){
            e.printStackTrace();}returnnull;}@OverridepublicintupdateStudentBySno(int sno,Student stu){try{Class.forName(DBTools.DRIVER_CLASS);// 加载驱动
            conn =DriverManager.getConnection(DBTools.CONN_STR,DBTools.USRENAME,DBTools.PWD);
            st = conn.createStatement();String sql ="update student set sname= '"+stu.getSname()+"', sex='"+stu.getSex()+"', age="+stu.getAge()+", phone='"+stu.getPhone()+"' where sno="+sno;System.out.println(sql);int result = st.executeUpdate(sql);}catch(Exception e){
            e.printStackTrace();}return0;}}
标签: servlet java 数据库

本文转载自: https://blog.csdn.net/weixin_52849365/article/details/127349023
版权归原作者 小菜鸟想逆袭 所有, 如有侵权,请联系我们删除。

“JavaWeb实现学生管理系统”的评论:

还没有评论