Home>Article>Backend Development> How the MVC framework implements paging query of database data

How the MVC framework implements paging query of database data

青灯夜游
青灯夜游 forward
2018-10-20 17:38:34 3786browse

The content of this article is to introduce how the MVC framework implements paging query of database data. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

This article uses the MVC mode to implement paging queries. It is a simple MVC entry example. The blog has many comprehensive and detailed explanations. I will summarize a few paragraphs. First, there is a simple diagram to understand the execution principle of the MVC framework:


How the MVC framework implements paging query of database data

MVC pattern (three-tier architecture pattern)

(Model-View-Controller) is a type of software engineering A software architecture model that divides the software system into three basic parts: Model, View and Controller.

The MVC pattern was first proposed by Trygve Reenskaug in 1974. It is a software design pattern invented by Xerox PARC in the 1980s for the programming language Smalltalk. The purpose of the MVC pattern is to implement a dynamic programming design, simplify subsequent modifications and expansions of the program, and make it possible to reuse certain parts of the program. In addition, this mode makes the program structure more intuitive by simplifying the complexity. The software system separates its basic parts and also gives each basic part its due functions. Professionals can be grouped by their own expertise:

(Controller) - Responsible for forwarding requests and processing them.

(View) - Interface designers design graphical interfaces.

(Model) - Programmers write the functions that the program should have (implementing algorithms, etc.), and database experts perform data management and database design (can realize specific functions).

How MVC works

MVC is a design pattern that enforces the separation of input, processing, and output of an application. Applications using MVC are divided into three core components: model, view, and controller. They each handle their own tasks.

View
View is the interface that users see and interact with. For old-fashioned Web applications, the view is an interface composed of HTML elements. In new-style Web applications, HTML still plays an important role in the view, but some new technologies have emerged in endlessly, including Macromedia Flash and Some markup languages and Web services like XHTML, XML/XSL, WML, etc. How to handle the interface of the application becomes more and more challenging. One of the big benefits of MVC is that it can handle many different views for your application. No real processing occurs in the view, whether the data is stored online or a list of employees. As a view, it just serves as a way to output the data and allow the user to manipulate it.

Model
Model represents enterprise data and business rules. Among the three components of MVC, the model has the most processing tasks. For example it might use component objects like EJBs and ColdFusion Components to handle databases. The data returned by the model is neutral, which means that the model has nothing to do with the data format, so that a model can provide data for multiple views. Code duplication is reduced because the code applied to the model only needs to be written once and can be reused by multiple views.

Controller
The controller accepts user input and calls models and views to complete the user's needs. So when a hyperlink in a Web page is clicked and an HTML form is sent, the controller itself does not output anything or do any processing. It just receives the request and decides which model component to call to handle the request, and then determines which view to use to display the data returned by the model processing. Now we summarize the MVC processing process. First, the controller receives the user's request and decides which model should be called for processing. Then the model uses business logic to process the user's request and returns the data. Finally, the controller formats the model return with the corresponding view. The data is presented to the user through the presentation layer.

Now that the introduction is complete, let’s move on to the steps of paging query:
Still follow the old rules and go directly to the code:
The first part (guide package, configuration file, JSP front-end part):
How the MVC framework implements paging query of database data
[jar package download address]http://archive.apache.org/dist

Configuration file:

jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/factory jdbc.username=root jdbc.password=ps123456

JSP part:

nbsp;html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  Insert title here 
雇员姓名:
雇员编号 雇员姓名 雇员薪水 雇员职位
${tt.empno} ${tt.ename} ${tt.sal} ${tt.job }
上一页 ${i} 当前页:${requestScope.pb.curPage} 总页数是:${requestScope.pb.totalPage} 总条数是:${requestScope.pb.total} 下一页

The second attribute class part (Emp):

package cn.pk.entity; public class Emp { private String empno; private String ename; private String deptno; private int sal; private String job; public String getEmpno() { return empno; } public void setEmpno(String empno) { this.empno = empno; } public String getEname() { return ename; } public void setEname(String ename) { this.ename = ename; } public String getDeptno() { return deptno; } public void setDeptno(String deptno) { this.deptno = deptno; } public int getSal() { return sal; } public void setSal(int sal) { this.sal = sal; } public String getJob() { return job; } public void setJob(String job) { this.job = job; } }

The third controller part (EmpServlet):

