当前位置: 首页 > news >正文

Day38

Day38

WEB-学生管理系统

详情页面index.jsp

学生角色:修改密码,修改信息

老师角色:修改密码,修改信息,查询所有学生

安全退出按钮

需要的数据:姓名,角色,username

将数据从LoginServlet中拿过来,方式一:存请求里,通过请求拿过来。

方式二:存session里,通过session拿过来。

推荐:存在session里,因为请求数据在返回成功后就会消失,但是目前需要将数据保存,所以用session。

if(user!=null){//有相关数据,登录成功request.getSession().setAttribute("username",user.getUsername());request.getSession().setAttribute("name",user.getName());request.getSession().setAttribute("role",role);response.sendRedirect("index.jsp");
}

详情页面:

<%--Created by IntelliJ IDEA.User: GuDate: 2024-06-14Time: 9:27To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>Title</title><style>body {display: flex;justify-content: center;align-items: center;height: 100vh;margin: 0;font-family: Arial, sans-serif;background: #f0f0f0;text-align: center;}</style>
</head>
<body>
<%String username = (String) session.getAttribute("username");String role = (String) session.getAttribute("role");String name = (String) session.getAttribute("name");
%><h2>欢迎<%=name %><%=(role.equals("student"))?"同学":""%><%=(role.equals("teacher"))?"老师":""%>进入学生管理系统!</h2><div><a href="repassword.jsp">修改密码</a><% if(role.equals("student")){%><a href="StuInitModifyServlet?username=<%=username%>">修改信息</a><%}%><% if(role.equals("teacher")){%><a href="TeaInitModifyServlet?username=<%=username%>">修改信息</a><a href="QueryAllStuSevlet">查询学生</a><%}%><button type="button" οnclick="doOutLogin()">安全退出</button></div><script type="text/javascript">function doOutLogin(){window.location="DoOutLoginServlet";}</script>
</body>
</html>
登录-记住我功能

登录成功后退出,再次点击登录直接跳转到详情页面

rememberMe:选中了返回on,没选中返回null

逻辑:当rememberMe非空时,把数据存到cookie里面,(不是session,session在服务器,cookie在浏览器),数据存储index.jsp所需要的数据,否则跳转过去数据为空。

一个数据为一个凭证,要做三个凭证。(要传三个数据)

使用工具类做凭证:

CookieUtil类,编写方法createCookie(String key,String value,int time)

注意:1.cookie是纯文本数据。2.存储中文的时候,使用URLEncoder.encode(value,“UTF-8”)方法把value转换为中文合法。

public static Cookie createCookie(String key,String value,int time){try {Cookie cookie = new Cookie(key, URLEncoder.encode(value,"UTF-8"));cookie.setMaxAge(time);return cookie;} catch (UnsupportedEncodingException e) {throw new RuntimeException(e);}}

然后利用该工具类添加cookie:

 if(user!=null){//有相关数据,登录成功//记住我功能if(rememberMe!=null){response.addCookie(CookieUtil.createCookie("username",user.getUsername(),60*60*24));response.addCookie(CookieUtil.createCookie("name",user.getName(),60*60*24));response.addCookie(CookieUtil.createCookie("role",role,60*60*24));}

之后再login.jsp中取凭证,如果凭证相同添加数据,都相同则直接跳转index.jsp。

<%Cookie[] cookies = request.getCookies();if(cookies!=null){int count=0;for(Cookie cookie:cookies){String key = cookie.getName();String value = URLDecoder.decode(cookie.getValue(),"UTF-8");if(key.equals("username")){session.setAttribute("username",value);count++;}if(key.equals("name")){session.setAttribute("name",value);count++;}if(key.equals("role")){session.setAttribute("role",value);count++;}}if(count==3){response.sendRedirect("index.jsp");}}%>

注意:1.cookie会自己有一个JSESSIONID,所以此刻有四个cookie。

2.需要对之前中文编码的value进行解码。

登录成功-安全退出

DoOutLoginServlet

思路:删除Session里的数据,删除cookie里的数据,跳转。

先在CookieUtil里添加删除Cookie的功能( 通过设置一个已存在的 Cookie 的过期时间为零来删除 Cookie ):

public static void removeCookie(HttpServletResponse response,String key){//通过设置一个已存在的 Cookie 的过期时间为零来删除 Cookieresponse.addCookie(createCookie(key,"",0));}

然后使用:

package com.qf.servlet;import com.qf.utils.CookieUtil;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("/DoOutLoginServlet")
public class DoOutLoginServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {this.doPost(request, response);}@Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {request.setCharacterEncoding("UTF-8");response.setContentType("text/html;charSet=UTF-8");HttpSession session = request.getSession();//删除session里的数据session.removeAttribute("username");session.removeAttribute("name");session.removeAttribute("role");//删除cookie里的数据CookieUtil.removeCookie(response,"username");CookieUtil.removeCookie(response,"name");CookieUtil.removeCookie(response,"role");//跳转response.sendRedirect("welcome.html");}
}
修改密码

从详情页面直接跳转到repassword.jsp,从session中获取账号和密码。

表单:

账号、原密码、新密码、提交、返回

判断角色和账号:

方案一:在action里面拼接,缺点:action里面的信息会显示出来。

方案二:隐藏域,input type=“hidden”

<%--Created by IntelliJ IDEA.User: GuDate: 2024-06-14Time: 13:51To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>Title</title>
</head>
<body>
<%String username = (String) session.getAttribute("username");String role = (String) session.getAttribute("role");
%><form action="RepasswordServlet" method="post"><tr><td><input type="hidden" name="username" value="<%=username%>"/><input type="hidden" name="role" value="<%=role%>"/>账号:<%=username%><br/></td></tr><tr><td>原密码:<input type="password" name="password"/><br/>新密码:<input type="password" name="repassword"/><br/><input type="submit" value="修改密码"/><button type="button" οnclick="fun01()">返回</button></td></tr></form><script type="text/javascript">function fun01(){window.location="index.jsp";}</script></body>
</html>

将数据传给RepasswordServlet:

获取数据,判断角色,查询对象判断是否为空,不为空则修改,修改后安全退出,为空修改失败,设置信息返回修改页面。

package com.qf.servlet;import com.qf.pojo.Student;
import com.qf.pojo.Teacher;
import com.qf.pojo.User;
import com.qf.utils.DBUtil;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.SQLException;@WebServlet("/RepasswordServlet")
public class RepasswordServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {this.doPost(request, response);}@Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {request.setCharacterEncoding("UTF-8");response.setContentType("text/html;charset=UTF-8");String username = request.getParameter("username");String role = request.getParameter("role");String password = request.getParameter("password");String repassword = request.getParameter("repassword");try {User user = null;if("student".equals(role)){user = DBUtil.commonQueryObj(Student.class, "select * from student where username=? and password=?", username, password);if(user != null){DBUtil.commonUpdate("update student set password=? where username=?",repassword,username);}}else if("teacher".equals(role)){user = DBUtil.commonQueryObj(Teacher.class,"select * from teacher where username=? and password=?", username, password);if(user != null){DBUtil.commonUpdate("update teacher set password=? where username=?",repassword,username);}}if(user != null){request.getRequestDispatcher("DoOutLoginServlet").forward(request,response);}else{request.setAttribute("msg","修改密码失败 -- 原密码不正确");request.getRequestDispatcher("repassword.jsp").forward(request,response);}} catch (SQLException e) {throw new RuntimeException(e);} catch (InstantiationException e) {throw new RuntimeException(e);} catch (IllegalAccessException e) {throw new RuntimeException(e);}}
}
修改学生信息

修改姓名,年龄,爱好

关键:已有数据从哪里来?–Servlet中利用传过来的username从数据库中获取对象,将对象放到session里面传到stuinfo页面

StuInitModifyServlet:

package com.qf.servlet;import com.qf.pojo.Student;
import com.qf.utils.DBUtil;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.SQLException;@WebServlet("/StuInitModifyServlet")
public class StuInitModifyServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {this.doPost(request, response);}@Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {request.setCharacterEncoding("UTF-8");response.setContentType("text/html;charSet=UTF-8");
//        String username = (String) request.getSession().getAttribute("username");String username = request.getParameter("username");try {//利用账户查询学生对象Student student = DBUtil.commonQueryObj(Student.class, "select * from student where username=?", username);//将对象返回给前端request.setAttribute("stu",student);request.getRequestDispatcher("stuinfo.jsp").forward(request,response);} catch (SQLException e) {throw new RuntimeException(e);} catch (InstantiationException e) {throw new RuntimeException(e);} catch (IllegalAccessException e) {throw new RuntimeException(e);}}
}

jsp页面根据对象获取数据

stuinfo.jsp:

<%@ page import="com.qf.pojo.Student" %><%--Created by IntelliJ IDEA.User: GuDate: 2024-06-14Time: 17:06To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>Title</title>
</head>
<body>
<%Student stu = (Student) request.getAttribute("stu");
%><h2>修改学生信息</h2><form action="StuModifyServlet" method="post"><input type="hidden" name="username" value="<%=stu.getUsername()%>"/><br/>姓名:<input type="text" name="name" value="<%=stu.getName()%>" /><br />年龄:<input type="text" name="age"  value="<%=stu.getAge()%>" /><br />性别:<input type="radio" name="sex" value="man" <%=(stu.getSex().equals("man"))?"checked='checked'":""%>/>男<input type="radio" name="sex" value="woman"<%=(stu.getSex().equals("woman"))?"checked='checked'":""%>/>女<br />爱好:<input type="checkbox" name="hobbies" value="football" <%=(stu.getHobbies().contains("football"))?"checked='checked'":""%>/>足球<input type="checkbox" name="hobbies" value="basketball" <%=(stu.getHobbies().contains("basketball"))?"checked='checked'":""%>/>篮球<input type="checkbox" name="hobbies" value="shop" <%=(stu.getHobbies().contains("shop"))?"checked='checked'":""%>/>购物<br /><input type="submit" value="修改" /><button type="button" οnclick="fun01()">返回</button></form><script type="text/javascript">function fun01(){window.location="index.jsp";}</script>
</body>
</html>

修改后将数据传回(注意要用隐藏域写账号,以便传回账号)到一个Servlet中完成对数据库信息的修改

StuModifyServlet:

package com.qf.servlet;import com.qf.pojo.Student;
import com.qf.utils.BeanUtil;
import com.qf.utils.CookieUtil;
import com.qf.utils.DBUtil;import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Map;@WebServlet("/StuModifyServlet")
public class StuModifyServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {this.doPost(request, response);}@Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {request.setCharacterEncoding("UTF-8");response.setContentType("text/html;charSet=UTF-8");Map<String, String[]> parameterMap = request.getParameterMap();Student stu = new Student();BeanUtil.populate(stu,parameterMap);System.out.println(stu);try {//更新数据库数据DBUtil.commonUpdate("update student set name=?,age=?,sex=?,hobbies=?",stu.getName(),stu.getAge(),stu.getSex(),stu.getHobbies());//更新sessionHttpSession session = request.getSession();session.setAttribute("name",stu.getName());//更新cookieresponse.addCookie(CookieUtil.createCookie("name",stu.getName(),60*60*24));//跳转response.sendRedirect("index.jsp");} catch (SQLException e) {throw new RuntimeException(e);}}
}
修改老师信息

老师角色->index.jsp–>TeaInitModifyServlet(根据username查询老师对象,并添加到请求中,查询所有学科对象(集合),并添加到请求中)–>teaInfo.jsp(获取请求中的老师对象和学科集合再适配到页面上,页面中有账号、姓名、学科,学科需要匹配当前账号的信息,判断老师和学科表中的id是否相同,默认选中。还有修改和返回两个按钮,修改到TeaModifyServlet,依据username修改name和courseId,更新session和cookie里的name数据,跳转到index.jsp;返回到index.jsp)。

TeaInitModifyServlet:

package com.qf.servlet;import com.qf.pojo.Course;
import com.qf.pojo.Teacher;
import com.qf.utils.DBUtil;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.SQLException;
import java.util.List;@WebServlet("/TeaInitModifyServlet")
public class TeaInitModifyServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {this.doPost(request, response);}@Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {request.setCharacterEncoding("UTF-8");response.setContentType("text/html;charSet=UTF-8");String username = request.getParameter("username");try {//查询老师对象Teacher teacher = DBUtil.commonQueryObj(Teacher.class, "select * from teacher where username=?", username);// 查询所有课程对象List<Course> courseList = DBUtil.commonQueryList(Course.class, "select * from course");//返回到请求中并跳转页面request.setAttribute("teacher",teacher);request.setAttribute("courseList",courseList);request.getRequestDispatcher("teainfo.jsp").forward(request,response);} catch (SQLException e) {throw new RuntimeException(e);} catch (InstantiationException e) {throw new RuntimeException(e);} catch (IllegalAccessException e) {throw new RuntimeException(e);}}
}

teainfo.jsp:

<%@ page import="com.qf.pojo.Course" %>
<%@ page import="com.qf.pojo.Teacher" %>
<%@ page import="java.util.List" %><%--Created by IntelliJ IDEA.User: GuDate: 2024-06-14Time: 19:24To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>Title</title>
</head>
<body><%List<Course> courseList = (List<Course>) request.getAttribute("courseList");Teacher tea = (Teacher) request.getAttribute("teacher");%><h2>修改老师信息</h2><form action="TeaModifyServlet" method="post"><input type="hidden" name="username" value="<%=tea.getUsername()%>"/><br/>姓名:<input type="text" name="name" value="<%=tea.getName()%>" /><br />课程:<select name="courseId"><%for(Course course:courseList){%><option value="<%=course.getId()%>" <%=(tea.getCourseId()== course.getId())?"selected":""%>><%=course.getName()%></option><%}%></select><input type="submit" value="修改" /><button type="button" οnclick="fun01()">返回</button></form><script type="text/javascript">function fun01(){window.location="index.jsp";}</script></body>
</html>

TeaModifyServlet:

package com.qf.servlet;import com.qf.pojo.Teacher;
import com.qf.utils.BeanUtil;
import com.qf.utils.CookieUtil;
import com.qf.utils.DBUtil;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.SQLException;
import java.util.Map;@WebServlet("/TeaModifyServlet")
public class TeaModifyServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {this.doPost(request, response);}@Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {request.setCharacterEncoding("UTF-8");response.setContentType("text/html;charSet=UTF-8");Teacher teacher = new Teacher();Map<String, String[]> parameterMap = request.getParameterMap();BeanUtil.populate(teacher,parameterMap);try {DBUtil.commonUpdate("update teacher set name=?,courseId=?",teacher.getName(),teacher.getCourseId());HttpSession session = request.getSession();session.setAttribute("name",teacher.getName());response.addCookie(CookieUtil.createCookie("name",teacher.getName(),60*60*24));response.sendRedirect("index.jsp");} catch (SQLException e) {throw new RuntimeException(e);}}
}
查询

QueryAllStuServlet

做分页假数据:

public static void main(String[] args) {for(int i=0;i<100;i++){String sql = "insert into student values (?,?,?,?,?,?)";try {DBUtil.commonInsert(sql,"jiashuju"+i,"123123","假数据"+i,"man",18,"football");} catch (SQLException e) {throw new RuntimeException(e);}}}

查询全部数据,存到请求里,

package com.qf.servlet;import com.qf.pojo.Student;
import com.qf.utils.DBUtil;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.SQLException;
import java.util.List;@WebServlet("/QueryAllStuSevlet")
public class QueryAllStuServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {this.doPost(request, response);}@Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {request.setCharacterEncoding("UTF-8");response.setContentType("text/html;charset=UTF-8");try {List<Student> students = DBUtil.commonQueryList(Student.class, "select * from student");request.setAttribute("stuList",students);request.getRequestDispatcher("stuList.jsp").forward(request,response);} catch (SQLException e) {throw new RuntimeException(e);} catch (InstantiationException e) {throw new RuntimeException(e);} catch (IllegalAccessException e) {throw new RuntimeException(e);}}
//      假数据
//    public static void main(String[] args) {
//        for(int i=0;i<100;i++){
//            String sql = "insert into student values (?,?,?,?,?,?)";
//            try {
//                DBUtil.commonInsert(sql,"jiashuju"+i,"123123","假数据"+i,"man",18,"football");
//            } catch (SQLException e) {
//                throw new RuntimeException(e);
//            }
//        }
//    }
}

stuList.jsp

获取数据集合,展示表格:账号、姓名、性别、年龄、爱好、操作,显示内容用for循环

<%@ page import="com.qf.pojo.Student" %>
<%@ page import="java.util.List" %><%--Created by IntelliJ IDEA.User: GuDate: 2024-06-14Time: 20:14To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>Title</title>
</head>
<body>
<%List<Student> stuList = (List<Student>) request.getAttribute("stuList");%><button οnclick="fun01()">返回</button>
<h1>学生列表页面</h1>
<table border="1" width="800px"><tr><th>账号</th><th>姓名</th><th>性别</th><th>年龄</th><th>爱好</th><th>操作</th></tr><%for(Student stu:stuList){ %><tr><td><%=stu.getUsername()%></td><td><%=stu.getName()%></td><td><%=stu.getSex()%></td><td><%=stu.getAge()%></td><td><%=stu.getHobbies()%></td><td><a href="#">修改</a><a href="#">删除</a></td></tr><%}%>
</table><script type="text/javascript">function fun01(){window.location = "index.jsp";}
</script>
</body>
</html>

但是展示的数据是数据库里的数据,不是展示的数据(不满足中英文转换等展示需求)。

概念:dto:满足前端数据展示需求

写StudentDto类

写工具类DtoUtil:把学生类封装成StudentDto类。

两个方法,studentHandler(Student student)方法把单个学生类转换成dto;studentListHandler(List<Student.> stuList)方法把学生对象集合转换成dto类集合。

package com.qf.utils;import com.qf.dto.StudentDto;
import com.qf.pojo.Student;import java.util.ArrayList;
import java.util.List;public class DtoUtil {public static StudentDto studentHandler(Student student){String sex = student.getSex();if("man".equals(sex)){sex = "男";}if("woman".equals(sex)){sex = "女";}String hobbies = student.getHobbies();hobbies = hobbies.replaceAll("football","足球");hobbies = hobbies.replaceAll("basketball","篮球");hobbies = hobbies.replaceAll("shop","购物");StudentDto studentDto = new StudentDto(student,sex,hobbies);return studentDto;}public static List<StudentDto> studentListHandler(List<Student> stuList){List<StudentDto> studentDtos = new ArrayList<>();for (Student stu :stuList){StudentDto studentDto = studentHandler(stu);studentDtos.add(studentDto);}return studentDtos;}
}

QueryAllStuServlet中就要对应修改:

            List<StudentDto> students = DtoUtil.studentListHandler(DBUtil.commonQueryList(Student.class, "select * from student"));

前端存的应该是dto类:

<%@ page import="com.qf.pojo.Student" %>
<%@ page import="java.util.List" %>
<%@ page import="com.qf.dto.StudentDto" %><%--Created by IntelliJ IDEA.User: GuDate: 2024-06-14Time: 20:14To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>Title</title>
</head>
<body>
<%List<StudentDto> stuList = (List<StudentDto>) request.getAttribute("stuList");%><button οnclick="fun01()">返回</button>
<h1>学生列表页面</h1>
<table border="1" width="800px"><tr><th>账号</th><th>姓名</th><th>性别</th><th>年龄</th><th>爱好</th><th>操作</th></tr><%for(StudentDto stu:stuList){ %><tr><td><%=stu.getStu().getUsername()%></td><td><%=stu.getStu().getName()%></td><td><%=stu.getSex()%></td><td><%=stu.getStu().getAge()%></td><td><%=stu.getHobbies()%></td><td><a href="#">修改</a><a href="#">删除</a></td></tr><%}%>
</table><script type="text/javascript">function fun01(){window.location = "index.jsp";}
</script>
</body>
</html>
分页查询

QueryAllStuServlet

数据库中利用分页查询语句查询,可以定为每页15条数据,偏移量为(页数-1)*每页数据量。

index.jsp:

<a href="QueryAllStuServlet?curPage=1">查询学生</a>

将页面数据添加到请求中,除了数据外还要存当前页数。

stuList.jsp中要写首页、上一页、下一页、尾页按钮。首页不能有上一页、尾页不能有下一页。

优化DBUtil:编写getAllCount(String sql)方法,获取数据条数。

/*** 获取数据条数* @param sql* @return*/public static int getAllCount(String sql){Connection connection = null;PreparedStatement statement = null;ResultSet resultSet = null;try {connection = getConnection();statement = connection.prepareStatement(sql);resultSet = statement.executeQuery();if(resultSet.next()){int allCount = resultSet.getInt(1);return allCount;}} catch (SQLException e) {throw new RuntimeException(e);} finally {close(connection,statement,resultSet);}return 0;}

然后再QueryAllStuSevlet中利用该工具类计算总页数,并存储该数据返回前端。

package com.qf.servlet;import com.qf.dto.StudentDto;
import com.qf.pojo.Student;
import com.qf.utils.DBUtil;
import com.qf.utils.DtoUtil;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.SQLException;
import java.util.List;@WebServlet("/QueryAllStuServlet")
public class QueryAllStuServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {this.doPost(request, response);}@Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {request.setCharacterEncoding("UTF-8");response.setContentType("text/html;charset=UTF-8");int curPage = Integer.parseInt(request.getParameter("curPage"));int count = 15;//每一页的数据条数int offset = (curPage-1)*count;//计算偏移量int allCount = DBUtil.getAllCount("select count(username) from student");//总条数int totalPage;//总页数if(allCount%count == 0){totalPage = allCount/count;}else{totalPage = allCount/count + 1;}try {String sql = "select * from student limit ?,?";List<Student> stuList = DBUtil.commonQueryList(Student.class,sql,offset,count);List<StudentDto> stuDtoList = DtoUtil.studentListHandler(stuList);//将页面数据添加到请求对象中request.setAttribute("stuList",stuDtoList);request.setAttribute("curPage",curPage);request.setAttribute("totalPage",totalPage);request.getRequestDispatcher("stuList.jsp").forward(request,response);} catch (SQLException e) {throw new RuntimeException(e);} catch (InstantiationException e) {throw new RuntimeException(e);} catch (IllegalAccessException e) {throw new RuntimeException(e);}}}
//      假数据
//    public static void main(String[] args) {
//        for(int i=0;i<100;i++){
//            String sql = "insert into student values (?,?,?,?,?,?)";
//            try {
//                DBUtil.commonInsert(sql,"jiashuju"+i,"123123","假数据"+i,"man",18,"football");
//            } catch (SQLException e) {
//                throw new RuntimeException(e);
//            }
//        }
//    }

前端中完善翻页功能

<%@ page import="com.qf.pojo.Student" %>
<%@ page import="java.util.List" %>
<%@ page import="com.qf.dto.StudentDto" %><%--Created by IntelliJ IDEA.User: GuDate: 2024-06-14Time: 20:14To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>Title</title>
</head>
<body>
<%List<StudentDto> stuList = (List<StudentDto>) request.getAttribute("stuList");int curPage = (int) request.getAttribute("curPage");int totalPage = (int) request.getAttribute("totalPage");
%><button οnclick="fun01()">返回</button>
<h1>学生列表页面</h1>
<table border="1" width="800px"><tr><th>账号</th><th>姓名</th><th>性别</th><th>年龄</th><th>爱好</th><th>操作</th></tr><%for(StudentDto stu:stuList){ %><tr><td><%=stu.getStu().getUsername()%></td><td><%=stu.getStu().getName()%></td><td><%=stu.getSex()%></td><td><%=stu.getStu().getAge()%></td><td><%=stu.getHobbies()%></td><td><a href="#">修改</a><a href="#">删除</a></td></tr><%}%>
</table><a href="QueryAllStuServlet?curPage=1">首页</a><%if(curPage>1){%><a href="QueryAllStuServlet?curPage=<%=curPage-1%>">上一页</a><%}%><%if(curPage<totalPage){%><a href="QueryAllStuServlet?curPage=<%=curPage+1%>">下一页</a><%}%><a href="QueryAllStuServlet?curPage=<%=totalPage%>">尾页</a>
<script type="text/javascript">function fun01(){window.location = "index.jsp";}
</script>
</body>
</html>

相关文章:

  • 对用户体验的一些思考
  • 【GIS矢量切片】tippecanoe在Windows和CentOS中的安装
  • React-Redux
  • 【Qnx】Qnx coredump解析
  • 使用NetAssist网络调试助手在单台计算机上配置TCP服务器和客户端
  • Go Module详解
  • 【安卓设备】通过adb批量安装apk
  • 计算机网络重要知识点
  • [Shell编程学习路线]——探讨Shell中变量的作用范围(export)
  • vscode软件上安装 Fitten Code插件及使用
  • 用Python处理Excel的资源
  • 4、视觉里程计:特征点法、直接法和半直接法
  • C++日期类的实现
  • 记一次 .NET某工控视觉自动化系统 卡死分析
  • 简单聊一下Oracle,MySQL,postgresql三种锁表的机制,行锁和表锁
  • #Java异常处理
  • 《用数据讲故事》作者Cole N. Knaflic:消除一切无效的图表
  • 「译」Node.js Streams 基础
  • 【跃迁之路】【641天】程序员高效学习方法论探索系列(实验阶段398-2018.11.14)...
  • CentOS6 编译安装 redis-3.2.3
  • CentOS7简单部署NFS
  • gf框架之分页模块(五) - 自定义分页
  • GraphQL学习过程应该是这样的
  • java 多线程基础, 我觉得还是有必要看看的
  • Javascript基础之Array数组API
  • JAVA之继承和多态
  • Mysql优化
  • PHP 程序员也能做的 Java 开发 30分钟使用 netty 轻松打造一个高性能 websocket 服务...
  • PHP那些事儿
  • XML已死 ?
  • 半理解系列--Promise的进化史
  • 闭包--闭包作用之保存(一)
  • 分享一份非常强势的Android面试题
  • 融云开发漫谈:你是否了解Go语言并发编程的第一要义?
  • 实现菜单下拉伸展折叠效果demo
  • 使用阿里云发布分布式网站,开发时候应该注意什么?
  • 系统认识JavaScript正则表达式
  • Mac 上flink的安装与启动
  • 宾利慕尚创始人典藏版国内首秀,2025年前实现全系车型电动化 | 2019上海车展 ...
  • 昨天1024程序员节,我故意写了个死循环~
  • ​LeetCode解法汇总1410. HTML 实体解析器
  • $.type 怎么精确判断对象类型的 --(源码学习2)
  • (2024,RWKV-5/6,RNN,矩阵值注意力状态,数据依赖线性插值,LoRA,多语言分词器)Eagle 和 Finch
  • (4)Elastix图像配准:3D图像
  • (7)摄像机和云台
  • (done) NLP “bag-of-words“ 方法 (带有二元分类和多元分类两个例子)词袋模型、BoW
  • (pt可视化)利用torch的make_grid进行张量可视化
  • (ZT)出版业改革:该死的死,该生的生
  • (第61天)多租户架构(CDB/PDB)
  • (附源码)ssm智慧社区管理系统 毕业设计 101635
  • (一)Dubbo快速入门、介绍、使用
  • (一)UDP基本编程步骤
  • (原創) 未来三学期想要修的课 (日記)
  • (转)shell中括号的特殊用法 linux if多条件判断
  • (转)Sublime Text3配置Lua运行环境