1. 程式人生 > >Mybatis分頁實現

Mybatis分頁實現

一、引言

Mybatis提供了強大的分頁攔截實現,可以完美的實現分功能

二、普通的分頁實現

普通分頁實現即使直接在mapper檔案中寫分頁查詢語句

Messsage.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
    PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.imooc.bean.Message">

  <resultMap type="com.imooc.bean.Message" id="MessageResult">
    <id column="id" jdbcType="INTEGER" property="id"/>
    <result column="command" jdbcType="VARCHAR" property="command"/>
    <result column="description" jdbcType="VARCHAR" property="description"/>
    <result column="content" jdbcType="VARCHAR" property="content"/>
  </resultMap>

  <!-- 
	普通分頁實現		
	使用sql實現分頁查詢,不是使用攔截器 
  	oracle分頁使用rownum,子查詢呢需要使用別名不能使用rownum,row等關鍵字
  -->
  <select id="queryMessageListByPage" parameterType="java.util.Map" resultMap="MessageResult">
  	select * from ( select rownum r, id,command,description,content from message
  	 	<where>
  			<if test="command != null and command.trim() != ''">
  				and command=#{command}
  			</if>
  			<if test="descriptioin != null and description.trim() != '' ">
  				and descriptioin=#{descriptioin}
  			</if>
  			<if test="page != null">
  			 	and rownum <= #{page.dbNumber}
  			</if>
 		 </where>
  		)
  		<where>
  			 and r > #{page.dbIndex}
 		 </where>
 		 order by id
  </select>
  <select id="count" parameterType="com.imooc.bean.Message"  resultType="int">
    select count(*) from message
    <where>
    	<if test="command != null and !"".equals(command.trim())">
	    	and command=#{command}
	    </if>
	    <if test="description != null and ''!=description.trim()">
	    	and description like concat(concat('%',#{description}),'%')
	    </if>
    </where>
  </select>
</mapper>

Page.java分頁相關的引數都通過該類物件設定

package com.imooc.common;

/**
 * 分頁對應的實體類
 */
public class Page {
	/**
	 * 總條數
	 * */
	private int totalNumber;

	/**
	 * 總頁數
	 * */
	private int totalPage;

	/**
	 * 當前頁
	 * */
	private int currentPage;

	/**
	 * 每頁顯示的數目
	 * */
	private int pageNumber = 5;

	/**
	 * 資料庫中limit的引數,從第幾條開始取
	 * */
	private int dbIndex;

	/**
	 * 資料庫中limit的引數,一共取多少條,適用於mysql, 如果是oracle則表示最大取到的條數
	 * */
	private int dbNumber;

	/**
	 * 根據當前物件中的屬性值計算並設定相關屬性的值
	 * */
	
	public void count() {
		// 計算總頁數
		int totalPageTemp = this.totalNumber / this.pageNumber;
		int plus = (this.totalNumber % this.pageNumber) == 0 ? 0 : 1;
		totalPageTemp += plus;
		// 如果總頁數小於0顯示第一頁
		if (totalPageTemp <= 0) {
			totalPageTemp += 1;
		}
		this.totalPage = totalPageTemp;	
		//設定limit引數
		this.dbIndex = (this.currentPage -1 ) * this.pageNumber;
		this.dbNumber = this.pageNumber;
	}

	public int getTotalNumber() {
		return totalNumber;
	}

	public void setTotalNumber(int totalNumber) {
		this.totalNumber = totalNumber;
		count();
	}

	public int gettotalPage() {
		return totalPage;
	}

	public void settotalPage(int totalPage) {
		this.totalPage = totalPage;
	}

	public int getCurrentPage() {
		return currentPage;
	}

	public void setCurrentPage(int currentPage) {
		this.currentPage = currentPage;
		count();
	}

	public int getPageNumber() {
		return pageNumber;
	}

	public void setPageNumber(int pageNumber) {
		this.pageNumber = pageNumber;
	}

	public int getDbIndex() {
		return dbIndex;
	}

	public void setDbIndex(int dbIndex) {
		this.dbIndex = dbIndex;
	}

	public int getDbNumber() {
		return dbNumber;
	}

	public void setDbNumber(int dbNumber) {
		this.dbNumber = dbNumber;
	}
	
}

Dao層實現
package com.imooc.dao;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.session.SqlSession;
import com.imooc.bean.Message;
import com.imooc.common.Page;
import com.imooc.db.DBAccess;

public class MessageDao {

	DBAccess dbAccess = new DBAccess();
 
	//計算查詢的資料的總數
	
         public int getMessageCount(String command,String description) throws Exception{
		int count = 0;
		SqlSession session = null;
		try {
			session = dbAccess.getSqlSession();
			Message message = new Message();
			message.setCommand(command);
			message.setDescription(description);
			count = session.selectOne(Message.class.getName()+".count", message);
		} catch (Exception e) {
			throw new Exception(e.getMessage());
		} finally {
			if (session != null) {
				session.close();
			}
		}
		return count;
	} 
    
	//分頁實現主要的方法
	public List<Message> queryMessageListByPage(String command, String description,Page page) throws Exception {
		List<Message> messagesList = null;
		SqlSession session = null;
		try {
			session = dbAccess.getSqlSession();
			Map<String, Object> paramater = new HashMap<String, Object>();
			paramater.put("command", command);
			paramater.put("description", description);
			paramater.put("page", page);
			messagesList = session.selectList(Message.class.getName()+".queryMessageListByPage2", paramater);
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception(e.getMessage());
		} finally {
			if (session != null) {
				session.close();
			}
		}
		return messagesList;
	}
	

}


Service層實現

呼叫Dao層的方法,返回本次查詢的資料

package com.imooc.service;

import java.util.ArrayList;
import java.util.List;
import com.imooc.bean.Message;
import com.imooc.common.Page;
import com.imooc.dao.MessageDao;

public class MessageService {

	MessageDao dao = new MessageDao();

	public int getCount(String command, String description) throws Exception {
		int count = 0;
		try {
			count= dao.getMessageCount(command, description);
		} catch (Exception e) {
			throw new Exception(e.getMessage());
		}
		return count;
	}
	

	public List<Message> queryMessageListByPage(String command, String description,Page page) throws Exception {
		List<Message> messageList = null;
		try {
			messageList = dao.queryMessageListByPage(command, description, page);
		} catch (Exception e) {
						throw new Exception(e.getMessage());

		}
		return messageList;
	}
}



ListServet.java 

用於接收前臺頁面的引數,以及傳回資料給jsp頁面

package com.imooc.servlet;

import java.io.IOException;
import java.util.List;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.imooc.bean.Message;
import com.imooc.common.Page;
import com.imooc.service.MessageService;

public class ListServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	MessageService messageService = new MessageService();

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
		try {
			// 設定編碼
			req.setCharacterEncoding("utf-8");
			// 接受引數
			String command = req.getParameter("command");
			String description = req.getParameter("description");
			String currentPage = req.getParameter("currentPage");
			//建立分頁物件
			Page page = new Page();
			//設定總條數
			page.setTotalNumber(messageService.getCount(command, description));
			Pattern patttern = Pattern.compile("[0-9]{1,9}"); 
			if(currentPage == null || !patttern.matcher(currentPage).matches()){
				page.setCurrentPage(1);
			}else {
				page.setCurrentPage(Integer.parseInt(currentPage));
			}
			//oracle資料庫分頁,dbNumber表示最大能取到的條數
			page.setDbNumber(page.getDbIndex()+page.getPageNumber());
			List<Message> messageList = messageService.queryMessageListByPage(command, description, page);
			req.setAttribute("command", command);
			req.setAttribute("description", description);
			req.setAttribute("messages", messageList);
			req.setAttribute("page", page);
			// 向頁面跳轉
			req.getRequestDispatcher("/WEB-INF/jsp/back/list.jsp").forward(req,resp);
		} catch (Exception e) {
			e.printStackTrace();
			req.setAttribute("retMsg", "查詢失敗");
		}
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doGet(req, resp);
	}

}

