Java理论和实践:了解泛型和实例

单态模式实现分页

   步骤如下

     首先,创建一个web项目  例如:2011firstweb

     其次,创建包命

              创建所需包命  如:

              1.cn.csdn.domain(主要封装bean)

              2.cn.csdn.util(工具类)

              3,cn.csdn.web.dao(主要写dao方法)

               4,cn.csdn.web.serivice(主要连接服务)

               5.cn.csdn.web.servlet(主要封装请求)

    三 ,进入编程阶段

           1,创建一个连接数据库类  如:DBConn

                 package cn.csdn.util;

import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.mysql.jdbc.Connection;

public class DBConn {
 
 private static Connection conn;
 private DBConn(){}
 public static Connection getConn(){
  if(conn==null){
   try {
    Class.forName("com.mysql.jdbc.Driver");
    try {
     conn=(Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/db?user=root&password=123&useUnicode=true&characterEncoding=utf8");
    } catch (SQLException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   } catch (ClassNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
   
   
  }
  return conn;
 }
 //关闭
 public static void coles(ResultSet rs,PreparedStatement pstmt){
  if(rs!=null){
  try {
   rs.close();
  } catch (SQLException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  }
  if(pstmt!=null){
  try {
   pstmt.close();
  } catch (SQLException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  
  }
 }
 
 public static void main(String[] args) {
  DBConn.getConn();
 }

}
     2.封装数据 

package cn.csdn.domain;

public class Student {
 public Student() {
 }

 public Student(String name, int age, String email) {
          this.name=name;
          this.age=age;
          this.email=email;
         
 }

 private int id;
 private String name;
 private String email;
 private int age;
 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public String getEmail() {
  return email;
 }

 public void setEmail(String email) {
  this.email = email;
 }

 public int getAge() {
  return age;
 }

 public void setAge(int age) {
  this.age = age;
 }

}
 

   3.写DAO方法

       接口类

     package cn.csdn.web.dao;

import java.util.List;

import cn.csdn.domain.Student;

public interface StudentDao {
 int getCountRecord();
 int getCountPage();
 List<Student> getNowPageInfo(int nowpage);

}
   方法 

   package cn.csdn.web.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

 

import cn.csdn.domain.Student;
import cn.csdn.util.DBConn;

public class StudentDaoImpl implements StudentDao {
 private Connection conn;
 private PreparedStatement pstmt;
 private ResultSet rs;
 private static final int PAGESIZE = 5;

 // 获取总页数
 public int getCountPage() {

  return getCountRecord() % PAGESIZE == 0 ? getCountRecord() / PAGESIZE
    : getCountRecord() / PAGESIZE + 1;
 }

 // 获取总信息
 public int getCountRecord() {
  // 定义返回变量
  int countrecord = 0;
  // 创建数据库连接
  conn = DBConn.getConn();
  //
  String sql = "select count(*) from student";
  try {
   pstmt = conn.prepareStatement(sql);
   rs = pstmt.executeQuery();
   if (rs.next()) {
    countrecord = rs.getInt(1);

   }
  } catch (SQLException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } finally {

   DBConn.coles(rs, pstmt);
  }

  return countrecord;
 }

 public List<Student> getNowPageInfo(int nowpage) {
  List<Student> allentities = new ArrayList<Student>();
  conn = DBConn.getConn();
  String sql = "select id,name,age,email from student limit ?,?";
  try {
   pstmt = conn.prepareStatement(sql);
   int index = 1;
   pstmt.setInt(index++, (nowpage-1)*PAGESIZE);
   pstmt.setInt(index++, PAGESIZE);
   rs = pstmt.executeQuery();
   while (rs.next()) {
    Student entity = new Student();
    entity.setId(rs.getInt("id"));
    entity.setAge(rs.getInt("age"));
    entity.setName(rs.getString("name"));
    entity.setEmail(rs.getString("email"));
    allentities.add(entity);

   }
  } catch (SQLException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }finally{
   DBConn.coles(rs, pstmt);
   
  }
  return allentities;
 }
     public static void main(String[] args) {
      StudentDaoImpl sdi = new StudentDaoImpl();
     /* int  countecord=sdi.getCountRecord();
      System.out.println(countecord);
      System.out.println(sdi.getCountPage());*/
     List<Student> allentities=sdi.getNowPageInfo(2);
     for(Student entity:allentities){
      System.out.println(entity.getAge());
      
     }
 }
}
  4,连接服务

      服务接口

package cn.csdn.web.service;

import java.util.List;

import cn.csdn.domain.Student;

public interface StudentService {
 int getCountRecord();
 //获取总页数
 int getCountPage();
 //获取当前页的信息
 List<Student> getNowPageInfo(int nowpage);
}
 方法

  package cn.csdn.web.service;

import java.util.List;

import cn.csdn.domain.Student;
import cn.csdn.web.dao.StudentDaoImpl;

public class StudentServiceImpl implements StudentService {
 private StudentDaoImpl sdi = new StudentDaoImpl();

 public int getCountPage() {
  // TODO Auto-generated method stub
  System.out.println("-----");
  return sdi.getCountPage();
  
 }

 public int getCountRecord() {
  // TODO Auto-generated method stub
  return sdi.getCountRecord();
 }

 public List<Student> getNowPageInfo(int nowpage) {
  // TODO Auto-generated method stub
  return sdi.getNowPageInfo(nowpage);
 }

 public static void main(String[] args) {
  StudentServiceImpl ass=new StudentServiceImpl();
  ass.getCountPage();
 }
}
5,封装请求

   package cn.csdn.web.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.csdn.domain.Student;
import cn.csdn.web.service.StudentServiceImpl;


public class ListStudentsServlet extends HttpServlet {

 /**
  *
  */
 private static final long serialVersionUID = 4438133059395214446L;

 @Override
 protected void doGet(HttpServletRequest req, HttpServletResponse resp)
   throws ServletException, IOException {
  this.doPost(req, resp);
 }

 @Override
 protected void doPost(HttpServletRequest req, HttpServletResponse resp)
   throws ServletException, IOException {
        //1、设置编码
  req.setCharacterEncoding("UTF-8");
  //2、获取当前页
  //定义当前页的变量
  int nowpage =1;
  String npage = req.getParameter("nowpage");
  
  if(npage!=null){
   nowpage = Integer.parseInt(npage);
  }
  
  
  //3、创业业务操作的实现类的对象
  StudentServiceImpl ssi = new StudentServiceImpl();
  
  int lastpage = ssi.getCountPage();
  List<Student> allentities = ssi.getNowPageInfo(nowpage);
  
  
  //存入当前页  最后一页  当前页的记录信息
  req.setAttribute("nowpage", nowpage);
  req.setAttribute("lastpage", lastpage);
  req.setAttribute("allentities", allentities);
  
  
  
  req.getRequestDispatcher("fend.jsp").forward(req, resp);
 }

}

6,创建JSP/HTML

 

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
   
    <title>My JSP 'index.jsp' starting page</title>
 <meta http-equiv="pragma" content="no-cache">
 <meta http-equiv="cache-control" content="no-cache">
 <meta http-equiv="expires" content="0">   
 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
 <meta http-equiv="description" content="This is my page">
 <!--
 <link rel="stylesheet" type="text/css" href="styles.css">
 -->
  </head>
 
  <body>
    <h1><a href="listStudents.do">查询所有学生信息</a></h1>
  </body>
</html>

      跳转页面

   <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
   
    <title>My JSP 'sc.jsp' starting page</title>
   
 <meta http-equiv="pragma" content="no-cache">
 <meta http-equiv="cache-control" content="no-cache">
 <meta http-equiv="expires" content="0">   
 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
 <meta http-equiv="description" content="This is my page">
 <!--
 <link rel="stylesheet" type="text/css" href="styles.css">
 -->

  </head>
 
  <body>
 
       <div align="center">
           <h1>显示所有的学员信息</h1>
          <table border="1px" cellpadding="0" cellspacing="0">
             <caption>学员信息</caption>
           <tr>
              <th>全选</th>
              <th>序列</th>
              <th>姓名</th>
              <th>年龄</th>
              <th>邮箱</th>
              <th>操作</th>
           </tr>
          
          <c:forEach items="${allentities}" var="entity">
           <tr>
              <td><input type="checkbox" name="chk"/></td>
              <td>${entity.id}</td>
              <td>${entity.name}</td>
              <td>${entity.age}</td>
              <td>${entity.email}</td>
              <td>编辑|删除</td>
           </tr>
          </c:forEach>
          </table>
         
          <div>
              <span><a href="./listStudents.do?nowpage=1">首页</a></span>
              <span><a href="./listStudents.do?nowpage=${nowpage-1}">上一页</a></span>
              <span><a href="./listStudents.do?nowpage=${nowpage+1}">下一页</a></span>
              <span><a href="./listStudents.do?nowpage=${lastpage}">最后一页</a></span>
          </div>
       </div>
       
        </body>
</html>

创建数据库

/*Column Information For - db.student*/
---------------------------------------

Field   Type         Collation        Null    Key     Default  Extra           Privileges                       Comment
------  -----------  ---------------  ------  ------  -------  --------------  -------------------------------  -------
id      int(11)      (NULL)           NO      PRI     (NULL)   auto_increment  select,insert,update,references        
name    varchar(40)  utf8_general_ci  YES             (NULL)                   select,insert,update,references        
age     int(11)      (NULL)           YES             (NULL)                   select,insert,update,references        
email   varchar(50)  utf8_general_ci  YES             (NULL)                   select,insert,update,references        

/*Index Information For - db.student*/
--------------------------------------

Table    Non_unique  Key_name  Seq_in_index  Column_name  Collation  Cardinality  Sub_part  Packed  Null    Index_type  Comment
-------  ----------  --------  ------------  -----------  ---------  -----------  --------  ------  ------  ----------  -------
student           0  PRIMARY              1  id           A                   19    (NULL)  (NULL)          BTREE             

/*DDL Information For - db.student*/
------------------------------------

Table    Create Table                            
-------  -----------------------------------------
student  CREATE TABLE `student` (                
           `id` int(11) NOT NULL auto_increment, 
           `name` varchar(40) default NULL,      
           `age` int(11) default NULL,           
           `email` varchar(50) default NULL,     
           PRIMARY KEY  (`id`)                   
         ) ENGINE=InnoDB DEFAULT CHARSET=utf8    

 


7,发布启动服务


QQ:点击这里给我发消息

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值