环境 WIN8 , Eclipse (Juno) , Maven 3.0.4 , Tomcat 7 为了方便测试分页功能,前台使用了jquery的Jqgrid插件。 1.建立项目 1.使用Eclipse新建一个Maven Project,Archetype选择 maven-archetype-webapp。 2.新建的项目中默认只有一个source folder - src/main/resources ,添加另外三个source folder来完善Maven的标准目录结构。 3.配置依赖 <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/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>jo.geun</groupId> <artifactId>sampleProj</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>sampleProj Maven Webapp</name> <url>http://maven.apache.org</url> <properties> <spring.version>3.1.3.RELEASE</spring.version> </properties> <dependencies> <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-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.1.1</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.1.1</version> </dependency> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency> <dependency> <groupId>com.oracle</groupId> <artifactId>ojdbc6</artifactId> <version>11.2.0.3.0</version> </dependency> <dependency> <groupId>cglib</groupId> <artifactId>cglib</artifactId> <version>2.2.2</version> </dependency> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-core-asl</artifactId> <version>1.9.11</version> </dependency> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.11</version> </dependency> </dependencies> <build> <finalName>sampleProj</finalName> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.5.1</version> <configuration> <source>1.6</source> <target>1.6</target> </configuration> </plugin> </plugins> </build> </project> 需注意的是,因为Oracle做了些license的限制,Maven Central不提供Oracle的JDBC Driver的下载。我们只能手动下载JAR包(你也可以在Oracle DB或Client的安装目录中找到它),再用install命令注册到本地仓库中。 E:\>mvn install:install-file -Dfile=E:\instantclient_11_2\ojdbc6.jar -DgroupId=com.oracle -DartifactId=ojdbc6 -Dversion=11.2.0.3.0 -Dpackaging=jar 3.web.xml的配置 <?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <display-name>Sample Web Application</display-name> <!-- The definition of the Root Spring Container shared by all Servlets and Filters --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring/root-context.xml</param-value> </context-param> <!-- Creates the Spring Container shared by all Servlets and Filters --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- Processes application requests --> <servlet> <servlet-name>appServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring/servlet-context.xml</param-value> </init-param> <load-on-startup>0</load-on-startup> </servlet> <servlet-mapping> <servlet-name>appServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app> 这里简简单单的说明一下吧。。 <context-param/> 节点配置contextConfigLocation属性是为了让ContextLoaderListener找到Spring上下文的位置并加载它,如果不指定contextConfigLocation,ContextLoaderListener会到/WEB-INF/目录下找applicationContext.xml来加载。 <listener/> 节点上配了ContextLoaderListener。它实现了ServletContextListener接口,所以web server启动时ContextLoaderListener能读取到ServletContext,也就能通过<context-param/>指定的Spring上下文的路径来找到上下文并加载它。 当然,如果你不需要Spring来管理你的Bean,可以去掉上面两个节点。 <servlet/>和<servlet-mapping/>两个节点其实也不用多说,就是告诉容器匹配<url-pattern/>的请求都让Spring的 DispatcherServlet(就是一个Servlet,继承自HttpServlet)来处理。而它会把请求分发给其他控制器。详见Spring reference 16章 。 在WEB-INF目录下创建一个叫Spring的文件夹,上面指定的Spring的两个配置文件会放到这个文件夹内。 4.配置Spring mvc 在web.xml的<servlet/>节点中我们指定了servlet-context.xml。这里可以配拦截器还有视图解析器等,也可以配multipartResolver来实现文件上传功能。 <?xml version="1.0" encoding="UTF-8"?> <beans:beans xmlns="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-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"> <!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure --> <!-- Enables the Spring MVC @Controller programming model --> <annotation-driven /> <!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory --> <resources mapping="/resources/**" location="/resources/" /> <!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory --> <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <beans:property name="prefix" value="/WEB-INF/pages/" /> <beans:property name="suffix" value=".jsp" /> </beans:bean> <context:component-scan base-package="jo.geun.controller" /> </beans:beans> 这儿需要注意的是<context:component-scan/>节点。看到很多人问起让Spring来管理事务时候,事务为什么会不起作用,其中也有在这儿犯错的。。 通常我们会做分层开发,在这个小例子中也分了controller、service 、 dao 三层,由service层来管理事务。 如果在这个servlet context里面把service层也给scan了,service Bean就会被提前实例化,Spring的事务就没法控制事务对象了。所以一定要让这个扫描器过滤掉service层的扫描。 上面因为package的结构简单,就直接指定了controller层,其实也可以换种方式来写 <context:component-scan base-package="com.geun"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service" /> </context:component-scan> 用上面的方式会过滤掉所有带@Service注解的类,也可以用正则表达式或AspectJ类型的表达式,具体的参阅官方文档。 5.root-context.xml 这儿主要包含了数据源及事务的配置,还有dao、service层bean的定义。 <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" 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-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <!-- Connection Info --> <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" /> <property name="url" value="jdbc:oracle:thin:@*******:1521:**" /> <property name="username" value="**" /> <property name="password" value="**" /> <!-- Connection Pooling DBCP --> <property name="initialSize" value="5" /> <property name="maxActive" value="100" /> <property name="maxIdle" value="30" /> <property name="maxWait" value="1000" /> <property name="poolPreparedStatements" value="true" /> <property name="defaultAutoCommit" value="false" /> </bean> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <tx:annotation-driven transaction-manager="transactionManager" /> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="configLocation" value="WEB-INF/mybatis/mybatis-conf.xml" /> </bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="jo.geun.dao;" /> </bean> <context:component-scan base-package="jo.geun.service" /> </beans> MapperScannerConfigurer会寻找指定包下的Mapper并自动将它们注册到到MapperFactoryBean代理工厂,这个代理工厂可以让你的mapper interface直接注入到其他bean中,而你完全不需要实现这个接口。不嫌累,也可以一个一个的注册Mapper接口,如下。 <bean id="sampleMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"> <property name="mapperInterface" value="jo.geun.dao.SampleMapper" /> <property name="sqlSessionFactory" ref="sqlSessionFactory" /> </bean> 6.mybatis-conf.xml WEB-INF目录下创建文件夹mybatis,来放置它。 <?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> <settings> <setting name="cacheEnabled" value="true" /> <setting name="lazyLoadingEnabled" value="true" /> <setting name="aggressiveLazyLoading" value="false" /> <setting name="multipleResultSetsEnabled" value="true" /> <setting name="useColumnLabel" value="true" /> <setting name="autoMappingBehavior" value="FULL" /> <setting name="defaultExecutorType" value="SIMPLE" /> <setting name="defaultStatementTimeout" value="25000" /> </settings> <plugins> <plugin interceptor="jo.geun.utility.PagePlugin"> <property name="dialect" value="oracle" /> <property name="pageSqlId" value=".*ListPage.*" /> </plugin> </plugins> </configuration> 如果mapper interface和mapper xml取一样的文件名,放到同一个包下就不用另配<mappers/>节点来告诉映射文件的位置了。 ibatis更名为mybatis以后加入了plugin功能,可以用它拦截执行语句的调用并扩展核心功能(Executer,StatementHandler 等)。这里我们用它来实现分页功能。 在之前在src/main/java下建5个package,附图 7.通过Mybatis的plugin做分页功能 utility包下新建一个POJO类。 package jo.geun.utility; import java.io.Serializable; public class PageInfo implements Serializable { private static final long serialVersionUID = 587754556498974978L; private int showCount = 10; private int totalPage; private int totalResult; private int currentPage; private int currentResult; private String sortField; private String order; //omit getter/setter methods .... } 反射辅助类 package jo.geun.utility; import java.lang.reflect.Field; public class ReflectHelper { 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) { } } 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); } } } 拦截器 ,通过拦截StatementHandler的prepare方法来实现分页 package jo.geun.utility; 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.Map; import java.util.Properties; import javax.xml.bind.PropertyException; import org.apache.ibatis.builder.xml.dynamic.ForEachSqlNode; 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.session.Configuration; import org.apache.ibatis.type.TypeHandler; import org.apache.ibatis.type.TypeHandlerRegistry; @Intercepts({ @Signature(type = StatementHandler.class, method = "prepare", args = { Connection.class }) }) public class PagePlugin implements Interceptor { private static String dialect = ""; private static String pageSqlId = ""; @SuppressWarnings("unchecked") 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)) { BoundSql boundSql = delegate.getBoundSql(); Object parameterObject = boundSql.getParameterObject(); 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 + ") "; 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(); PageInfo page = null; if (parameterObject instanceof PageInfo) { page = (PageInfo) parameterObject; page.setTotalResult(count); } else if(parameterObject instanceof Map){ Map<String, Object> map = (Map<String, Object>)parameterObject; page = (PageInfo)map.get("page"); if(page == null) page = new PageInfo(); page.setTotalResult(count); }else { Field pageField = ReflectHelper.getFieldByFieldName( parameterObject, "page"); if (pageField != null) { page = (PageInfo) ReflectHelper.getValueByFieldName( parameterObject, "page"); if (page == null) page = new PageInfo(); page.setTotalResult(count); ReflectHelper.setValueByFieldName(parameterObject, "page", page); } else { throw new NoSuchFieldException(parameterObject .getClass().getName()); } } String pageSql = generatePageSql(sql, page); ReflectHelper.setValueByFieldName(boundSql, "sql", pageSql); } } } return ivk.proceed(); } /** * 瀵筍QL鍙傛暟(?)璁惧�,鍙傝�org.apache.ibatis.executor.parameter. * DefaultParameterHandler * * @param ps * @param mappedStatement * @param boundSql * @param parameterObject * @throws SQLException */ 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()); } } } } /** * 鏍规嵁鏁版嵁搴撴柟瑷�紝鐢熸垚鐗瑰畾鐨勫垎椤祍ql * * @param sql * @param page * @return */ private String generatePageSql(String sql, PageInfo page) { if (page != null && (dialect !=null || !dialect.equals(""))) { StringBuffer pageSql = new StringBuffer(); if ("mysql".equals(dialect)) { pageSql.append(sql); pageSql.append(" limit " + page.getCurrentResult() + "," + page.getShowCount()); } else if ("oracle".equals(dialect)) { pageSql.append("select * from (select tmp_tb.*,ROWNUM row_id from ("); pageSql.append(sql); pageSql.append(") tmp_tb where ROWNUM<="); pageSql.append(page.getCurrentResult() + page.getShowCount()); pageSql.append(") where row_id>"); pageSql.append(page.getCurrentResult()); } return pageSql.toString(); } else { return sql; } } public Object plugin(Object arg0) { // TODO Auto-generated method stub return Plugin.wrap(arg0, this); } public void setProperties(Properties p) { dialect = p.getProperty("dialect"); if (dialect ==null || dialect.equals("")) { try { throw new PropertyException("dialect property is not found!"); } catch (PropertyException e) { // TODO Auto-generated catch block e.printStackTrace(); } } pageSqlId = p.getProperty("pageSqlId"); if (dialect ==null || dialect.equals("")) { try { throw new PropertyException("pageSqlId property is not found!"); } catch (PropertyException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } 看代码应该最容易理解吧,BoundSql 对象的sql字段是mybatis最终会执行的SQL语句,上面就是用处理过的sql替换原Sql。 8.dao层(映射文件及接口)的编写 在dao包下建立 SampleMapper.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="jo.geun.dao.SampleMapper"> <select id="getMemberListPage" resultType="jo.geun.entity.Member"> select * from member_sap </select> </mapper> SampleMapper.java package jo.geun.dao; import java.util.List; import jo.geun.entity.Member; import jo.geun.utility.PageInfo; import org.apache.ibatis.annotations.Param; public interface SampleMapper { List<Member> getMemberListPage(@Param("page") PageInfo page); } 这儿只有一个select语句,我们用它来测试分页功能。 Member只弄了两个字段,如下。 package jo.geun.entity; import java.io.Serializable; public class Member implements Serializable { private static final long serialVersionUID = -3138863613422043759L; private String sabun = ""; private String registno = ""; //omit getter/setter } 9.service层的编写 package jo.geun.service; import java.util.List; import jo.geun.dao.SampleMapper; import jo.geun.entity.Member; import jo.geun.utility.PageInfo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class SampleService { @Autowired SampleMapper sampleMapper; public List<Member> getMemberList(PageInfo pageInfo){ return sampleMapper.getMemberListPage(pageInfo); } } @Service(下面还会有一个@Controller)注解是用来标注一个Bean的,spring会根据我们在上面配的 component-scan节点来扫描注册这些bean。它会根据类名实例化一个首字母为小写的bean,也可以给它一个参数来自定义bean id,如@Service("这样")。他的作用跟Spring配置文件里配一个普通bean是一样的。 <bean id="sampleService" class="jo.geun.service.SampleService" /> @Autowired 可以对类成员变量、方法及构造函数进行标注,实现bean的自动装配(在Spring容器中找一个跟相应字段名一样的bean id来装配)。 10.Controller 在编写Controller以前,我们在写一个POJO叫JsonResponse。其实这个类跟json没什么关系。我们在前端会用jquery的 jqgrid插件,它需要一个Json格式的数据源,我们就结合这个JsonResponse类、spring web以及jackson lib来格式化Json数据。 package jo.geun.utility; import java.io.Serializable; import java.util.List; public class JsonResponse<T extends Serializable> { /** * Current page */ private int page; /** * Total pages */ private int total; /** * Total number of records */ private int records; /** * Contains the actual data */ private List<T> rows; public JsonResponse() { } public JsonResponse(List<T> rows, PageInfo page) { this.rows = rows; this.total = page.getTotalPage(); this.records = page.getTotalResult(); this.page = page.getCurrentPage(); } //omit getter/setter methods .... } SampleController package jo.geun.controller; import java.util.List; import jo.geun.entity.Member; import jo.geun.service.SampleService; import jo.geun.utility.JsonResponse; import jo.geun.utility.PageInfo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller public class SampleController { @Autowired SampleService sampleService; @RequestMapping("/home") public String home() { return "home"; } @ResponseBody @RequestMapping("/data") public JsonResponse<Member> getData(PageInfo pageInfo) { List<Member> list = sampleService.getMemberList(pageInfo); JsonResponse<Member> response = new JsonResponse<Member>(list, pageInfo); return response; } } 11.编写jsp 先下载 jquery,jquery ui,jqgrid 。然后webapp目录下建resources文件夹来放他们(目录结构看下面jsp里的引用吧。。)。 WEB-INF/pages目录下建home.jsp <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <link rel="stylesheet" type="text/css" media="screen" href="<c:url value="/resources/styles/jquery-ui-1.9.1.custom.min.css"/>" /> <link rel="stylesheet" type="text/css" media="screen" href="<c:url value="/resources/styles/ui.jqgrid.css"/>" /> <script src="<c:url value="/resources/js/jquery-1.8.2.js"/>" type="text/javascript"></script> <script type="text/javascript" src="<c:url value="/resources/js/jquery-ui-1.9.1.custom.min.js"/>"></script> <script src="<c:url value="/resources/js/jquery.jqGrid.min.js"/>" type="text/javascript"></script> <script src="<c:url value="/resources/js/grid.locale-en.js"/>" type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function() { $("#grid").jqGrid({ url : 'data', datatype : 'json', mtype : 'POST', colNames : [ 'sabun', 'registno' ], colModel : [ { name : 'sabun', index : 'sabun', width : 5 }, { name : 'registno', index : 'registno', width : 5 } ], rowList : [ 10, 20, 40, 60 ], pager : '#pager', sortname : '', sortorder : "desc", height : 240, width : 480, rowNum : 10, caption : "Sample App ", pgtext : "当前: {0} /{1}", recordtext : "View {0} - {1} of {2}", emptyrecords : "Empty records", rownumbers : true, viewrecords : true, scrollrows : true, loadonce : false, loadComplete : function() { }, prmNames : { page : 'currentPage', rows : 'showCount', sort : 'sortField', order : 'order' }, jsonReader : { root : "rows", page : "page", total : "total", records : "records", repeatitems : false, cell : "cell", id : "id" } }).navGrid("#pager", { edit : false, add : false, del : false, search : false }); }); </script> <title>Insert title here</title> </head> <body> <table id="grid"></table> <div id="pager"></div> </body> </html>
相关推荐
"spring+spring mvc+mybatis框架整合实现超市货物管理系统"是一个涵盖后端开发基础技能的项目,涉及了JavaEE的多个层面,从Web层的路由处理,到业务逻辑的实现,再到数据库操作,以及用户认证和分页显示等实用功能。...
但是,在参考写的同时也发现有很多地方都不解不能直接用的问题,导致实际使用的过程中经常会出错,参考原来做的项目,以及网上的资料,整理了一个比较简单的自己理解的spring+spring mvc+mybatis+mysql实现的分页的...
1. **配置Spring**:首先,需要创建一个Spring的配置文件,例如`applicationContext.xml`,在这个文件中定义Bean,如数据源、事务管理器以及MyBatis的SqlSessionFactory。 2. **配置SpringMVC**:接着,配置...
在本项目中,"Spring+SpringMVC+Mybatis+Maven+bootstrap+ajax+jQuery整合开发简单的员工后台管理系统",我们看到一个基于Java技术栈的Web应用开发实例。这个系统利用了多个核心技术来构建一个功能完备的员工管理...
Spring+Springmvc+Mybatis+Shiro+Mybatis物理分页整合,里面没有多的测试代码,自己测试,有问题可以留言,亲测可用,我已经用到我项目,关于里面的Mybatis的分页功能是网上某个哥们的。我加入了MSSQL的部分,分页...
【项目原型】spring+spring mvc+mybatis+shiro+maven+bootstrap+ajax+json+分页+逆向工程 包含现在最流行的技术框架,快速部署各种应用,加入shiro权限框架,安全,美观,你值得拥有
通过学习和分析这个demo,开发者可以深入理解Spring、SpringMVC和MyBatis的整合方式,以及如何利用Mybatis-Paginator实现高效便捷的分页功能。这对于提升Java Web开发技能和理解企业级应用架构具有重要意义。
Spring + Spring MVC + Mybatis + Maven搭建多模块的web项目 里面包含了很多配置方面的注释,方便日后维护。 采用了通用Mapper封装了单表的增删改查操作 github地址:https://gitee.com/free/Mapper 采用了分页...
**Spring+Spring MVC+MyBatis 整合详解** 在Java Web开发中,Spring、Spring MVC和MyBatis是常见的三大框架,它们的整合能够构建出高效、灵活且易于维护的Web应用程序。这个示例程序就是一个典型的三者结合的实例,...
基于Spring+Spring MVC+Mybatis+mysql实现web聊天室项目源码+数据库+项目说明.7z 【使用技术】 项目使用Maven构建,后台使用的语言是JAVA 框架为Spring + Spring MVC + Mybatis 数据库使用的是MySQL 前端采用Amaze ...
本教程将详细讲解如何进行Spring与MyBatis的基础配置,同时涵盖分页功能的实现以及JSON异常处理。下面,我们将一步步深入这个主题。 首先,我们需要在项目中引入Spring和MyBatis的相关依赖。Spring框架提供了依赖...
快速搭建项目原型,基于Spring + Spring MVC + Mybatis,简单轻便、易于扩展的架构,适用于大多数项目 封装了常用的CURD,配合mybatis-generator 自动生成dao、model、mapper层,减少重复劳动,提高生产力,实现快速...
本项目采用了“maven + spring mvc + mybatis(带分页) + easyui”的技术栈,这是一套非常常见的Java Web开发组合,适用于构建功能丰富的后台管理系统。下面将详细讲解这个组合中的各个组成部分及其在项目中的作用。 ...
这个"spring+spring mvc+mybatis+easyui整合demo"项目是针对这些技术的一个集成示例,旨在帮助开发者了解如何将它们协同工作以构建一个功能完备的Web应用程序。 首先,Spring框架作为基础,它提供了依赖注入(DI)...
里面包含了ssm基本整合以外,还包含了jackson demo、fastjson demo、freemarker demo、vus.js 2.5 demo、mybatis plus代码自动生成工具、mybatis plus 自定义分页示例、spring mvc各种类型参数传递demo、logback配置...
总的来说,这个"Maven+Spring MVC+Mybatis的分页例子"是一个实用的教程,帮助开发者了解如何在Java Web环境中集成这三个框架,并实现分页功能。通过这个实例,你可以学习到Maven的依赖管理、Spring MVC的请求处理、...
《Spring MVC与MYBatis企业应用实战》是一本深度探讨如何在实际企业环境中集成和运用Spring MVC和MYBatis两大主流技术的书籍。Spring MVC作为Spring框架的重要组成部分,是Java Web开发中的强大控制器,而MYBatis则...
在"mybatis分页"这一标签中,我们可以推测项目可能利用了MyBatis的分页插件来处理数据查询。分页插件通常会拦截SQL语句,自动添加LIMIT或OFFSET子句,根据用户请求的页码和每页大小进行数据截取。同时,插件还可能会...
<Spring+SpringMVC+Mybatis完整项目(SSM框架)> 框架:基于SSM框架(Spring+SpringMVC+MyBatis) + Mysql数据库 + Tomcat7 数据库工具建议用SQLyog 登录、首页显示用户名和身份、分页、模糊查询、 页面跳转(首页、上...
通过以上步骤和配置,我们可以构建一个功能完善的Web应用,利用Spring MVC处理请求,MyBatis处理数据库操作,同时实现事务控制、分页和JSON数据交换。在实际开发过程中,这些技术的结合使得应用更具可维护性和扩展性...