前后端交互,实现学生管理系统的部分功能,使用过滤器,过滤管理员未登录不能进行学生管理,并且使用tomcat发布。

前后端交互,实现学生管理系统的部分功能,并且使用tomcat发布。

过滤器

使用IO流,与.txt文件进行交互,因此只是实现了部分功能,包括管理员登录功能,登录成功后进行学生的添加和查询功能。

使用了Filter过滤器 ,用户没有登录的情况下是不能进行对学生的管理操作。

首先进行配置:

使用了Beanutils工具类,以及jstl技术,因此需要导入三个jar包

commons-beanutils-1.7.0.jar
commons-logging-1.2.jar
jstl-1.2.jar

过滤器的配置文件代码如下:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"      
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"         version="4.0"><filter>   
  <filter-name>login</filter-name>    
  <filter-class>com.zy.utils.LoginFilter</filter-class>
  </filter>    
  <filter-mapping>       
   <filter-name>login</filter-name>    
     <url-pattern>/addStudent</url-pattern>    
     </filter-mapping>    
     <filter-mapping>        
     <filter-name>login</filter-name>        
     <url-pattern>/selStudent</url-pattern>    
     </filter-mapping>    
     <filter-mapping>        
     <filter-name>login</filter-name>        
     <url-pattern>/login/addStudent.jsp</url-pattern>   
     </filter-mapping>    
     <filter-mapping>        
     <filter-name>login</filter-name>       
      <url-pattern>/login/selStudent.jsp</url-pattern>    
      </filter-mapping>
      </web-app>

后端代码展示如下:

首先是servlet层,因为未使用框架,所以所有功能的servlet都是分开的。

管理员登录 StudentLoginServlet.java