jsp頁面實現

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html xmlns="http://www.w3.org/1999/xhtml">
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
		<meta http-equiv="X-UA-Compatible"content="IE=9; IE=8; IE=7; IE=EDGE" />
		<title>內容列表頁面</title>
		<link href="<%= basePath %>css/all.css" rel="stylesheet" type="text/css" />
		<script src="<%= basePath %>js/common/jquery-1.8.0.min.js"></script>
		<script src="<%= basePath %>js/back/list.js"></script>
	</head>
	<body style="background: #e1e9eb;">
		<form action="<%= basePath %>List.action" id="mainForm" method="post">
			<input type="hidden" name="currentPage" id="currentPage" value="${page.currentPage}"/>
			
			<div class="right">
				<div class="current">當前位置:<a href="javascript:void(0)" style="color:#6E6E6E;">內容管理</a> > 內容列表</div>
				<div class="rightCont">
					<p class="g_title fix">內容列表 <a class="btn03" href="#">新 增</a>    <a class="btn03" href="javascript:deleteBatch('<%=basePath%>');">刪 除</a></p>
					<table class="tab1">
						<tbody>
							<tr>
								<td width="90" align="right">指令名稱:</td>
								<td>
									<input name="command" type="text" class="allInput" value="${command}"/>
								</td>
								<td width="90" align="right">描述:</td>
								<td>
									<input name="description" type="text" class="allInput" value="${description}"/>
								</td>
	                            <td width="85" align="right"><input type="submit" class="tabSub" value="查 詢" /></td>
	       					</tr>
						</tbody>
					</table>
					<div class="zixun fix">
						<table class="tab2" width="100%">
							<tbody>
								<tr>
								    <th><input type="checkbox" id="all" onclick="javascript:selAllCheckbox('id')"/></th>
								    <th>序號</th>
								    <th>指令名稱</th>
								    <th>描述</th>
								    <th>操作</th>
								</tr>
								<c:forEach items="${requestScope.messages}" var="message" varStatus="status">
									<tr  <c:if test="${status.index % 2 != 0}">style='background-color:#ECF6EE;'</c:if>>
										<td><input type="checkbox"  name="id" value="${message.id}"/></td>
										<td>${status.index + 1}</td>
										<td>${message.command}</td>
										<td>${message.description}</td>
										<td>
											<a href="#">修改</a>   
											<a href="${basePath}DeleteOneServlet.action?id=${message.id}">刪除</a>
										</td>
									</tr>
								</c:forEach>
							</tbody>
						</table>
						<div class='page fix'>
							共 <b>${page.totalNumber}</b> 條
							共<b>${page.totalPage }</b>頁
							<c:if test="${page.currentPage != 1}">
								<a href="javascript:changeCurrentPage('1')" class='first'>首頁</a>
								<a href="javascript:changeCurrentPage('${page.currentPage-1}')" class='pre'>上一頁</a>
							</c:if>
							當前第<span>${page.currentPage}/${page.totalPage}</span>頁
							<c:if test="${page.currentPage != page.totalPage}">
								<a href="javascript:changeCurrentPage('${page.currentPage+1}')" class='next'>下一頁</a>
								<a href="javascript:changeCurrentPage('${page.totalPage}')" class='last'>末頁</a>
							</c:if>
							跳至 <input id="currentPageText" type='text' value='${page.currentPage}' class='allInput w28' /> 頁 
							<a href="javascript:changeCurrentPage($('#currentPageText').val())" class='go'>GO</a>
						</div>
					</div>
				</div>
			</div>
	    </form>
	</body>
