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>