@WebServlet("/login")
public class StudentLoginServlet extends HttpServlet {
    private StudentService studentService = new StudentService();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
        //设置编码格式,防止乱码
        resp.setContentType("text/html;charset=UTF-8");
        //获取session
        HttpSession session = req.getSession();
        //获取前端的请求信息
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        // 获取虚拟路径
        String contextPath = req.getContextPath();
        //将登录 信息交给service层处理,并返回登录结果
        boolean flag = studentService.getSuccess(username, password);
        //如果登录成功
        if (flag) {

            try {
                //将登录信息写入session中,
                session.setAttribute("username", username);
                session.setAttribute("password", password);
                //登录成功,跳转到管理页面
                resp.sendRedirect(contextPath + "/login/index.jsp");
            } catch (IOException e) {
                e.printStackTrace();
            }
           //如果登录失败,则使用请求转发回到登录页面,并给出提示信息
        } else {

            try {
                req.setAttribute("errMsg", "用户名或密码错误,请重新输入");
                req.getRequestDispatcher("/login/login.jsp").forward(req, resp);
            } catch (ServletException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}


添加学生 AddStudentServlet.java

@WebServlet("/addStudent")
public class AddStudentServlet extends HttpServlet {
    private StudentService studentService = new StudentService();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        req.setCharacterEncoding("utf-8");
        //首先接收来自浏览器的请求,封装成一个对象。将这个对象传到dao层,在dao层进行业务逻辑判断
        Map<String, String[]> map = req.getParameterMap();
        //创建学生对象
        Student student = new Student();
        //将信息封装
        String contextPath = req.getContextPath();
        try {
            BeanUtils.populate(student, map);


        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        //首先判断接收到的学生id是否存在
        String[] id = map.get("id");
        if (id != null && id.length != 0) {
            //调用service层。返回一个结果
            try {
                boolean flag = studentService.isUsed(id);
                if (flag) {
                    req.setAttribute("msg", "学号已存在,请重新输入");
                    req.getRequestDispatcher("/login/addStudent.jsp").forward(req, resp);
                } else {
                    boolean result = studentService.addStudent(student);
                    resp.getWriter().write("添加成功,2秒后跳转到学生列表");
                    resp.setHeader("Refresh", "2;URL="+contextPath+"/selStudent");

                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } //调用service层,返回一个添加结果
        else {
            req.setAttribute("msg1", "您输入的信息有误,请重新输入");
            req.getRequestDispatcher("/login/addStudent.jsp").forward(req, resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

查询学生 SelStudentServlet.java

@WebServlet("/selStudent")
public class SelStudentServlet extends HttpServlet {
    private StudentService studentService = new StudentService();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        try {
            ArrayList<Student> al = studentService.findStudent();
            req.setAttribute("al", al);
            req.getRequestDispatcher("/login/selStudent.jsp").forward(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
      /*  HttpSession session = req.getSession();
        session.setAttribute("al",al);*/
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

Service层
StudentSevice.java

public class StudentService {
    private StudentDao studentDao = new StudentDao();

    public boolean getSuccess(String username, String password) {
        boolean flag = false;

        //如果用户和密码正确,返回true ,如果用户和密码错误,返回false
        if (username.equals("AfterSunday")) {
            if (password.equals("123456")) {
                flag = true;
            } else {
                flag = false;
            }
        } else {
            flag = false;
        }
        return flag;
    }

    public boolean isUsed(String[] id) throws Exception {
        //调用service层,接收到dao的学生集合
        ArrayList<Student> al = studentDao.findStudent();
        boolean flag = false;
        if (al == null || al.size() == 0 || id.length == 0 || id == null) {
            return flag;
        } else {
            for (int i = 0; i < al.size(); i++) {
                Student student = al.get(i);
                if (student.getId().equals(id[0])) {
                    //存在则为true
                    flag = true;
                    break;
                } else {
                    flag = false;
                }
            }
        }

        return flag;
    }

    public boolean addStudent(Student student) throws IOException {
        //调用dao层完成添加
        boolean result = studentDao.addStudent(student);
        return result;
    }

    public ArrayList<Student> findStudent() throws Exception {

        ArrayList<Student> al = studentDao.findStudent();

        return al;
    }
}

Dao层
StudentDao.java

public class StudentDao {


    public ArrayList<Student> findStudent() throws Exception {
        //设置编码集
        //首先通过字符流获取文件
        BufferedReader bf = new BufferedReader(new FileReader("G:\\code\\code\\JavaChow\\JavaChou\\StudentManager-Web-MVC(controller+service+dao)\\web\\student.txt"));
        //创建集合,将信息封装到集合中
        ArrayList<Student> al = new ArrayList<>();

        /*
        添加学生,判断一次添加一次,不要最后添加,因为while不会跳出
         */
        Student student = null;
        //读取信息,然后进行切割 ,将从文件中获取的信息加到集合中
        String line;
        while ((line = bf.readLine()) != null) {
            String[] split = line.split(",");
            if (split.length > 4) {
                String[] hobby = new String[2];
                hobby[0] = split[3];
                hobby[1] = split[4];
                student = new Student(split[0], split[1], split[2], hobby);
                al.add(student);
            } else if (split.length == 4) {
                String[] hobby = new String[1];
                hobby[0] = split[3];
                student = new Student(split[0], split[1], split[2], hobby);
                al.add(student);
            } else if (split.length == 3) {
                String[] hobby = new String[0];
                student = new Student(split[0], split[1], split[2], hobby);
                al.add(student);
            } else if (split.length == 0 || split == null) {
                al = null;
                return al;
            }

        }
        bf.close();
        return al;
    }

    public boolean addStudent(Student student) throws IOException {
        //写入文件中,
        BufferedWriter bw = new BufferedWriter(new FileWriter("G:\\code\\code\\JavaChow\\JavaChou\\StudentManager-Web-MVC(controller+service+dao)\\web\\student.txt", true));

        String[] hobby = student.getHobby();
        if (hobby.length == 1) {
            bw.write(student.getId() + "," + student.getUsername() + "," + student.getAge() + "," + hobby[0]);
            bw.newLine();
            bw.flush();

        } else if (hobby.length == 2) {
            bw.write(student.getId() + "," + student.getUsername() + "," + student.getAge() + "," + hobby[0] + "," + hobby[1]);
            bw.newLine();
            bw.flush();
        } else {
            bw.write(student.getId() + "," + student.getUsername() + "," + student.getAge());
            bw.newLine();
            bw.flush();
        }
        bw.close();
        return true;
    }
    }

学生实体类
Student.java

public class Student {
    private String id;
    private String username;
    private String age;
    private String[] hobby;

    public Student() {
    }

    public Student(String id, String username, String age, String[] hobby) {
        this.id = id;
        this.username = username;
        this.age = age;
        this.hobby = hobby;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

    public String[] getHobby() {
        return hobby;
    }

    public void setHobby(String[] hobby) {
        this.hobby = hobby;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id='" + id + '\'' +
                ", username='" + username + '\'' +
                ", age='" + age + '\'' +
                ", hobby=" + Arrays.toString(hobby) +
                '}';
    }
}

前端代码 ,采用的是jsp页面,并且使用了css样式
目录结构如下:
页面布局

web目录选的index.jsp

<%@ page import="java.util.ArrayList" %>
<%@ page contentType="text/html;charset=UTF-8" language="java"  %>
<html>
<head>
    <title>学生管理系统</title>
</head>
<body>
<div align="center">
<h1>欢迎来到德莱联盟<a href="${pageContext.request.contextPath}/login/login.jsp">立即登录</a></h1>
</div>

</body>
</html>

login目录下的
index.jsp

<%--
  Created by IntelliJ IDEA.
  User: AfterSunday
  Date: 2020/8/13
  Time: 19:56
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>学生管理系统首页</title>
</head>
<body>
<h1 align="center">登陆成功。</h1>
<%--添加学生,则是在页面中点击添加按钮,因此添加按钮需要调用到servlet--%>
<a href="addStudent.jsp" style="text-decoration: none">添加学生</a>
<%--查看学生 需要点击按钮就接收到信息,所以需要调用servlet--%>
<%--如果想要在页面查看,在哪里定义一个查看学生,点击的话 ,就出现,或者是转发,或者是重定向,跟这个原理相同--%>
<a href="/student/selStudent" style="text-decoration: none">查看学生</a>

</body>
</html>

login.jsp


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登录页面</title>
    <link rel="stylesheet" href="${pageContext.request.contextPath}/css/login.css"/>
</head>
<body>
<!--顶部公司图标-->
<div>
<img src="../img/logo.png"/>
</div>

<!--中间表单-->
<div class="center">
    <form action="/student/login" method="get">
        <table width="100%">
            <thead>
            <tr>
                <th colspan="2">账&nbsp;密&nbsp;登&nbsp;录<hr/></th>
            </tr>
            </thead>

            <tbody>
            <tr>
                <td>
                    <label for="username">账号</label>
                </td>
                <td>
                    <input type="text" id="username" name="username" placeholder=" 请输入账号" required/>
                </td>
                ${errMsg}
            </tr>
            <tr>
                <td>
                    <label for="password">密码</label>
                </td>
                <td>
                    <input type="password" id="password" name="password" placeholder=" 请输入密码" required/>
                </td>
                <%--   ${errMsg1}--%>
            </tr>

            </tbody>

            <tfoot>
            <tr>
                <td colspan="2">
                    <button type="submit">确&nbsp;定</button>
                </td>
            </tr>
            </tfoot>
        </table>

    </form>
</div>

<!--底部页脚-->
<div class="footer">
    <br/><br/>
    登录/注册即表示您同意&nbsp;&nbsp;
    <a href="#" target="_blank">用户协议</a>&nbsp;&nbsp;
    和&nbsp;&nbsp;
    <a href="#" target="_blank">隐私条款</a>&nbsp;&nbsp;&nbsp;&nbsp;
    <a href="#" target="_blank">忘记密码?</a>
</div>
</body>
</html>

addStudent.jsp

<%--
  Created by IntelliJ IDEA.
  User: AfterSunday
  Date: 2020/8/14
  Time: 20:57
  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="/student/addStudent">
    学号:<input type="text" name="id" required><br>
    姓名:<input type="text" name="username" required><br>
    年龄:<input type="text" name="age" required><br>
    爱好:篮球<input type="checkbox" name="hobby" value="篮球">
    足球<input type="checkbox" name="hobby" value="足球"><br>
    ${msg}
    ${msg1}
    <input type="submit" value="添加学生">
</form>

</body>
</html>

promit.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>提示信息</title>
    <style>
        a {
            text-decoration: none;
            color: blue;
        }

        a:hover {
            color: red;
        }
    </style>
</head>
<body>
<div align="center">
    <span> 您还没有登录,请 <a href="login.jsp">登录</a>后进行接下来的操作</span>
</div>
</body>
</html>

selStudent.jsp

<%--
  Created by IntelliJ IDEA.
  User: AfterSunday
  Date: 2020/8/14
  Time: 20:58
  To change this template use File | Settings | File Templates.
--%>

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@taglib prefix="fun" uri="http://java.sun.com/jsp/jstl/functions" %>

<html>
<head>
    <title>查看学生</title>
    <link rel="stylesheet" href="${pageContext.request.contextPath}/css/login.css">
</head>
<body>
<table>
    <tr>
        <th>编号</th>
        <th>学号</th>
        <th>姓名</th>
        <th>年龄</th>
        <th>爱好</th>
    </tr>

    <c:forEach items="${al}" var="student" varStatus="status">
        <tr>
            <td>${status.index+1}</td>
            <td>${student.id}</td>
            <td>${student.username}</td>
            <td>${student.age}</td>
            <td>${student.hobby[0]}&nbsp;${student.hobby[1]}</td>
                <%--不会爆索引越界异常--%>
                <%--<td>${student.hobby[1]}</td>--%>
            <%--<td><a href="${pageContext.request.contextPath}/login/updStudent.jsp">修改</a></td>--%>
        </tr>
    </c:forEach>

    <%-- <c:forEach items="${al}" var="student" varStatus="status">
         <c:choose>
             <c:when test="test=${fun:length(student.hobby)==0}">
                 <tr>
                     <td>${status.index+1}</td>
                     <td>${student.id}</td>
                     <td>${student.username}</td>
                     <td>${student.age}</td>
                 </tr>
             </c:when>
             <c:when test="${fun:length(student.hobby)==1}">
                 <tr>
                     <td>${status.index+1}</td>
                     <td>${student.id}</td>
                     <td>${student.username}</td>
                     <td>${student.age}</td>
                     <td>${student.hobby[0]}</td>
                 </tr>
             </c:when>
             <c:when test="${fun:length(student.hobby)==2}">
                 <tr>
                     <td>${status.index+1}</td>
                     <td>${student.id}</td>
                     <td>${student.username}</td>
                     <td>${student.age}</td>
                     <td>${student.hobby[0]}${student.hobby[1]}</td>
                 </tr>
             </c:when>
         </c:choose>
     </c:forEach>
     <td><c:forEach items="${al}" var="student">
         ${student.hobby[]}
     </c:forEach></td>--%>


    <%--<td>${student.hobby[0]}${fun:length(student.hobby)}</td>--%>
    <%--<c:if test="${student.hobby.length=1}">
     <td>${student.hobby[0]}</td>
    </c:if>--%>


</table>
</body>
</html>

css目录下的 login.css

/*背景图片*/
body{
    background: url("../img/bg.png");
}

/*中间表单样式*/
.center{
    background: white;      /*背景色*/
    width: 40%;             /*宽度*/
    margin: auto;           /*水平居中外边距*/
    margin-top: 100px;      /*上外边距*/
    border-radius: 15px;    /*边框弧度*/
    text-align: center;     /*文本水平居中*/
}

/*表头样式*/
thead th{
    font-size: 30px;    /*字体大小*/
    color: orangered;   /*字体颜色*/
}

/*表体提示信息样式*/
tbody label{
    font-size: 20px;    /*字体大小*/
}

/*表体输入框样式*/
tbody input{
    border: 1px solid gray; /*边框*/
    border-radius: 5px;     /*边框弧度*/
    width: 90%;             /*输入框的宽度*/
    height: 40px;           /*输入框的高度*/
    outline: none;          /*取消轮廓的样式*/
}

/*表底确定按钮样式*/
tfoot button{
    border: 1px solid crimson;  /*边框*/
    border-radius: 5px;         /*边框弧度*/
    width: 95%;                 /*宽度*/
    height: 40px;               /*高度*/
    background: crimson;        /*背景色*/
    color: white;               /*文字的颜色*/
    font-size: 20px;            /*字体大小*/
}

/*表行高度*/
tr{
    line-height: 60px;  /*行高*/
}

/*底部页脚样式*/
.footer{
    width: 35%; /*宽度*/
    margin: auto;   /*水平居中外边距*/
    font-size: 15px;    /*字体大小*/
    color: gray;    /*字体颜色*/
}

/*超链接样式*/
a{
    text-decoration: none;  /*去除超链接的下划线*/
    color: blue;            /*超链接颜色*/
}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值