环境
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.配置依赖
4.0.0
jo.geun
sampleProj
war
0.0.1-SNAPSHOT
sampleProj Maven Webapp
http://maven.apache.org
3.1.3.RELEASE
org.springframework
spring-core
${spring.version}
org.springframework
spring-web
${spring.version}
org.springframework
spring-webmvc
${spring.version}
org.mybatis
mybatis
3.1.1
org.mybatis
mybatis-spring
1.1.1
commons-dbcp
commons-dbcp
1.4
com.oracle
ojdbc6
11.2.0.3.0
cglib
cglib
2.2.2
taglibs
standard
1.1.2
javax.servlet
jstl
1.2
org.codehaus.jackson
jackson-core-asl
1.9.11
org.codehaus.jackson
jackson-mapper-asl
1.9.11
sampleProj
org.apache.maven.plugins
maven-compiler-plugin
2.5.1
1.6
需注意的是,因为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的配置
Sample Web Application
contextConfigLocation
/WEB-INF/spring/root-context.xml
org.springframework.web.context.ContextLoaderListener
appServlet
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
/WEB-INF/spring/servlet-context.xml
0
appServlet
/
这里简简单单的说明一下吧。。
节点配置contextConfigLocation属性是为了让ContextLoaderListener找到Spring上下文的位置并加载它,如果不指定contextConfigLocation,ContextLoaderListener会到/WEB-INF/目录下找applicationContext.xml来加载。
节点上配了ContextLoaderListener。它实现了ServletContextListener接口,所以web server启动时ContextLoaderListener能读取到ServletContext,也就能通过 指定的Spring上下文的路径来找到上下文并加载它。
当然,如果你不需要Spring来管理你的Bean,可以去掉上面两个节点。
和 两个节点其实也不用多说,就是告诉容器匹配 的请求都让Spring的 DispatcherServlet(就是一个Servlet,继承自HttpServlet)来处理。而它会把请求分发给其他控制器。详见Spring reference 16章 。
在WEB-INF目录下创建一个叫Spring的文件夹,上面指定的Spring的两个配置文件会放到这个文件夹内。
4.配置Spring mvc
在web.xml的 节点中我们指定了servlet-context.xml。这里可以配拦截器还有视图解析器等,也可以配multipartResolver来实现文件上传功能。
这儿需要注意的是 节点。看到很多人问起让Spring来管理事务时候,事务为什么会不起作用,其中也有在这儿犯错的。。
通常我们会做分层开发,在这个小例子中也分了controller、service 、 dao 三层,由service层来管理事务。
如果在这个servlet context里面把service层也给scan了,service Bean就会被提前实例化,Spring的事务就没法控制事务对象了。所以一定要让这个扫描器过滤掉service层的扫描。
上面因为package的结构简单,就直接指定了controller层,其实也可以换种方式来写
用上面的方式会过滤掉所有带@Service注解的类,也可以用正则表达式或AspectJ类型的表达式,具体的参阅官方文档。
5.root-context.xml
这儿主要包含了数据源及事务的配置,还有dao、service层bean的定义。
MapperScannerConfigurer会寻找指定包下的Mapper并自动将它们注册到到MapperFactoryBean代理工厂,这个代理工厂可以让你的mapper interface直接注入到其他bean中,而你完全不需要实现这个接口。不嫌累,也可以一个一个的注册Mapper接口,如下。
6.mybatis-conf.xml
WEB-INF目录下创建文件夹mybatis,来放置它。
如果mapper interface和mapper xml取一样的文件名,放到同一个包下就不用另配 节点来告诉映射文件的位置了。
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 map = (Map)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 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
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 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 getMemberList(PageInfo pageInfo){
return sampleMapper.getMemberListPage(pageInfo);
}
}
@Service(下面还会有一个@Controller)注解是用来标注一个Bean的,spring会根据我们在上面配的 component-scan节点来扫描注册这些bean。它会根据类名实例化一个首字母为小写的bean,也可以给它一个参数来自定义bean id,如@Service("这样")。他的作用跟Spring配置文件里配一个普通bean是一样的。
@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 {
/**
* Current page
*/
private int page;
/**
* Total pages
*/
private int total;
/**
* Total number of records
*/
private int records;
/**
* Contains the actual data
*/
private List rows;
public JsonResponse() {
}
public JsonResponse(List 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 getData(PageInfo pageInfo) {
List list = sampleService.getMemberList(pageInfo);
JsonResponse response = new JsonResponse(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"%>
" />
" />
"
type="text/javascript">
">
"
type="text/javascript">
"
type="text/javascript">
Insert title here