</html>

使用jquery提交分頁引數

/*
 * 實現翻頁功能
 */
function changeCurrentPage(currentPage){
$("#currentPage").val(currentPage).val();
$("#mainForm").submit();
}

三、使用Mybatis分頁攔截器實現

 使用Mybatis分頁攔截器,我們可以不用在Mapper配置檔案中寫分頁查詢語句,我們只需要寫非分頁查詢語句就行,然後通過分頁攔截器,攔截到需要分頁查詢的普通sql

將普通的sql替換成分頁sql,非常巧妙的實現分頁查詢

1.實現攔截器我們需實現Interceptor

我們假如將攔截器形象的比喻成夠票與代理商

[email protected]註解聲明瞭代夠員取哪裡攔截需要買票的顧客(去哪裡攔截顧客)

b.setProperties獲取Configuration.xml中plugins--》plugin--->propertis中的固定資本(公司固定資本)

c.plugin方法中判斷是否需要攔截(顧客是否需要購票)

d.intercept方法中可以獲取原始的sql(非分頁查詢的sql),和分頁引數   通過取到這些引數替換掉原來的sql即程式設計分頁sql(代購員從顧客哪裡獲取資訊)

package com.imooc.interceptor;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Map;
import java.util.Properties;

import org.apache.ibatis.executor.parameter.ParameterHandler;
import org.apache.ibatis.executor.statement.RoutingStatementHandler;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
import org.apache.ibatis.session.Configuration;

import com.imooc.common.Page;

/**
 * myBatis分頁攔截器實現
 * 攔截器在配置檔案Configuration.xml中註冊後,通過下邊的註解宣告攔截的類,方法,方法引數
 * */
//type指向需要攔截的介面,method指向需要攔截的方法,args指向方法中的引數
//StatementHandler是一個介面,實現類是BaseStatementHanlder,實現了其中的prepare方法,實現方法中instantiateStatement(connection)
//返回Statement
@Intercepts({@Signature(type=StatementHandler.class,method="prepare",args={Connection.class})})
public class PageInterceptor implements Interceptor{
	private Object object;
	private static String defualtSqlId = ".+ByPage$";  //需要攔截的配置檔案中的id的正則表示式
	private static String defaultDialect = "oracle";   //預設資料庫型別
	private String dialect;     			//資料庫型別
	
	/**
	 * 3.代購
	 * 可以指定攔截對映檔案中那種id的值,
	 * invocation中可以獲取想要的資料
	 * */
	@Override
	public Object intercept(Invocation invocation) throws Throwable {
		//代理業務員獲取代理物件的攜帶的資訊(需要買票的人哪裡獲取資訊)
		StatementHandler statementHandler =	(StatementHandler)invocation.getTarget();
		//使用metaObject中獲取statementHandler屬性的值
		MetaObject metaObject = MetaObject.forObject(statementHandler, SystemMetaObject.DEFAULT_OBJECT_FACTORY, SystemMetaObject.DEFAULT_OBJECT_WRAPPER_FACTORY);
		//BaseStatementHandler-->mappedStatement(delegate為<span style="font-family: Arial, Helvetica, sans-serif;">mappedStatement屬性名</span><span style="font-family: Arial, Helvetica, sans-serif;">)</span>
		MappedStatement mappedStatement=(MappedStatement) metaObject.getValue("delegate.mappedStatement");
	       Configuration configuration = (Configuration) metaObject.getValue("delegate.configuration");
		//獲取資料庫型別,獲取Configuration.xml properties標籤中宣告的變數
	    dialect = configuration.getVariables().getProperty("dialect");
	    if (null == dialect || "".equals(dialect)) {
            dialect = defaultDialect;
        }
		//獲取mapper檔案中sql語句的id
		String pageSqlId = mappedStatement.getId();
		if(pageSqlId.matches(defualtSqlId)){//獲取已Bypage結尾的id中的sql語句    		攔截誰
			BoundSql boundSql = statementHandler.getBoundSql();
			//獲取原始的sql
			String sql = boundSql.getSql();
			//查詢總條數
			String countSql = "select count(*) from ("+sql+") a";
			Connection connection = (Connection) invocation.getArgs()[0];
			PreparedStatement countStatement = connection.prepareStatement(countSql);
			//獲取原始的sql引數資訊
			ParameterHandler parameterHandler =  (ParameterHandler) metaObject.getValue("delegate.parameterHandler");
			//設定引數值
			parameterHandler.setParameters(countStatement);
			//執行獲取總條數
			ResultSet rs = countStatement.executeQuery();
			
			//改造成帶分頁查詢的sql,獲取傳給配置檔案的引數,就是MessageDao中queryMessageListByPage中方法執行中傳遞進去的map引數,所以需要強轉
			Map<String, Object> parameter = (Map<String, Object>) boundSql.getParameterObject();
			//paramter(map)中傳入的page物件的引數
			Page page = (Page)parameter.get("page"); 
			//設定page的總條數
			if(rs.next()){
				page.setTotalNumber(rs.getInt(1));
			}
			//改造成帶分頁查詢的sql
			String pageSql = buildPageSql(sql,page);
			//替換員來的sql
			//第一引數:找到原始碼中的sql
			//第二個引數:改造後的sql
			metaObject.setValue("delegate.boundSql.sql", pageSql);   		//買票
		}
		return invocation.proceed();   //交回主權,買票後送回
	}

	/**
	 * 2.定位客戶  @Intercepts({@Signature(type=StatementHandler.class,method="prepare",args={Connection.class})})
	 * 如果攔截成功,會返回一個代理類(業務員),然後會執行intercept方法
	 * 就好比攔截到買票的人,需不需要買票,不需要放行,return就是放行
	 * 需要就代表一種協議Plugin.wrap(target, this);
	 * target就好比攔截住的需要買票的人,this就是公司的業務員,返回後this就變成可以代理target去買票的業務員
	 * */
	@Override
	public Object plugin(Object target) {
		return Plugin.wrap(target, this);
	}

	/**
	 * 1.獲取固定資本
	 * 獲取Configuration.xml中的plugin中的property中的屬性值
	 * */
	@Override
	public void setProperties(Properties properties) {
		this.object = properties.get("test"); 
	}
	
	/**
	 * 改造成帶分頁查詢的sql
	 * sql原始sql(不帶分頁功能)
	 * Page page分頁實體類物件
	 **/
	public String buildPageSql(String sql,Page page){
		StringBuilder builder = new StringBuilder();
		if(dialect.equals("oracle")){
			builder = pageSqlForOracle(sql, page);
		}
		if(dialect.equals("mysql")){
			pageSqlForMysql(sql, page);
		}
		return builder.toString();
	}
	//mysql分頁查詢
	public StringBuilder pageSqlForMysql(String sql,Page page){
		StringBuilder builder = new StringBuilder();
		builder.append(sql);
		builder.append(" limit "+page.getDbIndex()+","+page.getDbNumber());
		builder.append(" order by id");
		return builder;
	}

	/**
	 * 實現oracle分頁
	 * */
	public StringBuilder pageSqlForOracle(String sql,Page page){
		StringBuilder builder = new StringBuilder();
		builder.append("select * from ( select rownum r, id,command,description,content from (");
		builder.append(sql);
		builder.append(") where rownum <= ").append(page.getDbNumber()+page.getDbIndex());
		builder.append(") where r > ").append(page.getDbIndex());
		builder.append(" order by id");
		System.out.println(builder.toString());
		return builder;
	}
}

Configuration.xml中註冊分頁攔截器外掛
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
    PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>
	<properties>
		<property name="dialect" value="oracle" />
	</properties>
	<!-- 攔截器可以有很多,就像代購公司有很多每一個公司都需要註冊,下邊就是註冊 -->
	<plugins>
		<plugin interceptor="com.imooc.interceptor.PageInterceptor">
			<property name="test" value="interceptor" /><!-- property中的值可以在攔截器中的setProperties中拿到 -->
		</plugin>
	</plugins>

	<environments default="development">
		<environment id="development">
			<transactionManager type="JDBC">
				<property name="" value="" />
			</transactionManager>
			<dataSource type="UNPOOLED">
				<property name="driver" value="oracle.jdbc.driver.OracleDriver" />
				<!-- <property name="url" value="jdbc:oracle:thin:@localhost:1521:orcl"/> -->
				<property name="url" value="jdbc:oracle:thin:@localhost:1521:xe" />
				<property name="username" value="caojx" />
				<property name="password" value="caojx" />
			</dataSource>
		</environment>
	</environments>

	<mappers>
		<mapper resource="com/imooc/config/sqlxml/Message.xml" />
	</mappers>

</configuration>

Message.xml變化

不需要寫分語句

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE mapper
    PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.imooc.bean.Message">

  <resultMap type="com.imooc.bean.Message" id="MessageResult">
    <id column="id" jdbcType="INTEGER" property="id"/>
    <result column="command" jdbcType="VARCHAR" property="command"/>
    <result column="description" jdbcType="VARCHAR" property="description"/>
    <result column="content" jdbcType="VARCHAR" property="content"/>
  </resultMap>

<!-- select標籤用於書寫查詢語句-->
  <select id="queryMessageListByPage" parameterType="java.util.Map" resultMap="MessageResult">
    select id,command,description,content from message
    <where>
    	<if test="command != null and !"".equals(command.trim())">
	    	and command=#{command}
	    </if>
	    <!-- like 查詢一般會拼接concat()拼接兩個字串 -->
	    <if test="description != null and ''!=description.trim()">
	    	and description like concat(concat('%',#{description}),'%')
	    </if>
    </where>
  </select>
</mapper>

ListServlet.java中的一小點變化

package com.imooc.servlet;

import java.io.IOException;
import java.util.List;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.imooc.bean.Message;
import com.imooc.common.Page;
import com.imooc.service.MessageService;

public class ListServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	MessageService messageService = new MessageService();

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
		try {
			// 設定編碼
			req.setCharacterEncoding("utf-8");
			// 接受引數
			String command = req.getParameter("command");
			String description = req.getParameter("description");
			String currentPage = req.getParameter("currentPage");
			//建立分頁物件
			Page page = new Page();	
			Pattern patttern = Pattern.compile("[0-9]{1,9}"); 
			if(currentPage == null || !patttern.matcher(currentPage).matches()){
				page.setCurrentPage(1);
			}else {
				page.setCurrentPage(Integer.parseInt(currentPage));
			}
			List<Message> messageList = messageService.queryMessageListByPage(command, description, page);
			req.setAttribute("command", command);
			req.setAttribute("description", description);
			req.setAttribute("messages", messageList);
			req.setAttribute("page", page);
			// 向頁面跳轉
			req.getRequestDispatcher("/WEB-INF/jsp/back/list.jsp").forward(req,resp);
		} catch (Exception e) {
			e.printStackTrace();
			req.setAttribute("retMsg", "查詢失敗");
		}
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doGet(req, resp);
	}

}

結果圖


注:本案例思想有慕課網提供指導

相關推薦

Mybatis實現的方法(攔截器+pageHelper)

一、攔截器實現 1.原理 在mybatis 執行過程中攔截執行物件,獲得sql資訊,將分頁資訊新增到sql語句中,然後放行mybatis的執行過程 2.瞭解一點mybatis原始碼 首先我們需要明白要攔截的物件是處理物件(Statement),攔截的時機應該是sql執

mybatis實現(非外掛方式)

前面一篇文章介紹了通過攔截器發方式實現mybatis分頁(應該是比較常用的一種方式,網上搜索結果較多),這裡介紹另一種方式:通過程式碼封裝,不改變mybatis框架的任何東西(個人推薦使用該方式),這個程式碼是我老大寫的,個人覺得很好,原理也很簡單,修改也很容易,所以貼出來

Mybatis實現

一、引言 Mybatis提供了強大的分頁攔截實現,可以完美的實現分功能 二、普通的分頁實現 普通分頁實現即使直接在mapper檔案中寫分頁查詢語句 Messsage.xml <?xml version="1.0" encoding="UTF-8"?> <

MyBatis學習——第五篇(手動和pagehelper實現

1:專案場景介紹 在專案中分頁是十分常見的功能,一般使用外掛實現分頁功能,但是在使用外掛之前我們首先手動寫出分頁程式碼,發然對比外掛實現的分頁,利於我們理解分頁底層實現和更好的實現外掛分頁實用技術,本次使用的外掛是PageHelper(採用都是物理分頁) 在開始之前我們建立兩個表,分別是t_

MyBatis學習——第四篇(攔截器和攔截器實現

MyBatis架構體圖 1:mybatis核心物件 從MyBatis程式碼實現的角度來看,MyBatis的主要的核心部件有以下幾個: SqlSession         &n

MyBatis功能的實現(陣列、sql、攔截器,RowBounds

前言:學習hibernate & mybatis等持久層框架的時候,不外乎對資料庫的增刪改查操作。而使用最多的當是資料庫的查詢操

Ext實現(前臺與後臺)Spring+Mybatis

Ext分頁實現(前臺與後臺)Spring+Mybatis 一、專案背景   關於Ext的分頁網上有很多部落格都有提到,但是作為Ext新手來說,並不能很容易的在自己的專案中得以應用。因為,大多數教程以及部落格基本都是隻寫了前端的東西,而關於分頁演算法更多的應該是後臺。並且大多數資料庫的sql基

基於Mybatis外掛PageHelper實現功能

使用PageHelper外掛實現分頁功能 分頁的功能幾乎是所有專案必備的功能,在SSM(spring 、springmvc、mybatis)組織的專案中如何實現分頁呢? 下面介紹一種基於mybatis的分頁外掛PageHelper來幫助我們實現分頁的功能。

mybatis攔截器的實現

import java.lang.reflect.Field; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql

SpringMVC+MyBatis外掛簡單實現

一、封裝分頁page類 package com.framework.common.page.impl; import java.io.Serializable; import com.framework.common.page.IPage; /*

MyBatis的簡單實現

使用spring+springmvc+mybatis實現簡單的分頁查詢 spring+springmvc+mybatis的整合配置就不在贅述了 1.需要下載pagehelper-3.2.1.jar

MyBatis自動實現

近兩天一直再研究MyBatis的分頁問題,看了別人的處理方式,自己總結優化了一下,寫了兩個攔截類,給有需要的人使用和參考,原始碼請下載附件。 主要有3個類:Page,MybatisPageInterceptor,MybatisSpringPageInterceptor

mybatis外掛實現

1.瞭解過程:在資料庫伺服器中,sql語句實現分頁便要每個查詢語句都要寫上limit(開始,結束),並且不能靈活的隨前端變化,為此使用攔截器的方法,過程:攔截器攔截請求的sql語句(根據需要攔截的ID(正則匹配),進行攔截),並對根據前端傳過來的頁數,和每頁的條

Mybatis

less namespace als order sta mes type utf-8 space <?xml version="1.0" encoding="UTF-8"?><!DOCTYPE mapper PUBLIC "-//mybatis.org

Spring實現PageImpl<T>類

sea equals public ini ack format contain link 部分 Spring框架中PageImpl<T>類的源碼如下: /* * Copyright 2008-2013 the original author or aut

Mybatis助手PageHelper

助手 myba size 分頁 tails net 16px pan ron 註意:PageHelper.startPage(1, 3);這個方法是從1開始而非0 參考: http://blog.csdn.net/zbw18297786698/article/detail

Mybatis插件-PageHelper的使用

epo obj 實現 默認值 prev asn release dsm out 轉載:http://blog.csdn.net/u012728960/article/details/50791343 Mybatis分頁插件-PageHelper的使用 怎樣配置mybat

symfony實現方法

ont param creat com render 實現 使用 ext urn 1.symfony分頁是要用到組件的,所以這裏使用KnpPaginatorBundle實現翻頁 2. 用composer下載 在命令行中: composer require "

Mybatis插件

-- dep tor mvn repos version pid enc 5.0 <!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper --><dependency

整合mybatis插件及通用接口測試出現問題

ping provide form onf ann tsql tro com nbsp 嚴重: Servlet.service() for servlet [springmvc] in context with path [/mavenprj] threw excepti