package cn.pk.controller; import java.io.IOException; import java.sql.SQLException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.BeanListHandler; import org.apache.commons.lang.StringUtils; import cn.pk.entity.Emp; import cn.pk.servlet.EmpService; import cn.pk.servlet.impl.EmpServiceImpl; import cn.pk.util.MyDbUtils; import cn.pk.util.PageBean; /** * Servlet implementation class EmpSerlvet */ @WebServlet(urlPatterns="/listEmp") public class EmpSerlvet extends HttpServlet { private EmpService service=new EmpServiceImpl(); protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String ename = request.getParameter("ename"); String curPage=request.getParameter("curPage"); String pageNum= request.getParameter("pageNum"); try { PageBean pb=service.queryEmp(ename, curPage, pageNum); request.setAttribute("pb", pb); request.getRequestDispatcher("/emp.jsp").forward(request, response); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }

The fourth tool class Util part:
Connect to database:

/** * */ package cn.pk.util; import java.io.IOException; import java.util.Properties; import org.apache.tomcat.dbcp.dbcp2.BasicDataSource; /** * @author 摸摸大白兔 *时间 2017年10月19日 下午3:55:46 * */ public class MyDbUtils { public static BasicDataSource bds=new BasicDataSource(); static { Properties p=new Properties(); try { p.load(MyDbUtils.class.getResourceAsStream("/jdbc.properties")); bds.setDriverClassName(p.getProperty("jdbc.driver")); bds.setUrl(p.getProperty("jdbc.url")); bds.setUsername(p.getProperty("jdbc.username")); bds.setPassword(p.getProperty("jdbc.password")); } catch (IOException e) { e.printStackTrace(); } } }

Paging help class:

package cn.pk.util; import java.util.List; /** * 分页的帮助类 * @author 摸摸大白兔 *时间 2017年10月20日 下午2:14:26 * */ public class PageBean { public void calc() { } /** * 构造方法 * @param curPage当前页 * @param pageNum每页显示的条数 * @param total总条数 */ public PageBean(int curPage,int pageNum,int total) { //计算上一页 this.prePage = curPage==1?1:curPage-1; //计算总页数 this.totalPage=total%pageNum==0?total/pageNum:total/pageNum+1; //下一页 this.nextPage=curPage==totalPage?totalPage:curPage+1; //当前页数的下标 this.startIndex=(curPage-1)*pageNum; this.total=total; this.curPage=curPage; this.pageNum=pageNum; } /** * 当前查询的默认当前页=1; * (页面传递参数) */ private int curPage; /** * 每一页的数据条数默认10条 * 页面传递的参数 */ private int pageNum=10; /** * 上一页 *根据当前页判断 *curPage=1 prePage=1; *curPage>1 prePage=curPage-1; */ private int prePage; /** * 下一页 * curPage=totalpage nextPage=totalpage; * curPage data; /** * 开始的索引 * startIndex = (curPage-1)*pageNum */ private int startIndex; public int getCurPage() { return curPage; } public int getStartIndex() { return startIndex; } public void setStartIndex(int startIndex) { this.startIndex = startIndex; } public void setCurPage(int curPage) { this.curPage = curPage; } public int getPageNum() { return pageNum; } public void setPageNum(int pageNum) { this.pageNum = pageNum; } public int getPrePage() { return prePage; } public void setPrePage(int prePage) { this.prePage = prePage; } public int getNextPage() { return nextPage; } public void setNextPage(int nextPage) { this.nextPage = nextPage; } public int getTotalPage() { return totalPage; } public void setTotalPage(int totalPage) { this.totalPage = totalPage; } public int getTotal() { return total; } public void setTotal(int total) { this.total = total; } public List getData() { return data; } public void setData(List data) { this.data = data; } }

Persistence layer part of the fifth model layer:

package cn.pk.dao.impl; import java.sql.SQLException; import java.util.List; import java.util.Map; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.BeanListHandler; import org.apache.commons.dbutils.handlers.MapHandler; import org.apache.commons.lang.StringUtils; import cn.pk.dao.EmpDao; import cn.pk.entity.Emp; import cn.pk.util.MyDbUtils; /** * 模型层的持久层(数据库的sql语句) * @author 摸摸大白兔 *时间 2017年10月20日 下午1:24:12 * */ public class EmpDaoImp implements EmpDao{ public int countEmp(String ename) throws SQLException { QueryRunner qr=new QueryRunner(MyDbUtils.bds); String sql="select count(*) as myCount from newemp"; if(StringUtils.isNotEmpty(ename)) { sql+=" where ename like '%"+ename+"%'"; } Map map=(Map)qr.query(sql,new MapHandler()); return Integer.parseInt(map.get("myCount").toString()); } @Override public List queryEmp(String ename,int startIndex,int pageNum) throws SQLException { QueryRunner qr=new QueryRunner(MyDbUtils.bds); String sql="select * from newemp"; if(StringUtils.isNotEmpty(ename)) { sql+=" where ename like '%"+ename+"%'"; } sql+=" limit "+startIndex+","+pageNum; List empList = (List)qr.query(sql,new BeanListHandler(Emp.class)); return empList; } }

Excuse class part:

package cn.pk.dao; import java.sql.SQLException; import java.util.List; import cn.pk.entity.Emp; public interface EmpDao { public int countEmp(String ename) throws SQLException ; List queryEmp(String name,int startIndex,int pageNum) throws SQLException; }

第六servlet部分:

package cn.pk.servlet.impl; import java.sql.SQLException; import java.util.List; import org.apache.commons.lang.StringUtils; import cn.pk.dao.EmpDao; import cn.pk.dao.impl.EmpDaoImp; import cn.pk.entity.Emp; import cn.pk.servlet.EmpService; import cn.pk.util.PageBean; public class EmpServiceImpl implements EmpService{ private EmpDao dao=new EmpDaoImp(); @Override public PageBean queryEmp(String ename,String curPage,String pageNum) throws Exception { //如果第一次没有访问当前页 if(StringUtils.isEmpty(curPage)) { curPage="1"; } if(StringUtils.isEmpty(pageNum)) { pageNum="10"; } //转换为int类型 int curPageIn =Integer.parseInt(curPage); int pageNumIn= Integer.parseInt(pageNum); int total=dao.countEmp(ename); PageBean pb=new PageBean(curPageIn,pageNumIn,total); List queryEmp = dao.queryEmp(ename,pb.getStartIndex(), pb.getPageNum()); pb.setData(queryEmp); return pb; } }

servlet接口类部分:

package cn.pk.servlet; import java.sql.SQLException; import java.util.List; import cn.pk.entity.Emp; import cn.pk.util.PageBean; public interface EmpService { public PageBean queryEmp(String ename, String curPage,String pageNum) throws Exception; }

最后的执行效果如图:
How the MVC framework implements paging query of database data

好了。一个简易完整版的数据库表查询就完成了;

The above is the detailed content of How the MVC framework implements paging query of database data. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete