実際、私はアプリケーションに対して mvc-3 層アーキテクチャに従っています。これが私の検索オプションの実装です。私のサーブレット(コントローラ)で私はこれをやっています:
String select = request.getParameter("select"); // getting value
String search = request.getParameter("search"); // getting value
request.setAttribute("select", select);
request.setAttribute("search", search);
System.out.println("Select : "+select+" Search : "+search);
int page = 1;
int recordsPerPage = 20;
if(request.getParameter("page") != null)
page = Integer.parseInt(request.getParameter("page"));
SearchDAO searchDAO=new SearchDAO();
List<User> list1=searchDAO.searchAllUsers((page-1)*recordsPerPage,recordsPerPage,select,search); //getting null value,doing SOP of list1
int noOfRecords = searchDAO.getNoOfRecords(); //getting null value,doing SOP
int noOfPages = (int) Math.ceil(noOfRecords * 1.0 / recordsPerPage); //getting null value,doing SOP
session.setAttribute("noOfRecords", noOfRecords);
request.setAttribute("searchList", list1);
request.setAttribute("noOfPages", noOfPages);
request.setAttribute("currentPage", page);
そしてSearchDAOには次のものがあります:
public class SearchDAO {
private int noOfRecords;
Connection connection;
Statement stmt;
public List<User> searchAllUsers(int offset ,int noOfRecords,String select,String search){
private static Connection getConnection() throws SQLException,ClassNotFoundException{
Connection con = ConnectionFactory.getInstance().getConnection();
return con; //ConnectionFactory is class for making the connection to DB.
}
String query="select SQL_CALC_FOUND_ROWS * from info where '"+select+
"' like '%"+search+"%' order by serialNo asc limit
" + offset + " , " + noOfRecords;
List<User> list1 = new ArrayList<User>();
User user1=null;
try {
connection = getConnection();
stmt = connection.createStatement();
ResultSet rs=stmt.executeQuery(query);
while(rs.next()){
user1=new User();
user1.setSerial(rs.getInt(1));
user1.setName(rs.getString(2));
user1.setEmail(rs.getString(3));
list1.add(user1);
}
rs.close();
rs = stmt.executeQuery("SELECT FOUND_ROWS()");
if(rs.next())
this.noOfRecords = rs.getInt(1);
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}finally
{
try {
if(stmt != null)
stmt.close();
if(connection != null)
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return list1;
}
public int getNoOfRecords() {
return noOfRecords;
}
}
- Editted お気軽にコメントしてください。適切な mvc アーキテクチャに従っていない場合は、修正してください。