springMVC中通用的分页配置

来源:互联网 发布:手机sd卡数据免费恢复 编辑:程序博客网 时间:2024/06/01 10:26

在前面的文章中,我们一步步完成了springmvc的maven工程的搭建,整合mybatis,日志,等操作,本文在此基础上继续添加通用的分页操作,并贴出源码供给参考。

下面先讲解本文通用的分页配置,其实通用目前仅支持oracle和mysql的两大主流数据库分页

一,此前的项目下建立新的实体类Page,并添加util包新增几个工具类,最后修改我们原先的mybatis-config.xml配置文件即可



page.java:用于封装分页的实体类

package com.test.entity;import com.test.util.PageData;import java.io.Serializable;import java.util.ArrayList;import java.util.List;/** * 分页类 * @author yufeng * 创建时间:2017-10-12 */public class Page implements Serializable{    /**     *      */    private static final long serialVersionUID = 1L;    private int showCount = 5; //每页显示记录数,默认为5条    private int totalPage; //总页数    private int totalResult; //总记录数    private int currentPage; //当前页    private int currentResult; //当前记录起始索引    private boolean entityOrField; //true:需要分页的地方,传入的参数就是Page实体;false:需要分页的地方,传入的参数所代表的实体拥有Page属性    private String pageStr; //最终页面显示的底部翻页导航,详细见:getPageStr();    private String formName;//分页时所要提交的form的名字    private PageData pd = new PageData();    private List<PageData> list = new ArrayList<PageData>();    public int getTotalPage()    {        if (totalResult % showCount == 0)            totalPage = totalResult / showCount;        else            totalPage = totalResult / showCount + 1;        return totalPage;    }    public void setTotalPage(int totalPage)    {        this.totalPage = totalPage;    }    public int getTotalResult()    {        return totalResult;    }    public void setTotalResult(int totalResult)    {        this.totalResult = totalResult;    }    public int getCurrentPage()    {        if (currentPage <= 0)            currentPage = 1;        if (currentPage > getTotalPage())            currentPage = getTotalPage();        return currentPage;    }    public void setCurrentPage(int currentPage)    {        this.currentPage = currentPage;    }    //拼接分页 页面及JS函数    public String getPageStr()    {        StringBuffer sb = new StringBuffer();        if(totalResult>0){            sb.append(" <ul class=\"fanyecontrol\">\n");            if(currentPage==1){                                sb.append(" <li class=\"fyclicked\"><a>首页</a></li>\n");                sb.append(" <li class=\"fyclicked\"><a>上一页</a></li>\n");            }else{                sb.append(" <li style=\"cursor:pointer;\" class=\"fyactive\"><a onclick=\"nextPage(1)\">首页</a></li>\n");                sb.append(" <li style=\"cursor:pointer;\" class=\"fyactive\"><a onclick=\"nextPage("+(currentPage-1)+")\">上一页</a></li>\n");            }            int showTag = 5;//分页标签显示数量            int startTag = 1;            if(currentPage>showTag){                startTag = currentPage-1;            }            int endTag = startTag+showTag-1;            for(int i=startTag; i<=totalPage && i<=endTag; i++){                if(currentPage==i){                    sb.append("<li class=\"fyonclick\"><a>"+i+"</a></li>\n");                }else{                    sb.append(" <li style=\"cursor:pointer;\" class=\"fyactive\"><a onclick=\"nextPage("+i+")\">"+i+"</a></li>\n");                }            }            if(currentPage==totalPage){                sb.append(" <li class=\"fyclicked\"><a>下一页</a></li>\n");                sb.append(" <li class=\"fyclicked\"><a>末页</a></li>\n");            }else{                sb.append(" <li style=\"cursor:pointer;\" class=\"fyactive\"><a onclick=\"nextPage("+(currentPage+1)+")\">下一页</a></li>\n");                sb.append(" <li style=\"cursor:pointer;\" class=\"fyactive\"><a onclick=\"nextPage("+totalPage+")\">末页</a></li>\n");            }            sb.append(" <li>共<span>"+totalPage+"</span>页</li>\n");            sb.append(" <li>到第<input type=\"number\" value=\"\" id=\"toGoPage\" class=\"selectpage\"/>页</li>\n");            sb.append(" <li class=\"surebtn\"><a onclick=\"toTZ();\">确定</a></li>\n");                        sb.append("</ul>\n");            sb.append("<script type=\"text/javascript\">\n");                        //换页函数            sb.append("function nextPage(page){");            sb.append(" if(true && document.forms[0]){\n");            sb.append("     var url = document.forms[0].getAttribute(\"action\");\n");            sb.append("     if(url.indexOf('?')>-1){url += \"&"+(entityOrField?"currentPage":"page.currentPage")+"=\";}\n");            sb.append("     else{url += \"?"+(entityOrField?"currentPage":"page.currentPage")+"=\";}\n");            sb.append("     url = url + page + \"&" +(entityOrField?"showCount":"page.showCount")+"="+showCount+"\";\n");            sb.append("     document.forms[0].action = url;\n");            sb.append("     document.forms[0].submit();\n");            sb.append(" }else{\n");            sb.append("     var url = document.location+'';\n");            sb.append("     if(url.indexOf('?')>-1){\n");            sb.append("         if(url.indexOf('currentPage')>-1){\n");            sb.append("             var reg = /currentPage=\\d*/g;\n");            sb.append("             url = url.replace(reg,'currentPage=');\n");            sb.append("         }else{\n");            sb.append("             url += \"&"+(entityOrField?"currentPage":"page.currentPage")+"=\";\n");            sb.append("         }\n");            sb.append("     }else{url += \"?"+(entityOrField?"currentPage":"page.currentPage")+"=\";}\n");            sb.append("     url = url + page + \"&" +(entityOrField?"showCount":"page.showCount")+"="+showCount+"\";\n");            sb.append("     document.location = url;\n");            sb.append(" }\n");            sb.append("}\n");                            //跳转函数             sb.append("function toTZ(){");            sb.append("var toPaggeVlue = document.getElementById(\"toGoPage\").value;");            sb.append("if(toPaggeVlue == ''){document.getElementById(\"toGoPage\").value=1;return;}");            sb.append("if(isNaN(Number(toPaggeVlue))){document.getElementById(\"toGoPage\").value=1;return;}");            sb.append("nextPage(toPaggeVlue);");            sb.append("}\n");            sb.append("</script>\n");        }        pageStr = sb.toString();        return pageStr;    }    /**     * ajax-分页     */    public String getAjaxPageStr()    {        StringBuffer sb = new StringBuffer();        if (totalResult > 0)        {            sb.append(" <ul class=\"newpagination\">\n");            if (currentPage == 1)            {                sb.append(" <li><a><</a></li>\n");            }            else            {                sb.append(" <li style=\"cursor:pointer;\"  onclick=\"getPagInfo("                          + (currentPage - 1) + ")\"><a><</a></li>\n");            }            int showTag = 5;//分页标签显示数量            int startTag = 1;            if (currentPage > showTag)            {                sb.append("<li>...</li>\n");                startTag = currentPage - 1;            }            int endTag = startTag + showTag - 1;            for (int i = startTag; i <= totalPage && i <= endTag; i++ )            {                if (currentPage == i)                {                    sb.append("<li class=\"active\"><a><font color='white'>"                              + i + "</font></a></li>\n");                }                else                {                    sb.append(" <li style=\"cursor:pointer;\" onclick=\"getPagInfo("                              + i + ")\"><a>" + i + "</a></li>\n");                }            }            if (endTag < totalPage)            {                sb.append("<li>...</li>\n");            }            if (currentPage == totalPage)            {                sb.append(" <li><a>></a></li>\n");            }            else            {                sb.append(" <li style=\"cursor:pointer;\" onclick=\"getPagInfo("                          + (currentPage + 1) + ")\"><a>></a></li>\n");            }            sb.append("</ul>\n");            sb.append("<script type=\"text/javascript\">\n");            sb.append("</script>\n");        }        pageStr = sb.toString();        return pageStr;    }    public void setPageStr(String pageStr)    {        this.pageStr = pageStr;    }    public int getShowCount()    {        return showCount;    }    public void setShowCount(int showCount)    {        this.showCount = showCount;    }    public int getCurrentResult()    {        currentResult = (getCurrentPage() - 1) * getShowCount();        if (currentResult < 0)            currentResult = 0;        return currentResult;    }    public void setCurrentResult(int currentResult)    {        this.currentResult = currentResult;    }    public boolean isEntityOrField()    {        return entityOrField;    }    public void setEntityOrField(boolean entityOrField)    {        this.entityOrField = entityOrField;    }    public String getFormName()    {        return formName;    }    public void setFormName(String formName)    {        this.formName = formName;    }    public PageData getPd()    {        return pd;    }    public void setPd(PageData pd)    {        this.pd = pd;    }    public List<PageData> getList()    {        return list;    }    public void setList(List<PageData> list)    {        this.list = list;    }}

PageData.java:封装了map类型(相当于map类型),并封装了页面http用于请求的request参数放入此类型中

package com.test.util;import java.io.Serializable;import java.util.Collection;import java.util.HashMap;import java.util.Iterator;import java.util.Map;import java.util.Set;import javax.servlet.http.HttpServletRequest;/** * 说明:参数封装Map * 创建人:yufeng * 修改时间 2017-10-12 */@SuppressWarnings("rawtypes")public class PageData extends HashMap implements Map, Serializable {    private static final long serialVersionUID = 1L;    transient Map  map = null;    HttpServletRequest request;    @SuppressWarnings("unchecked")    public PageData(HttpServletRequest request) {        this.request = request;        Map properties = request.getParameterMap();        Map returnMap = new HashMap();        Iterator entries = properties.entrySet().iterator();        Map.Entry entry;        String name = "";        String value = "";        while (entries.hasNext()) {            entry = (Map.Entry) entries.next();            name = (String) entry.getKey();            Object valueObj = entry.getValue();            if (null == valueObj) {                value = "";            } else if (valueObj instanceof String[]) {                String[] values = (String[]) valueObj;                for (int i = 0; i < values.length; i++) {                    value = values[i] + ",";                }                value = value.substring(0, value.length() - 1);            } else {                value = valueObj.toString();            }            returnMap.put(name, value);        }        map = returnMap;    }    public PageData() {        map = new HashMap();    }    @Override    public Object get(Object key) {        Object obj = null;        if (map.get(key) instanceof Object[]) {            Object[] arr = (Object[]) map.get(key);            obj = request == null ? arr : (request.getParameter((String) key) == null ? arr : arr[0]);        } else {            obj = map.get(key);        }        return null != obj ? obj : "";    }    public String getString(Object key) {        return (String) get(key);    }    @SuppressWarnings("unchecked")    @Override    public Object put(Object key, Object value) {        return map.put(key, value);    }    @Override    public Object remove(Object key) {        return map.remove(key);    }    public void clear() {        map.clear();    }    public boolean containsKey(Object key) {        return map.containsKey(key);    }    public boolean containsValue(Object value) {        return map.containsValue(value);    }    public Set entrySet() {        return map.entrySet();    }    public boolean isEmpty() {        return map.isEmpty();    }    public Set keySet() {        return map.keySet();    }    @SuppressWarnings("unchecked")    public void putAll(Map t) {        map.putAll(t);    }    public int size() {        return map.size();    }    public Collection values() {        return map.values();    }}
PagePlugin.java:用于分页的插件工具类,根据不同的数据库,执行不同的查询分页方法:

package com.test.util;import java.lang.reflect.Field;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.util.List;import java.util.Properties;import javax.xml.bind.PropertyException;import org.apache.ibatis.executor.ErrorContext;import org.apache.ibatis.executor.ExecutorException;import org.apache.ibatis.executor.statement.BaseStatementHandler;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.mapping.ParameterMapping;import org.apache.ibatis.mapping.ParameterMode;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.property.PropertyTokenizer;import org.apache.ibatis.scripting.xmltags.ForEachSqlNode;import org.apache.ibatis.session.Configuration;import org.apache.ibatis.type.TypeHandler;import org.apache.ibatis.type.TypeHandlerRegistry;import org.apache.log4j.Logger;import org.springframework.util.StringUtils;import com.test.entity.Page;/** * * 类名称:分页插件* 类描述: * @author yufneg* 作者单位: * 联系方式:* 修改时间:2017-10-12* @version 1.0 */@Intercepts({@Signature(type=StatementHandler.class,method="prepare",args={Connection.class})})public class PagePlugin implements Interceptor {    private static String dialect = ""; //数据库方言    private static String pageSqlId = ""; //mapper.xml中需要拦截的ID(正则匹配)    private static final Logger logger = Logger.getLogger(PagePlugin.class);    public Object intercept(Invocation ivk) throws Throwable {        if(ivk.getTarget() instanceof RoutingStatementHandler){            RoutingStatementHandler statementHandler = (RoutingStatementHandler)ivk.getTarget();            BaseStatementHandler delegate = (BaseStatementHandler) ReflectHelper.getValueByFieldName(statementHandler, "delegate");            MappedStatement mappedStatement = (MappedStatement) ReflectHelper.getValueByFieldName(delegate, "mappedStatement");                        if(mappedStatement.getId().matches(pageSqlId)){ //拦截需要分页的SQL                BoundSql boundSql = delegate.getBoundSql();                Object parameterObject = boundSql.getParameterObject();//分页SQL<select>中parameterType属性对应的实体参数,即Mapper接口中执行分页方法的参数,该参数不得为空                if(parameterObject==null){                    throw new NullPointerException("parameterObject尚未实例化!");                }else{                    Connection connection = (Connection) ivk.getArgs()[0];                    String sql = boundSql.getSql();                    //String countSql = "select count(0) from (" + sql+ ") as tmp_count"; //记录统计                    String fhsql = sql;                    String countSql = "select count(0) from (" + fhsql+ ")  tmp_count"; //记录统计 == oracle 加 as 报错(SQL command not properly ended)                    PreparedStatement countStmt = connection.prepareStatement(countSql);                    BoundSql countBS = new BoundSql(mappedStatement.getConfiguration(),countSql,boundSql.getParameterMappings(),parameterObject);                    setParameters(countStmt,mappedStatement,countBS,parameterObject);                    ResultSet rs = countStmt.executeQuery();                    int count = 0;                    if (rs.next()) {                        count = rs.getInt(1);                    }                    rs.close();                    countStmt.close();                    Page page = null;                    if(parameterObject instanceof Page){    //参数就是Page实体                         page = (Page) parameterObject;                         page.setEntityOrField(true);                             page.setTotalResult(count);                    }else{  //参数为某个实体,该实体拥有Page属性                        Field pageField = ReflectHelper.getFieldByFieldName(parameterObject,"page");                        if(pageField!=null){                            page = (Page) ReflectHelper.getValueByFieldName(parameterObject,"page");                            if(page==null)                                page = new Page();                            page.setEntityOrField(false);                             page.setTotalResult(count);                            ReflectHelper.setValueByFieldName(parameterObject,"page", page); //通过反射,对实体对象设置分页对象                        }else{                            throw new NoSuchFieldException(parameterObject.getClass().getName()+"不存在 page 属性!");                        }                    }                    String pageSql = generatePageSql(sql,page);                    ReflectHelper.setValueByFieldName(boundSql, "sql", pageSql); //将分页sql语句反射回BoundSql.                }            }        }        return ivk.proceed();    }        /**     * 对SQL参数(?)设值,参考org.apache.ibatis.executor.parameter.DefaultParameterHandler     * @param ps     * @param mappedStatement     * @param boundSql     * @param parameterObject     * @throws SQLException     */    @SuppressWarnings({"rawtypes", "unchecked"})    private void setParameters(PreparedStatement ps,MappedStatement mappedStatement,BoundSql boundSql,Object parameterObject) throws SQLException {        ErrorContext.instance().activity("setting parameters").object(mappedStatement.getParameterMap().getId());        List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();        if (parameterMappings != null) {            Configuration configuration = mappedStatement.getConfiguration();            TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();            MetaObject metaObject = parameterObject == null ? null: configuration.newMetaObject(parameterObject);            for (int i = 0; i < parameterMappings.size(); i++) {                ParameterMapping parameterMapping = parameterMappings.get(i);                if (parameterMapping.getMode() != ParameterMode.OUT) {                    Object value;                    String propertyName = parameterMapping.getProperty();                    PropertyTokenizer prop = new PropertyTokenizer(propertyName);                    if (parameterObject == null) {                        value = null;                    } else if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {                        value = parameterObject;                    } else if (boundSql.hasAdditionalParameter(propertyName)) {                        value = boundSql.getAdditionalParameter(propertyName);                    } else if (propertyName.startsWith(ForEachSqlNode.ITEM_PREFIX)&& boundSql.hasAdditionalParameter(prop.getName())) {                        value = boundSql.getAdditionalParameter(prop.getName());                        if (value != null) {                            value = configuration.newMetaObject(value).getValue(propertyName.substring(prop.getName().length()));                        }                    } else {                        value = metaObject == null ? null : metaObject.getValue(propertyName);                    }                    TypeHandler typeHandler = parameterMapping.getTypeHandler();                    if (typeHandler == null) {                        throw new ExecutorException("There was no TypeHandler found for parameter "+ propertyName + " of statement "+ mappedStatement.getId());                    }                    typeHandler.setParameter(ps, i + 1, value, parameterMapping.getJdbcType());                }            }        }    }        /**     * 根据数据库方言,生成特定的分页sql     * @param sql     * @param page     * @return     */    private String generatePageSql(String sql,Page page){        if(page!=null && !StringUtils.isEmpty(dialect)){            StringBuffer pageSql = new StringBuffer();            if("mysql".equals(dialect)){                pageSql.append(sql);                pageSql.append(" limit "+page.getCurrentResult()+","+page.getShowCount());            }else if("oracle".equals(dialect)){                String oracleSql="SELECT * FROM (SELECT A.*, ROWNUM RN FROM (";                pageSql.append(oracleSql);                pageSql.append(sql);                pageSql.append(") A) WHERE RN >"+page.getCurrentResult()+" AND RN <="+(page.getCurrentResult()+page.getShowCount()));            }            return pageSql.toString();        }else{            return sql;        }    }        public Object plugin(Object arg0) {        return Plugin.wrap(arg0, this);    }    public synchronized void setProperties(Properties p) {        dialect = p.getProperty("dialect");        if (StringUtils.isEmpty(dialect)) {            try {                logger.error("PagePlugin | setProperties:|description:PropertyException",new PropertyException("dialect property is not found!"));                throw new PropertyException("dialect property is not found!");            } catch (PropertyException e) {                logger.error("PagePlugin | setProperties:|description:dialect PropertyException",e);            }        }        pageSqlId = p.getProperty("pageSqlId");        if (StringUtils.isEmpty(pageSqlId)) {            try {                logger.error("PagePlugin | setProperties:|description:PropertyException",new PropertyException("pageSqlId property is not found!"));                throw new PropertyException("pageSqlId property is not found!");            } catch (PropertyException e) {                logger.error("PagePlugin | setProperties:|description:pageSqlId PropertyException",e);            }        }    }    }

ReflectHelper.java:反射的工具类

package com.test.util;import java.lang.reflect.Field;import org.apache.log4j.Logger;/**  * 说明:反射工具 * 创建人:yufeng * 修改时间 2017-10-12 * @version */public class ReflectHelper {/**日志*/    public static final Logger logger = Logger.getLogger(ReflectHelper.class);/** * 获取obj对象fieldName的Field * @param obj * @param fieldName * @return */public static Field getFieldByFieldName(Object obj, String fieldName) {for (Class<?> superClass = obj.getClass(); superClass != Object.class; superClass = superClass.getSuperclass()) {try {return superClass.getDeclaredField(fieldName);} catch (NoSuchFieldException e) {logger.debug("ReflectHelper | getFieldByFieldName:|getFieldByFieldName Exception",e);}}return null;}/** * 获取obj对象fieldName的属性 * @param obj * @param fieldName * @return * @throws SecurityException * @throws NoSuchFieldException * @throws IllegalArgumentException * @throws IllegalAccessException */public static Object getValueByFieldName(Object obj, String fieldName)throws SecurityException, NoSuchFieldException,IllegalArgumentException, IllegalAccessException {Field field = getFieldByFieldName(obj, fieldName);Object value = null;if(field!=null){if (field.isAccessible()) {value = field.get(obj);} else {field.setAccessible(true);value = field.get(obj);field.setAccessible(false);}}return value;}/** * 设置obj对象fieldName的属性 * @param obj * @param fieldName * @param value * @throws SecurityException * @throws NoSuchFieldException * @throws IllegalArgumentException * @throws IllegalAccessException */public static void setValueByFieldName(Object obj, String fieldName,Object value) throws SecurityException, NoSuchFieldException,IllegalArgumentException, IllegalAccessException {Field field = obj.getClass().getDeclaredField(fieldName);if (field.isAccessible()) {field.set(obj, value);} else {field.setAccessible(true);field.set(obj, value);field.setAccessible(false);}}}

最后修改我们原有的mybatis-config.xml配置文件

<?xml version="1.0" encoding="UTF-8"?>  <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD SQL Map Config 3.0//EN"        "http://mybatis.org/dtd/mybatis-3-config.dtd">  <configuration>            <settings>           <setting name="cacheEnabled" value="true" /><!-- 全局映射器启用缓存 -->          </settings>          <typeAliases><typeAlias type="com.test.util.PageData" alias="pd"/><!-- 分页 --><typeAlias type="com.test.entity.Page" alias="Page"/></typeAliases>  <plugins><plugin interceptor="com.test.util.PagePlugin"><property name="dialect" value="oracle"/><property name="pageSqlId" value=".*listPage.*"/></plugin></plugins></configuration>  

这里需要注意两点(下图红圈内):1.根据自己的业务选择自己的数据库。


2.在mapper.xml中定义的需要分页查询方法必须含有listpage这样的关键字,这样系统会对含listpage关键字的sql进行分页,如下图


二、完成后我们重新写一个查询用户的方法,分别写接口,实现类,mapper.xml,和controller调用,最后新建一个jsp页面展示即可

我这里直接在一起的userService中新增新的方法:

UserService.java:这里返回值和参数都定义Page类型,(一般我们需要返回list)但它里面包含了我们需要查询的list集合。

public Page list(Page page)throws Exception;


UserServiceImpl.java:实现类,主要将获取到的list据转化为Page,这里的PageData和map一致,是键值对类型

@SuppressWarnings("unchecked")@Overridepublic Page list(Page page) throws Exception {List<PageData> list = (List<PageData>)dao.findForList("UserMapper.selectUserlistPage", page);    page.setList(list);    return page;} 

userMapper.xml:编写sql,参数是page类型,返回值是pd即pagedata

<!-- 通过分页查询所有user -->    <select id="selectUserlistPage"  parameterType="page" resultType="pd">         select user_id,username, password,name,rights,last_login,ip,status,role_id from sys_app_user      </select> 

TestController.java 这里添加了三个方法:getList:获取集合数据,getPageData()和getRequest()方法目的是获取request请求的参数放入pagedata中。

@RequestMapping(value="list.do")          public ModelAndView getList(Page page){              ModelAndView mv=new ModelAndView();          PageData pd = this.getPageData();       List<PageData> pdlist=new ArrayList<PageData>();        try {          //查询人员列表            page.setPd(pd);            page.setShowCount(10);            page = userService.list(page);            //获取列表            pdlist = page.getList();            logger.info(" [TestController] [getList][success]");        } catch (Exception e) {          logger.error("[TestController] [getList][error]",e);          }          if(pdlist!=null&&pdlist.size()>0){               mv.addObject("list", pdlist);             }          mv.addObject("page", page);        mv.setViewName("listUser");        return mv;        }        /**得到pagedata对象     * @return     */    public PageData getPageData()    {        return new PageData(this.getRequest());    }        /**得到request对象     * @return     */    public HttpServletRequest getRequest()    {        HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder            .getRequestAttributes()).getRequest();        return request;    }

最后listUser.jsp:jsp中需要在展示和遍历list的外层包一个form表单,action则填写上面的getList()方法的请求,因为这里封装的分页通过点击的页面数通过提交表单来实现的。

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>        <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>        <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">        <html>            <head>                <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">                <title>test</title>          <style type="text/css">        ul{        list-style:none; /* 去掉ul前面的符号 */    margin: 0px; /* 与外界元素的距离为0 */    padding: 0px; /* 与内部元素的距离为0 */    width: auto; /* 宽度根据元素内容调整 */        }                ul li{        float:left; /* 向左漂移,将竖排变为横排 */        padding: 10px; /* 与内部元素的距离为0 */        }        </style>          </head>                        <body>     <form action="http://localhost:9795/test/list.do" method="post" name="Form" id="Form">    <div>          <c:forEach items="${list}" var="l" >              <h4>${l.USER_ID} | ${l.USERNAME} | ${l.NAME}</h4>        </c:forEach>      <!--翻页控件-->${page.pageStr}</div> </form></body> </html>    

最后结果:(没有优化css样式,实现了基本功能即可)点击页面的时候,注意上面地址栏参数的变化




下面贴出源码地址,源码中没有数据库脚本,自行准备数据库这块的数据

源码地址:http://download.csdn.net/download/yufeng005/10018398

原创粉丝点击