Spring + mvc,Mybatis整合 (含事务配置,分页功能)

Spring + mvc,Mybatis整合 (含事务配置,分页功能)

环境

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的标准目录结构。

2.配置依赖

<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>

12.Run App

 上传源码,提取码为:ccff

http://l13.yunpan.cn/lk/sVt2FiVeDpcaX

 

 

posted @ 2012-11-30 15:41  Mr.24k  阅读(9914)  评论(9编辑  收藏  举报