实际上,我在我的应用程序中遵循 mvc-3 层架构。这是我的搜索选项的实现。在我的 servlet(控制器)中,我正在这样做:
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;
}
}
- 已编辑如果我没有遵循正确的 mvc 架构,请随时发表评论并纠正我。