道德三黄五帝,功名夏侯商周。五霸七雄闹春秋,顷刻兴亡过手。清时几行名姓,北芒无数荒丘。前人播种后人收,说什么原创与否。
今天和大家分享一下springmvc+mybatis+easyui的分页实现。springmvc,mybatis的优缺点不做太多敖述大家都比较了解了,ssm框架整合的例子网上也有很多了,为什么还要写这篇文章那,主要是觉得大多过于零散配置方式又是千差万别,总结一下本文希望对遇到此问题的人有所帮助,前人播种后人收。当然程序开发没有觉得正确,谁也说不出一个正确的实现第N行代码是什么,由于水平有限,难免有纰漏之处,希望大家多多指点。
正文开始之前和大家说说为什么选择easyui,个人从13年开始管理系统前端技术使用easyui非常多,easyui很对得起easy这个词,上手很容易,浏览器兼容性优良,文档内容完善且有中文,datagrid请求数据参数简单方便。
本文应用到技术相关版本如下:
技术 |
版本 |
Spring |
4.0.2.RELEASE |
Mybatis |
3.2.6 |
jquery |
jquery -1.11.1.js |
EasyUI |
1.4 |
Maven |
2.5 |
技术思路:
1. 用Springmvc构建 Web应用程序的全功能 MVC 模块
2. ORM框架选用mybatis,mybatis相对ibatis增加了mapper功能,大大简化了开发的工作量,但是spring和mybatis整合时没有了类似整合ibatis时的queryForList(String
statementName,Object parameterObject, int skipResults, intmaxResults)方法,对于数据范围的控制需要借助mybatis的Interceptor实现。
3. 结合思路2中提到的特点,需要定义StatementHandler类型的Interceptor,同时本实例将分页相关的查询参数封装为PageUtil类。在该拦截器中判断如果参数类型为PageUtil则需要对sql进行处理,将其构造为分页模式的sql,oracle可用利用rownum,mysql利用limit函数。同时我们还可以在拦截器中获取到查询数据的总记录数,这样是相对于spring整合ibatis的又一方便之处。
4. PageUtil中封装分页相关的参数。由于easyui在请求时使用rows(Int类型)表示每页显示的记录数,page表示当前页,而响应时需要使用rows(List类型)表示查询结果,total表示记录数,所以PageUtil中的setRows,getRows方法不能简单的依靠IDE自动生成了。同时为了方便将PageUtil作为了控制层返回值,所以PageUtil类还需注意对其转换为符合easyuidatagrid标准的json格式时,不必要参数的控制。
5. Spring自动扫描mybatis的xml文件,自动扫描mapper类,service层控制事务。
程序代码如下:
1. Maven pom.xml文件内容如下
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.asiainfo</groupId> <artifactId>cbar</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <name>bomcreport2</name> <properties> <!-- spring版本号 --> <spring.version>4.0.2.RELEASE</spring.version> <!-- mybatis版本号 --> <mybatis.version>3.2.6</mybatis.version> <!-- log4j日志文件管理包版本 --> <slf4j.version>1.7.7</slf4j.version> <log4j.version>1.2.17</log4j.version> </properties> <dependencies> <dependency> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-resources-plugin</artifactId> <version>2.4.1</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <!-- 表示开发的时候引入,发布的时候不会加载此包 --> <scope>test</scope> </dependency> <!-- spring核心包 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-oxm</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>${spring.version}</version> <type>jar</type> <scope>compile</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> </dependency> <!-- mybatis核心包 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <!-- mybatis/spring包 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.2</version> </dependency> <!-- 导入dbcp的jar包,用来在applicationContext.xml中配置数据库 --> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.2.2</version> </dependency> <!-- JSTL标签类 --> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- 日志文件管理包 --> <!-- log start --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${slf4j.version}</version> </dependency> <!-- log end --> <!-- 上传组件包 --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency> <dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>1.9</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.0.1</version> <scope>provided</scope> </dependency> <dependency> <groupId>commons-beanutils</groupId> <artifactId>commons-beanutils</artifactId> <version>1.9.2</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.5.0</version> </dependency> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.13</version> </dependency> </dependencies> <build> <defaultGoal>compile</defaultGoal> <sourceDirectory>src/main/java</sourceDirectory> <resources> <resource> <directory>src/main/java</directory> <excludes> <exclude>**/*.java</exclude> </excludes> </resource> </resources> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>2.3.2</version> <configuration> <source>1.6</source> <target>1.6</target> </configuration> </plugin> <plugin> <artifactId>maven-war-plugin</artifactId> <version>2.2</version> <configuration> <warSourceDirectory>${basedir}/WebRoot</warSourceDirectory> <version>3.0</version> <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> </plugin> </plugins> </build> </project>
2. spring-config.xml文件
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <context:annotation-config /> <!-- 自动扫描com.asia包先相关类 --> <context:component-scan base-package="com.asia" > <!-- <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> --> </context:component-scan> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="classpath:base.properties" /> </bean> <!-- 定义数据源 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${driverClassName}" /> <property name="url" value="${DBTUrl}" /> <property name="username" value="${DBUser}" /> <property name="password" value="${DBPassword}" /> <!-- 初始化连接大小 --> <property name="initialSize" value="${initialSize}"></property> <!-- 连接池最大数量 --> <property name="maxActive" value="${maxActive}"></property> <!-- 连接池最大空闲 --> <property name="maxIdle" value="${maxIdle}"></property> <!-- 连接池最小空闲 --> <property name="minIdle" value="${minIdle}"></property> <!-- 获取连接最大等待时间 --> <property name="maxWait" value="${maxWait}"></property> </bean> <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- 自动扫描mapping.xml文件 --> <property name="mapperLocations" value="classpath:mapping/*.xml"></property> <property name="plugins"> <array> <bean class="com.asia.util.mybatispage.PageInterceptor"> <property name="properties"> <value> databaseType=oracle </value> </property> </bean> </array> </property> </bean> <!-- DAO接口所在包名,Spring会自动查找其下的类 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.asia.*.mapper" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> </bean> <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <tx:advice id="userTxAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="delete*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception" no-rollback-for="java.lang.RuntimeException"/> <tx:method name="add*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception" /> <tx:method name="insert*" propagation="REQUIRES_NEW" read-only="false" rollback-for="java.lang.Exception" /> <tx:method name="update*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception" /> <tx:method name="modify*" propagation="REQUIRES_NEW" read-only="false" rollback-for="java.lang.Exception" /> <tx:method name="find*" propagation="SUPPORTS"/> <tx:method name="get*" propagation="SUPPORTS"/> <tx:method name="select*" propagation="SUPPORTS"/> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut id="pc" expression="execution(public * com.asia.*.service.*.*(..))" /> <!-- 把事务控制在Service层 --> <aop:advisor pointcut-ref="pc" advice-ref="userTxAdvice" /> </aop:config> </beans>
3. spring-servlet.xml文件
<?xml version="1.0" encoding="UTF-8"?> <!-- <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:util="http://www.springframework.org/schema/util" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation=" http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> --> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> <mvc:annotation-driven /> <!-- <context:annotation-config /> --> <context:component-scan base-package="com.asia.*.controller"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" /></context:component-scan> <!-- <context:component-scan base-package="com.asia.*.controller" /> --> <!-- <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/" p:suffix=".jsp" /> --> <!-- <bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> </list> </property> </bean> 启动Spring MVC的注解功能,完成请求和注解POJO的映射 <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <ref bean="mappingJacksonHttpMessageConverter" />json转换器 </list> </property> </bean> --> <!-- <bean id="defaultViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:order="3"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> <property name="contentType" value="text/html" /> <property name="prefix" value="/" /> <property name="suffix" value=".jsp" /> </bean> --> <!-- <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver"> <property name="mediaTypes"> <map> <entry key="atom" value="application/atom+xml"/> <entry key="html" value="text/html"/> <entry key="json" value="application/json"/> </map> </property> <property name="viewResolvers"> <list> <bean class="org.springframework.web.servlet.view.BeanNameViewResolver"/> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/"/> <property name="suffix" value=".jsp"/> </bean> </list> </property> <property name="defaultViews"> <list> <bean class="org.springframework.web.servlet.view.json.MappingJackson2JsonView"/> </list> </property> </bean> --> </beans>
4. web.xml文件
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>cbar</display-name> <context-param> <param-name>contextConfigLocation</param-name> <param-value> classpath:spring-config.xml </param-value> </context-param> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> <filter> <filter-name>Encoding</filter-name> <filter-class> org.springframework.web.filter.CharacterEncodingFilter </filter-class> <init-param> <param-name>encoding</param-name> <param-value>utf8</param-value> </init-param> </filter> <filter-mapping> <filter-name>Encoding</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <servlet> <servlet-name>spring</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet </servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-servlet.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>spring</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <error-page> <exception-type>java.lang.Exception</exception-type> <location>/error.jsp</location> </error-page> <welcome-file-list> <welcome-file>report/report.jsp</welcome-file> </welcome-file-list> </web-app>
5. PageUtil类
package com.asia.util.mybatispage; import java.util.List; import com.fasterxml.jackson.annotation.JsonIgnore; public class PageUtil { private int rows; private int total; private int page; private String orderStr; private String sort; private String order; private Object queryObj; private List<?> data; @JsonIgnore public String getOrderStr() { orderStr = ""; if (!org.springframework.util.StringUtils.isEmpty(order)) { String[] orders = order.split(","); String[] sorts = sort.split(","); for (int i = 0; i < sorts.length; i++) { orderStr += sorts[i] + " " + orders[i] + ", "; } orderStr = orderStr.endsWith(", ") ? orderStr.substring(0, orderStr.length() - 2) : orderStr; } return orderStr; } @JsonIgnore public int getPageSize() { return rows; } public List<?> getRows(){ return data; } public void setRows(int rows) { this.rows = rows; } public int getTotal() { return total; } public void setTotal(int total) { this.total = total; } @JsonIgnore public int getPage() { return page; } public void setPage(int page) { this.page = page; } @JsonIgnore public String getSort() { return sort; } public void setSort(String sort) { this.sort = sort; } @JsonIgnore public String getOrder() { return order; } public void setOrder(String order) { this.order = order; } @JsonIgnore public Object getQueryObj() { return queryObj; } public void setQueryObj(Object queryObj) { this.queryObj = queryObj; } public void setOrderStr(String orderStr) { this.orderStr = orderStr; } public void setData(List<?> data) { this.data = data; } @Override public String toString() { return "PageUtil [rows=" + rows + ", total=" + total + ", page=" + page + ", orderStr=" + orderStr + ", sort=" + sort + ", order=" + order + ", queryObj=" + queryObj + ", data=" + data + "]"; } }
6. Mybatis过滤器PageInterceptor类
package com.asia.util.mybatispage; 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 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.mapping.ParameterMapping; 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.scripting.defaults.DefaultParameterHandler; import com.asia.util.ReflectUtil; /** * 分页拦截器 * * @author SCY * * @CreateTime 2016年2月19日下午2:21:26 * * @Vsersion 1.0 */ @Intercepts({@Signature(method = "prepare", type = StatementHandler.class, args = {Connection.class})} ) public class PageInterceptor implements Interceptor { private String databaseType; @Override public Object intercept(Invocation invocation) throws Throwable { final RoutingStatementHandler handler = (RoutingStatementHandler) invocation.getTarget(); final StatementHandler delegate = (StatementHandler) ReflectUtil.getFieldValue(handler, "delegate"); final BoundSql boundSql = delegate.getBoundSql(); final Object obj = boundSql.getParameterObject(); //如果参数类型为自定义的PageUtil类型则执行分页处理 if (obj instanceof PageUtil) { final PageUtil page = (PageUtil) obj; MappedStatement mappedStatement = (MappedStatement) ReflectUtil.getFieldValue(delegate, "mappedStatement"); Connection connection = (Connection) invocation.getArgs()[0]; final String sql = boundSql.getSql();//获取原sql final String pageSql = this.getPageSql(page, sql);//转换为分页SQL System.out.println(pageSql); //获取总记录数 int rowCount = getRowCount(page, mappedStatement, connection); System.out.println("rowCount:"+rowCount); page.setTotal(rowCount); ReflectUtil.setFieldValue(boundSql, "sql", pageSql); } return invocation.proceed(); } private String getCountSql(String sql) { return "select count(*) from (" + sql+") a"; } /** * 生成分页数据sql * @param page * @param sql * @return */ private String getPageSql(PageUtil page, String sql) { final StringBuffer sqlBuffer = new StringBuffer(sql); if ("mysql".equalsIgnoreCase(databaseType)) { return getMysqlPageSql(page, sqlBuffer); } else if ("oracle".equalsIgnoreCase(databaseType)) { return getOraclePageSql(page, sqlBuffer); } return sqlBuffer.toString(); } /** * 生产mysql数据分页sql * @param page * @param sqlBuffer * @return */ private String getMysqlPageSql(PageUtil page, StringBuffer sqlBuffer) { int offset = (page.getPage() - 1) * page.getPageSize() ; sqlBuffer.append(" limit ").append(offset).append(",").append(page.getPageSize()); return sqlBuffer.toString(); } /** * 获取Oracle数据库的分页查询语句 */ private String getOraclePageSql(PageUtil page, StringBuffer sqlBuffer) { System.out.println(page); int offset = (page.getPage() - 1) * page.getPageSize() + 1; System.out.println(offset); sqlBuffer.insert(0, "select u.*, rownum r from (").append(") u where rownum < ") .append(offset + page.getPageSize()); sqlBuffer.insert(0, "select * from (").append(") where r >= ").append(offset); return sqlBuffer.toString(); } /** * 获取总数据量 * @param page * @param mappedStatement * @param connection * @return * @throws SQLException */ private int getRowCount(PageUtil page, MappedStatement mappedStatement, Connection connection) throws SQLException { int totalRecord = 0; BoundSql boundSql = mappedStatement.getBoundSql(page); String sql = boundSql.getSql(); String countSql = this.getCountSql(sql); List<ParameterMapping> parameterMappings = boundSql.getParameterMappings(); BoundSql countBoundSql = new BoundSql(mappedStatement.getConfiguration(), countSql, parameterMappings, page); ParameterHandler parameterHandler = new DefaultParameterHandler(mappedStatement, page, countBoundSql); PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = connection.prepareStatement(countSql); parameterHandler.setParameters(pstmt); rs = pstmt.executeQuery(); if (rs.next()) { totalRecord = rs.getInt(1); } } finally { try { if (rs != null) rs.close(); } finally{ if (pstmt != null) pstmt.close(); } } return totalRecord; } @Override public Object plugin(Object target) { return Plugin.wrap(target, this); } @Override public void setProperties(Properties properties) { this.databaseType = properties.getProperty("databaseType"); } }
以下相关内容为样例程序代码,已简单的用户信息管理为例
7. UserInfo类
package com.asia.demo.bean; public class UserInfo { private int id; private String uname; private String birthday; private String sex; private String address; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUname() { return uname; } public void setUname(String uname) { this.uname = uname; } public String getBirthday() { return birthday; } public void setBirthday(String birthday) { this.birthday = birthday; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Override public String toString() { return "UserInfo [id=" + id + ", uname=" + uname + ", birthday=" + birthday + ", sex=" + sex + ", address=" + address + "]"; } }
8. UserController类
package com.asia.demo.controller; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.asia.demo.bean.UserInfo; import com.asia.demo.service.IUserService; import com.asia.util.mybatispage.PageUtil; @Controller @RequestMapping("/user") public class UserController { @Resource private IUserService userService; @RequestMapping(value="/searchUser") public @ResponseBody PageUtil search(UserInfo uesrInfo, PageUtil pu) { pu.setQueryObj(uesrInfo);//设置查询条件 List<UserInfo> data= userService.searchUser(pu); pu.setData(data);//设置反馈结果 return pu; } public IUserService getUserService() { return userService; } public void setUserService(IUserService userService) { this.userService = userService; } }
9. UserInfoMapper类
package com.asia.demo.mapper; import java.util.List; import org.springframework.stereotype.Repository; import com.asia.demo.bean.UserInfo; import com.asia.util.mybatispage.PageUtil; @Repository("userInfoMapper") public interface UserInfoMapper { public List<UserInfo> queryUser(); public List<UserInfo> searchUser(PageUtil spu); }
10. Mybatis配置文件UserMapper.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.asia.demo.mapper.UserInfoMapper"> <!-- 查询所有记录 --> <select id="queryUser" resultType="com.asia.demo.bean.UserInfo"> select id, uname, birthday, sex, address from userinfo </select> <select id="searchUser" resultType="com.asia.demo.bean.UserInfo" parameterType="com.asia.util.mybatispage.PageUtil"> select id, uname, birthday, sex, address from userinfo <where> <if test="queryObj.uname != null"> AND uname = #{queryObj.uname} </if> <if test="queryObj.sex != null "> AND sex = #{queryObj.sex} </if> </where> </select> </mapper>
11. UserServiceImpl类,接口代码省略
package com.asia.demo.service.impl; import java.util.List; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.asia.demo.bean.UserInfo; import com.asia.demo.mapper.UserInfoMapper; import com.asia.demo.service.IUserService; import com.asia.util.mybatispage.PageUtil; @Service("userServiceImpl") public class UserServiceImpl implements IUserService { @Resource private UserInfoMapper userInfoMapper; @Override public List<UserInfo> queryUser() { return userInfoMapper.queryUser(); } @Override public List<UserInfo> searchUser(PageUtil spu) { return userInfoMapper.searchUser(spu); } public UserInfoMapper getUserInfoMapper() { return userInfoMapper; } public void setUserInfoMapper(UserInfoMapper userInfoMapper) { this.userInfoMapper = userInfoMapper; } }
12. UserList.jsp
<%@ page contentType="text/html; charset=UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>查询</title> <meta http-equiv="pragma" content="no-cache" /> <meta http-equiv="cache-control" content="no-cache" /> <meta http-equiv="expires" content="0" /> <link type="text/css" href="<%=path %>/common/jquery/easyui/css/default/easyui.css" rel="stylesheet" charset='UTF-8'> <link type="text/css" href="<%=path %>/common/jquery/easyui/css/icon.css" rel="stylesheet" charset='UTF-8'> <script type="text/javascript"> var basePath="<%=path %>"; </script> <script language="javascript" src="<%=path %>/common/jquery/core/jquery-1.11.1.js"></script> <script language="javascript" src="<%=path %>/common/jquery/easyui/js/jquery.easyui.min.js"></script> <script language="javascript" src="<%=path %>/demo/js/UserList.js"></script> </head> <body class="body"> <table width="98%"> <tr> <td> <table id="userInfo" title=""> </table> </td> </tr> </table> </body> </html>
13. UserList.js
/** * 设置列 * * @return */ function getColumns() { return [[ {field:'id', title:"编号", checkbox:true}, {field:'user', title:"用户名", halign:'center', align:'center',sortable:true, width:278}, {field:'birthday', title:"出生日期", halign:'center', align:'center', sortable:true, width:150}, {field:'sex', title:"性别", halign:'center', align:'center',sortable:true, width:80}, /* {field:'address', title:"状态", halign:'center', align:'center',sortable:true, width:80, formatter: function(value,row,index){ return taskState.get(value); } },*/ {field:'address', title:"地址", halign:'center', align:'center',sortable:true, width:180} ]]; } /** * 初始化页面 */ jQuery(function() { var gridParam = { rownumbers:true, loadMsg : "数据加载中", pagination : true, multiSort : true, pageSize : 10, pageList : [ 10, 20, 30, 50, 100 ], striped : true, columns : getColumns(), //queryParams : queryParams, url:basePath+"/user/searchUser.do", collapsible : true, singleSelect : true, idField : "id" // 支持跨页选择 }; $('#userInfo').datagrid(gridParam); $('#userInfo').datagrid("getPager").pagination( { pageSize : 10, displayMsg : '当前数据范围 {from} 到 {to} ,共 {total} 条记录', beforePageText : '当前', afterPageText : ' ,共 {pages}页' }); });
欢迎大家拍砖