📜  Servlet中的分页

📅  最后修改于: 2021-01-09 12:51:47             🧑  作者: Mango

Servlet中的分页

要将大量记录分为多个部分,我们使用分页。它仅允许用户显示部分记录。在单个页面中加载所有记录可能需要一些时间,因此始终建议创建分页。在servlet中,我们可以轻松开发分页示例。

在这个servlet分页示例中,我们使用MySQL数据库来获取记录。

在这里,我们在“测试”数据库中创建了“ emp”表。 emp表具有三个字段:id,名称和薪水。要么手动创建表并插入记录,要么导入我们的sql文件。

index.html

ViewServlet.java

package com.javatpoint.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
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 com.javatpoint.beans.Emp;
import com.javatpoint.dao.EmpDao;

@WebServlet("/ViewServlet")
public class ViewServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
     protected void doGet(HttpServletRequest request, HttpServletResponse response) 
           throws ServletException, IOException {
         response.setContentType("text/html");
         PrintWriter out=response.getWriter();
         
         String spageid=request.getParameter("page");
         int pageid=Integer.parseInt(spageid);
         int total=5;
         if(pageid==1){}
         else{
             pageid=pageid-1;
             pageid=pageid*total+1;
         }
         List list=EmpDao.getRecords(pageid,total);

         out.print("

Page No: "+spageid+"

"); out.print(""); out.print(""); for(Emp e:list){ out.print(""); } out.print("
IdNameSalary
"+e.getId()+""+e.getName()+""+e.getSalary()+"
"); out.print("1 "); out.print("2 "); out.print("3 "); out.close(); } }

Emp.java

package com.javatpoint.beans;

public class Emp {
private int id;
private String name;
private float salary;
//getters and setters
}

EmpDao.java

package com.javatpoint.dao;
import com.javatpoint.beans.*;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class EmpDao {

    public static Connection getConnection(){
        Connection con=null;
        try{
            Class.forName("com.mysql.jdbc.Driver");
            con=DriverManager.getConnection("jdbc:mysql://localhost:3306/test","","");
        }catch(Exception e){System.out.println(e);}
        return con;
    }

    public static List getRecords(int start,int total){
        List list=new ArrayList();
        try{
            Connection con=getConnection();
            PreparedStatement ps=con.prepareStatement("select * from emp limit "+(start-1)+","+total);
            ResultSet rs=ps.executeQuery();
            while(rs.next()){
                Emp e=new Emp();
                e.setId(rs.getInt(1));
                e.setName(rs.getString(2));
                e.setSalary(rs.getFloat(3));
                list.add(e);
            }
            con.close();
        }catch(Exception e){System.out.println(e);}
        return list;
    }
}

下载SQL文件

下载mysql-connector.jar文件

下载专案

输出量