- package com.tsinghua;
- import javax.servlet.http.*;
- import java.io.*;
- import java.sql.*;
- public class Wel extends HttpServlet{
- //处理get请求
- //req:用于获得客户端(浏览器)的信息
- //res:用于向客户端(浏览器)返回信息
- public void doGet(HttpServletRequest req,HttpServletResponse res){
- Connection ct=null;
- PreparedStatement ps=null;
- ResultSet rs=null;
- //中文乱码
- res.setContentType("text/html;charset=gbk");
- PrintWriter pw=null;
- try{
- pw=res.getWriter();
- pw.println("<body><center>");
- //得到session
- HttpSession hs=req.getSession(true);
- String myName=(String)hs.getAttribute("pass");
- //判断
- if(myName==null){
- //非法登录,返回登录界面
- res.sendRedirect("login");
- return ;
- }
-
- //===========分页的功能================
- int pageSize=3;//一页显示几条记录
- int pageNow=1;//希望显示第几页
- int rowCount=0;//共有几条记录
- int pageCount=0;//共有几页(计算出来的)
- //动态的接受pageNow
- String sPageNow=req.getParameter("pageNow");
- if(sPageNow!=null){
- pageNow=Integer.parseInt(sPageNow);
- }
- //得到rowCount
- //连接数据库
- Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
- //得到链接(数据库的url)
- ct=DriverManager.getConnection("jdbc:microsoft:sqlserver://127.0.0.1:1433;databaseName=spdb","sa","sa");
- //创建一个Statement
- ps=ct.prepareStatement("select count(*) from users");
- rs=ps.executeQuery();
- if(rs.next()){
- rowCount=rs.getInt(1);
- }
- //计算pageCount
- if(rowCount%pageSize==0){
- pageCount=rowCount/pageSize;
- }else{
- pageCount=rowCount/pageSize+1;
- }
- ps=ct.prepareStatement("select top "+pageSize+" * from users where userId not in(select top "+pageSize*(pageNow-1)+" userId from users)");
- rs=ps.executeQuery();
- //显示结果集
- pw.println("<table border=1>");
- pw.println("<tr><th>id</th><th>username</th><th>password</th><th>email</th><th>grade</th></tr>");
- while(rs.next()){
- pw.println("<tr>");
- pw.println("<td>"+rs.getInt(1)+"</td>");
- pw.println("<td>"+rs.getString(2)+"</td>");
- pw.println("<td>"+rs.getString(3)+"</td>");
- pw.println("<td>"+rs.getString(4)+"</td>");
- pw.println("<td>"+rs.getInt(5)+"</td>");
- pw.println("</tr>");
- }
- pw.println("</table>");
- //显示超链接
- if(pageNow>1){
- pw.println("<a href=wel?pageNow="+1+">首页</a>");
- pw.println("<a href=wel?pageNow="+(pageNow-1)+">上一页</a>");
- }
- for(int i=pageNow;i<=pageNow+4;i++){
- pw.println("<a href=wel?pageNow="+i+">"+i+"</a>");
- if(i>pageCount)
- break;
- }
- if(pageNow<pageCount){
- pw.println("<a href=wel?pageNow="+(pageNow+1)+">下一页</a>");
- pw.println("<a href=wel?pageNow="+pageCount+">末页</a>");
- }
- pw.println("</center></body>");
- }catch(Exception e){
- e.printStackTrace();
- }
- }
- //处理Post请求
- public void doPost(HttpServletRequest req,HttpServletResponse res){
- this.doGet(req,res);
- }
- }
最近在学习用Servlet做网页,这是刚刚学会的分页算法,与大家共享。
ps:我的新博客地址:http://www.xinghaixu.com