日期:2014-05-17 浏览次数:20860 次
package com.chk.cms.servlet; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.chk.cms.model.Article; public class SearchArticlesServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); // 对文章进行分页查询,需要具备几个必要的条件 // 1、从第几条记录开始查询 int offSet = 0; // 2、每页显示多少条记录 int pageSize = 5; // 3、总共有多少条记录 int totel; // 从request中获得offset的值 try { offSet = Integer.parseInt(request.getParameter("offSet")); } catch (Exception ignore) { } if (request.getParameter("pageSize") != null) { request.getSession().setAttribute("pageSize", Integer.parseInt(request.getParameter("pageSize"))); } // 从Http Session中获得pagesize的值 Integer pages = (Integer) request.getSession().getAttribute("pageSize"); if (pages == null) { request.getSession().setAttribute("pageSize", pageSize); } else { pageSize = pages; } // 查询文章列表 List articleList = new ArrayList(); Connection conn = null; PreparedStatement ps = null; PreparedStatement psForTotal = null; ResultSet rs = null; ResultSet rsForTotal = null; // 总记录数 int total = 0; try { // 查询条件 String title = request.getParameter("title"); Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/cms", "root", "chengke168"); String sqlCon = "select count(*) from article"; // 查询总记录数 if (title != null) { sqlCon = "select count(*) from article where title like '%"+title+"%'"; } psForTotal = conn.prepareStatement(sqlCon); rsForTotal = psForTotal.executeQuery(); if (rsForTotal.next()) { total = rsForTotal.getInt(1); } // 分页查询 String sql = "select * from article limit ?,?"; if (title != null) { sql = "select * from article where title like '%"+title+"%' limit ?,?"; } ps = conn.prepareStatement(sql); ps.setInt(1, offSet); ps.setInt(2, pageSize); rs = ps.executeQuery(); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); while (rs.next()) { Article a = new Article(); a.setId(rs.getInt("id")); a.setTitle(rs.getString("title")); a.setSource(rs.getString("source"));