JSP实现学生管理系统

登录功能

  1. 创建一个web项目
  2. 在web目录下创建一个index.jsp
  3. 在页面中获取会话域中的用户名,获取到了就显示添加和查看功能的超链接,没获取到就显示登录功能
  4. 在web目录下创建一个login.jsp。实现登录页面
  5. 创建loginServlet,获取用户名和密码
  6. 如果用户名为空,则重定向到登录页面
  7. 如果不为空,将用户添加到会话域中,在重定向到首页
  • 创建一个web项目,在web路径下创建一个index.jsp
<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
    <title>学生管理系统首页</title>
</head>
<body>
<%--
    获取会话域中的数据
    如果获取到了则显示添加和查看功能的超连接
    如果没有获取到则显示登录功能的超链接
--%>
    <c:if test="${sessionScope.username eq null}" >
        <a href="${pageContext.request.contextPath}/login.jsp">请登录
    </c:if>
    <c:if test="${sessionScope.username ne null}" >
            <a href="${pageContext.request.contextPath}/addStudent.jsp">添加学生</a>
            <a href="${pageContext.request.contextPath}/list">查看学生</a>
    </c:if>

</body>
</html>
  • 在web目录下创建一个login.jsp.实现登录页面
<%--
  Created by IntelliJ IDEA.
  User: heroma
  Date: 2022/1/28
  Time: 5:02 下午
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>学生登录</title>
</head>
<body>
    <form action="${pageContext.request.contextPath}/login" method="get" autocomplete="off">
        姓名:<input type="text" name="username"><br>
        密码:<input type="password" name="password"><br>
        <button type="submit">登录</button>
    </form>
</body>
</html>

  • 创建LoginStudentServlet,获取用户名和密码

    package com.example.jsp_demo.servlet;
    
    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("/login")
    public class LoginStudentServlet extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            //1.获取用户名和密码
            String username = req.getParameter("username");
            String password = req.getParameter("password");
            //2.判断用户名
            if (username == null || username.equals("")){
                resp.sendRedirect("/stu/login.jsp");
                return;
            }
            //3.用户名不为空,将用户名存入会话域中
            req.getSession().setAttribute("username", username);
            //4. 重定向到首页
            resp.sendRedirect("/stu/index.jsp");
        }
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            doGet(req,resp);
        }
    }
    

添加功能实现

  • 在web目录下创建一个addStudent.jsp,实现添加学生的表单项
<%--
  Created by IntelliJ IDEA.
  User: heroma
  Date: 2022/1/28
  Time: 5:04 下午
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%%>
<html>
<head>
    <title>添加学生</title>
</head>
<body>
    <form action="${pageContext.request.contextPath}/add" method="get" autocomplete="off">
        学生姓名:<input type="text" name="username"><br>
        学生年龄:<input type="number" name="age"><br>
        学生成绩:<input type="number" name="score"><br>
        <button type="submit">保存</button>
    </form>
</body>
</html>

  • 创建AddStudentServlet,获取并保存到文件夹中

    package com.example.jsp_demo.servlet;
    
    import com.example.jsp_demo.bean.Student;
    
    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.BufferedWriter;
    import java.io.FileWriter;
    import java.io.IOException;
    
    @WebServlet("/add")
    public class AddStudentServlet extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            //1.获取表单中的数据
            String username = req.getParameter("username");
            String age = req.getParameter("age");
            String score = req.getParameter("score");
            //2.创建学生对象并赋值
            Student student = new Student(username, Integer.parseInt(age), Integer.parseInt(score));
            //3.将学生对象保存到文件中
            String realPath = getServletContext().getRealPath("/resource/stu.txt");
            System.out.println(realPath);
            BufferedWriter bw = new BufferedWriter(new FileWriter(realPath,true));
            bw.write(student.getUsername() + "," + student.getAge() + "," + student.getScore());
            bw.newLine();
            bw.close();
            //4.通过定时刷新功能相应给浏览器
            //resp.setContentType("text/html;charset=UTF-8");
            resp.getWriter().write("添加成功,1秒后自动跳转首页......");
            resp.setHeader("Refresh","1;URL=/stu/index.jsp");
        }
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            doGet(req,resp);
        }
    }
    

查看学生功能

  • 创建ListStudentServlet,读取文件中的学生信息到消息集合中

    package com.example.jsp_demo.servlet;
    
    import com.example.jsp_demo.bean.Student;
    
    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.*;
    import java.util.ArrayList;
    
    @WebServlet("/list")
    public class ListStudentServlet extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            //1.创建字符输入流,关联相关文件
            String realPath = getServletContext().getRealPath("/resource/stu.txt");
            System.out.println(realPath);
            BufferedReader br = new BufferedReader(new FileReader(realPath));
            //2.创建集合对象,用来保存学生对象
            ArrayList<Student> students = new ArrayList<>();
            //3.循环读取文件中的数据,将数据封装到student对象中,再把多个学生对象添加到集合中
            String line;
            while ((line = br.readLine()) != null ){
                String[] s = line.split(",");
                Student student = new Student(s[0], Integer.parseInt(s[1]), Integer.parseInt(s[2]));
                students.add(student);
            }
            //4.将集合对象保存到会话中去
            req.getSession().setAttribute("students",students);
            //5.将页面重定向到学生列表页面
            resp.sendRedirect("/stu/list.jsp");
        }
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            super.doPost(req, resp);
        }
    }
    
  • 在web目录下创建一个list.jsp

<%@ page import="java.util.ArrayList" %>
<%@ page import="com.example.jsp_demo.bean.Student" %><%--
  Created by IntelliJ IDEA.
  User: heroma
  Date: 2022/1/28
  Time: 5:41 下午
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>查看学生</title>
</head>
<body>
    <table width="600px" border="1px">
        <tr>
            <th>学生姓名</th>
            <th>学生年龄</th>
            <th>学生成绩</th>
        </tr>
        <c:forEach items="${students}" var="s">
            <tr align="center">
                <td>${s.username}</td>
                <td>${s.age}</td>
                <td>${s.score}</td>
            </tr>
        </c:forEach>
    </table>
</body>
</html>

  • 通过过滤器解决乱码问题
package com.example.jsp_demo.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;

@WebFilter("/*")
public class EncodingFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
       
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //1.将请求和响应转化为http协议相关的
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        //2.设置编码格式
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        //3.执行
        filterChain.doFilter(req,resp);
    }

    @Override
    public void destroy() {

    }
}

  • 登录校验
package com.example.jsp_demo.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(value = {"/addStudent.jsp", "/list"})
public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //1.将请求和响应转化为http协议相关的
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        //2.获取会话域对象数据
        Object username = req.getSession().getAttribute("username");
        System.out.println(username);
        //3.判断用户名
        if (username == null || "".equals(username)){
            resp.sendRedirect(req.getContextPath() + "/login.jsp");
            return;
        }
        //4.放行
        filterChain.doFilter(req,resp);
    }
}

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