search
HomeBackend DevelopmentPHP TutorialHow the MVC framework implements paging query of database data

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">


<meta>
<title>Insert title here</title>

<style>
	table tr td{
		border:1px solid black;
	}
</style>




雇员姓名:
雇员编号 雇员姓名 雇员薪水 雇员职位
${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<emp> 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();
		}
	
	}

}</emp>

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<t> {
	
	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<totalpage private> 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<t> getData() {
		return data;
	}

	public void setData(List<t> data) {
		this.data = data;
	}

}</t></t></totalpage></t>

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<emp> 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<emp> empList = (List<emp>)qr.query(sql,new BeanListHandler(Emp.class));
		
		return empList;
	}

}</emp></emp></emp>

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<emp> queryEmp(String name,int startIndex,int pageNum) throws SQLException;
}</emp>

第六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<emp> 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<emp> pb=new PageBean(curPageIn,pageNumIn,total);
		
		List<emp> queryEmp = dao.queryEmp(ename,pb.getStartIndex(), pb.getPageNum()); 
		pb.setData(queryEmp);
		
		return pb;
	}
}</emp></emp></emp>

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<emp> queryEmp(String ename, String curPage,String pageNum) throws Exception;
	
}</emp>

最后的执行效果如图:
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. If there is any infringement, please contact admin@php.cn delete
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools