SpringMVC paging, interceptor implementation, and springmvc paging implementation

Source: Internet
Author: User

SpringMVC paging, interceptor implementation, and springmvc paging implementation

PageInterceptor. java

@ Intercepts ({@ Signature (type = StatementHandler. class, method = "prepare", args = {Connection. class}) public class PageInterceptor implements Interceptor {private static final Logger logger = Logger. getLogger (PageInterceptor. class); private static final ObjectFactory DEFAULT_OBJECT_FACTORY = new DefaultObjectFactory (); private static final ObjectWrapperFactory DEFAULT_OBJECT_WRAPPER_FACTORY = New DefaultObjectWrapperFactory (); private static String defaultPageSqlId = ". * Page $ "; // The ID to be intercepted (regular match) private static String pageSqlId =" "; // The ID to be intercepted (regular match) @ Override public Object intercept (Invocation invocation) throws Throwable {StatementHandler statementHandler = (StatementHandler) invocation. getTarget (); MetaObject metaStatementHandler = MetaObject. forObject (statementHandler, DEFAULT_O BJECT_FACTORY, DEFAULT_OBJECT_WRAPPER_FACTORY); // separates the proxy object chain (because the target class may be intercepted by multiple interceptors, multiple proxies are formed, the following two loops can be used to separate the original target class.) while (metaStatementHandler. hasGetter ("h") {Object object = metaStatementHandler. getValue ("h"); metaStatementHandler = MetaObject. forObject (object, DEFAULT_OBJECT_FACTORY, DEFAULT_OBJECT_WRAPPER_FACTORY);} // separates the target class of the last proxy object while (metaStatementHandler. hasGetter ("target") {Object object = MetaStatementHandler. getValue ("target"); metaStatementHandler = MetaObject. forObject (object, DEFAULT_OBJECT_FACTORY, DEFAULT_OBJECT_WRAPPER_FACTORY);} Configuration configuration Configuration = (Configuration) metaStatementHandler. getValue ("delegate. configuration "); Properties properties = configuration. getVariables (); if (null! = Properties & StringUtils. isNotBlank (properties. getProperty ("pageSqlId") {pageSqlId = properties. getProperty ("pageSqlId");} else {pageSqlId = defaultPageSqlId;} MappedStatement mappedStatement = (MappedStatement) metaStatementHandler. getValue ("delegate. mappedStatement "); // only rewrite the SQL statement that requires paging. By default, if (MappedStatement. getId (). matches (pageSqlId) {BoundSql boundSql = (BoundSql) metaStatementHandler. getValue ("delegate. boundSql "); Object parameterObject = boundSql. getParameterObject (); if (parameterObject = null) {throw new NullPointerException ("parameterObject is null! ");} Map <String, Object> paramMap = (Map) parameterObject; PageParameter page = (PageParameter) paramMap. get ("0"); String SQL = boundSql. getSql (); // rewrite SQL String pageSql = buildPageSqlForMysql (SQL, page); metaStatementHandler. setValue ("delegate. boundSql. SQL ", pageSql); // after the physical paging is used, the mybatis memory paging is not required. Therefore, reset the following two parameters: metaStatementHandler. setValue ("delegate. rowBounds. offset ", RowBounds. NO_ROW_OFFSET); met AStatementHandler. setValue ("delegate. rowBounds. limit ", RowBounds. NO_ROW_LIMIT); Connection connection Connection = (Connection) invocation. getArgs () [0]; // reset setPageParameter (SQL, connection, mappedStatement, boundSql, page) such as the total number of pages in the page parameter );} // give the execution permission to the next interceptor return invocation. proceed () ;}@ Override public Object plugin (Object target) {// The target class is packaged when the target class is of the StatementHandler type. Otherwise, the target class is directly returned, reduce the number of times target instanceo F StatementHandler) {return Plugin. wrap (target, this) ;}else {return target ;}@override public void setProperties (Properties properties Properties) {// TODO Auto-generated method stub}/*** mysql paging statement ** @ param SQL * @ param page * @ return String */public String buildPageSqlForMysql (String SQL, pageParameter page) {StringBuilder pageSql = new StringBuilder (100); String beginrow = String. valueOf (p Age. getCurrentPage ()-1) * page. getPageSize (); pageSql. append (SQL); pageSql. append ("limit" + beginrow + "," + page. getPageSize (); return pageSql. toString ();} private void setPageParameter (String SQL, Connection connection, MappedStatement mappedStatement, BoundSql boundSql, PageParameter page) {// total number of records String countSql = "select count (0) from ("+ SQL +") as total "; PreparedStatement coun TStmt = null; ResultSet rs = null; try {countStmt = connection. prepareStatement (countSql); BoundSql countBS = new BoundSql (mappedStatement. getConfiguration (), countSql, boundSql. getParameterMappings (), boundSql. getParameterObject (); setParameters (countStmt, mappedStatement, countBS, boundSql. getParameterObject (); rs = countStmt.exe cuteQuery (); int totalCount = 0; if (rs. next () {totalCount = r S. getInt (1);} page. setTotalCount (totalCount); int totalPage = totalCount/page. getPageSize () + (totalCount % page. getPageSize () = 0 )? 0: 1); page. setTotalPage (totalPage);} catch (SQLException e) {logger. error ("Ignore this exception", e);} finally {try {rs. close ();} catch (SQLException e) {logger. error ("Ignore this exception", e);} try {countStmt. close ();} catch (SQLException e) {logger. error ("Ignore this exception", e) ;}} private void setParameters (PreparedStatement ps, MappedStatement mappedStatement, BoundSql boundSql, Object parameterObject) throws SQLException {ParameterHandler parameterHandler = new DefaultParameterHandler (mappedStatement, parameterObject, boundSql); parameterHandler. setParameters (ps );}}

PageParameter. java

public class PageParameter {    public static final int DEFAULT_PAGE_SIZE = 10;    private int pageSize;    private int currentPage;    private int prePage;    private int nextPage;    private int totalPage;    private int totalCount;    public PageParameter() {        this.currentPage = 1;        this.pageSize = DEFAULT_PAGE_SIZE;    }    /**     *      * @param currentPage     * @param pageSize     */    public PageParameter(int currentPage, int pageSize) {        this.currentPage = currentPage;        this.pageSize = pageSize;    }    public int getCurrentPage() {        return currentPage;    }    public void setCurrentPage(int currentPage) {        this.currentPage = currentPage;    }    public int getPageSize() {        return pageSize;    }    public void setPageSize(int pageSize) {        this.pageSize = pageSize;    }    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 getTotalCount() {        return totalCount;    }    public void setTotalCount(int totalCount) {        this.totalCount = totalCount;    }    public String toString() {        return ToStringBuilder.reflectionToString(this);    }}

Mybatis-config.xml Configuration

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd"><configuration>    <plugins>        <plugin interceptor="*.*.PageInterceptor"></plugin>    </plugins></configuration>

Usage:

Map<String, Object> paramMap = new HashMap<String, Object>();        PageParameter pageParameter = new PageParameter();        pageParameter.setCurrentPage(10000);        userService.findUserPage(pageParameter, null);

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.