学生管理系统优化
1.解决乱码
使用过滤器实现所有资源的编码统一。
2.检查登录
使用过滤器实现校验是否登陆问题
3.优化JSP页面
通过EL表达式和JSTL替换之前的Java代码块和JSP表达式
获取 真实路径
request.getContextPath()+/login.jsp
目录结构如下
实体类 Student
package com.itheima.bean; public class Student { private String username; private int age; private int score; public Student() { } public Student(String username, int age, int score) { this.username = username; this.age = age; this.score = score; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public int getScore() { return score; } public void setScore(int score) { this.score = score; } @Override public String toString() { return "Student{" + "username='" + username + '\'' + ", age=" + age + ", score=" + score + '}'; } }
解决全局乱码问题过滤器
package com.itheima.filter; import javax.servlet.*; import javax.servlet.annotation.WebFilter; import javax.servlet.annotation.WebListener; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /* * 解决全局乱码问题 * */ @WebFilter("/*") public class EncodingFilter implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { //1.将请求和响应对象转换为和http协议相关 HttpServletRequest request= (HttpServletRequest) servletRequest; HttpServletResponse response= (HttpServletResponse) servletResponse; //2.设置编码格式 request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); //放行 filterChain.doFilter(request,response); } }
限制必须登录 过滤器
package com.itheima.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","/listStudentServlet"}) public class LoginFilter implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { //1.将请求和响应对象转换为和http协议相关 HttpServletRequest request= (HttpServletRequest) servletRequest; HttpServletResponse response= (HttpServletResponse) servletResponse; //2.获取会话域对象中的数据 Object username = request.getSession().getAttribute("username"); //3.判断用户名 if (username == null||"".equals(username)) { //重定向到登陆页面 response.sendRedirect(request.getContextPath()+"/login.jsp"); return; } //4.放行 filterChain.doFilter(request,response); } }
添加Servlet
package com.itheima.servlet; import com.itheima.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("/addStudentServlet") 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 stu=new Student(); stu.setUsername(username); stu.setAge(Integer.parseInt(age)); stu.setScore(Integer.parseInt(score)); //3.将学生对象的数据保存到d:\\stu.txt中 BufferedWriter bw=new BufferedWriter(new FileWriter("d:\\stu.txt",true)); bw.write(stu.getUsername()+","+stu.getAge()+","+stu.getScore()); bw.newLine(); bw.close(); //通过定时刷新功能相应给浏览器 //resp.setContentType("text/html;charset=UTF-8"); resp.getWriter().write("添加成功。2秒后自动跳转到首页"); resp.setHeader("Refresh","2;URL="+req.getContextPath()+"/index.jsp"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
查看功能的Servlet
package com.itheima.servlet; import com.itheima.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.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; /** * 实现查看功能 * */ @WebServlet("/listStudentServlet") public class ListStudentServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //1.创建一个字符输入流对象,关联读取的文件 BufferedReader br=new BufferedReader(new FileReader("d:\\stu.txt")); //2.创建集合对象,保存Student对象 ArrayList<Student> list=new ArrayList<>(); //3.循环读取文件中的数据,将数据封装到Student对象中,在把多个对象添加到集合中 String line; while((line= br.readLine())!=null){ //张三,23,90 Student stu=new Student(); String[] split = line.split(","); stu.setUsername(split[0]); stu.setAge(Integer.parseInt(split[1])); stu.setScore(Integer.parseInt(split[2])); list.add(stu); } //4.将集合对象存入到会话域中 req.getSession().setAttribute("students",list); //重定向到学生列表页面 resp.sendRedirect(req.getContextPath() +"/listStudent.jsp"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
学生登陆的Servlet
package com.itheima.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("/loginStudentServlet") public class LoginStudentServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //获取到用户名和密码 String username = req.getParameter("username"); String password = req.getParameter("password"); //2.判断用户名 if (username == null||"".equals(username)) { //2.1用户名为空,重定向到登陆页面 resp.sendRedirect(req.getContextPath()+"/login.jsp"); return; } //2.2用户名不为空,将用户名存入到会话域对象中 req.getSession().setAttribute("username",username); //3.重定向到首页 resp.sendRedirect(req.getContextPath()+"/index.jsp"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
添加学生页面addStudent.jsp
<%-- Created by IntelliJ IDEA. User: 12270 Date: 2021/3/18 Time: 22:03 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}/addStudentServlet" 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>
主页面index.jsp
<%-- Created by IntelliJ IDEA. User: 12270 Date: 2021/3/18 Time: 21:39 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"%> <html> <head> <title>学生管理系统首页</title> </head> <body> <%-- 获取会话域中的数据 如果获取到了则显示添加和查看功能的超链接 如果没获取到则显示登录功能额超链接 --%> <c:if test="${sessionScope.username eq null}"> <a href="${pageContext.request.contextPath}/login.jsp">请登录</a> </c:if> <c:if test="${sessionScope.username ne null}"> <a href="${pageContext.request.contextPath}/addStudent.jsp">添加学生</a> <a href="${pageContext.request.contextPath}/listStudentServlet">查看学生</a> </c:if> </body> </html>
展示学生页面listStudent.jsp
<%@ page import="java.util.ArrayList" %> <%@ page import="com.itheima.bean.Student" %><%-- Created by IntelliJ IDEA. User: 12270 Date: 2021/3/18 Time: 22:27 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"%> <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> <td>${s.username}</td> <td>${s.age}</td> <td>${s.score}</td> </tr> </c:forEach> </table> </body> </html>
登陆页面login.jsp
<%-- Created by IntelliJ IDEA. User: 12270 Date: 2021/3/18 Time: 21:46 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}/loginStudentServlet" method="get"autocomplete="off"> 姓名:<input type="text" name="username"><br> 密码:<input type="password" name="password"><br> <button type="submit">登录</button> </form> </body> </html>