反射需要的几个工具类

 

对应的工具代码

package com.feizhou.common.plug_in.page;


/**
 * 类似hibernate的Dialect,但只精简出分页部分
 */
public class Dialect
{

    public boolean supportsLimit()
    {
        return false;
    }

    public boolean supportsLimitOffset()
    {
        return supportsLimit();
    }

    /**
     * 将sql变成分页sql语句,直接使用offset,limit的值作为占位符.</br> 源代码为:
     * getLimitString(sql,offset
     * ,String.valueOf(offset),limit,String.valueOf(limit))
     */
    public String getLimitString(String sql, int offset, int limit)
    {
        return getLimitString(sql, offset, Integer.toString(offset), limit,
                Integer.toString(limit));
    }

    /**
     * 将sql变成分页sql语句,提供将offset及limit使用占位符(placeholder)替换.
     * 
     * <pre>
     * 如mysql
     * dialect.getLimitString("select * from user", 12, ":offset",0,":limit") 将返回
     * select * from user limit :offset,:limit
     * </pre>
     * 
     * @return 包含占位符的分页sql
     */
    public String getLimitString(String sql, int offset,
            String offsetPlaceholder, int limit, String limitPlaceholder)
    {
        throw new UnsupportedOperationException("paged queries not supported");
    }

}
package com.feizhou.common.plug_in.page;


/**
 * mysql分页方言
 * @author Administrator
 *
 */
public class MySQLDialect extends Dialect{

	public boolean supportsLimitOffset(){
		return true;
	}
	
    public boolean supportsLimit() {   
        return true;   
    }  
    
	/** 
	 * 查询数量
	 */
	public String getLimitString(String sql, int offset,String offsetPlaceholder, int limit, String limitPlaceholder) {
        if (offset > 0) {   
        	return sql + " limit "+offsetPlaceholder+","+limitPlaceholder; 
        } else {   
            return sql + " limit "+limitPlaceholder;
        }  
	}   
  
}

 

 

 

package com.feizhou.common.plug_in.page;



/*
 The MIT License (MIT)

 Copyright (c) 2014 abel533@gmail.com

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
 */
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;

import javax.xml.bind.PropertyException;

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.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.feizhou.common.tools.reflect.ReflectUtil;


/**
 * 原理
 * 
 *  
 * 
 * 分页拦截器,用于拦截需要进行分页查询的操作,然后对其进行分页处理。 
 * 利用拦截器实现Mybatis分页的原理: 
 * 要利用JDBC对数据库进行操作就必须要有一个对应的Statement对象,
 * Mybatis在执行Sql语句前就会产生一个包含Sql语句的Statement对象,而且对应的Sql语句 
 * 是在Statement之前产生的,所以我们就可以在它生成Statement之前对用来生成Statement的Sql语句下手。
 * 在Mybatis中Statement语句是通过RoutingStatementHandler对象的 
 * prepare方法生成的。所以利用拦截器实现Mybatis分页的一个思路就是拦截StatementHandler接口的prepare方法,
 * 然后在拦截器方法中把Sql语句改成对应的分页查询Sql语句,之后再调用 StatementHandler对象的prepare方法,即调用invocation.proceed()。 
 * 对于分页而言,在拦截器里面我们还需要做的一个操作就是统计满足当前条件的记录一共有多少,这是通过获取到了原始的Sql语句后,
 * 把它改为对应的统计语句再利用Mybatis封装好的参数和设 
 * 置参数的功能把Sql语句中的参数进行替换,之后再执行查询记录数的Sql语句进行总记录数的统计。 
 * 
 *  
 * Mybatis的分页查询插件,通过拦截StatementHandler的prepare方法来实现。
 * 只有在参数列表中包括Page类型的参数时才进行分页查询。 在多参数的情况下,只对第一个Page类型的参数生效。
 * 另外,在参数列表中,Page类型的参数无需用@Param来标注
 * 
 * 对于StatementHandler其实只有两个实现类,一个是RoutingStatementHandler,另一个是抽象类BaseStatementHandler,  
 * BaseStatementHandler有三个子类,分别是SimpleStatementHandler,PreparedStatementHandler和CallableStatementHandler,  
 * SimpleStatementHandler是用于处理Statement的,PreparedStatementHandler是处理PreparedStatement的,而CallableStatementHandler是  
 * 处理CallableStatement的。Mybatis在进行Sql语句处理的时候都是建立的RoutingStatementHandler,而在RoutingStatementHandler里面拥有一个  
 * StatementHandler类型的delegate属性,RoutingStatementHandler会依据Statement的不同建立对应的BaseStatementHandler,即SimpleStatementHandler、  
 * PreparedStatementHandler或CallableStatementHandler,在RoutingStatementHandler里面所有StatementHandler接口方法的实现都是调用的delegate对应的方法。  
 * 我们在PageInterceptor类上已经用@Signature标记了该Interceptor只拦截StatementHandler接口的prepare方法,又因为Mybatis只有在建立RoutingStatementHandler的时候  
 * 是通过Interceptor的plugin方法进行包裹的,所以我们这里拦截到的目标对象肯定是RoutingStatementHandler对象。
 */
@SuppressWarnings("unchecked")
@Intercepts({ @Signature(type = StatementHandler.class, method = "prepare", args = { Connection.class }) })
public class PagePlugin implements Interceptor
{

    /**
     * 数据库方言
     */
    private static Dialect dialectObject = null;

    /**
     * mybaits的数据库xml映射文件中需要拦截的ID(正则匹配)
     */
    private static String pageSqlId = "";

    public Object intercept(Invocation ivk) throws Throwable
    {
        if (ivk.getTarget() instanceof RoutingStatementHandler)
        {
            RoutingStatementHandler statementHandler = (RoutingStatementHandler) ivk
                    .getTarget();
            BaseStatementHandler delegate = (BaseStatementHandler) ReflectUtil
                    .getValueByFieldName(statementHandler, "delegate");
            
            
//            通过反射获取delegate父类BaseStatementHandler的mappedStatement属性  
            MappedStatement mappedStatement = (MappedStatement) ReflectUtil
                    .getValueByFieldName(delegate, "mappedStatement");

            // 方法1:通过ID来区分是否需要分页..*query.* 方法2:传入的参数是否有page参数,如果有,则分页,

            // if (mappedStatement.getId().matches(pageSqlId)) { // 拦截需要分页的SQL
            BoundSql boundSql = delegate.getBoundSql();
        
            // 分页SQL<select>中parameterType属性对应的实体参数,即Mapper接口中执行分页方法的参数,该参数不得为空
            Object parameterObject = boundSql.getParameterObject();
          
            if (parameterObject == null)
            {
                // throw new
                // NullPointerException("boundSql.getParameterObject() is null!");
                return ivk.proceed();
            } else
            {

                PageView pageView = null;
               
                if (parameterObject instanceof PageView)
                {
                    // 参数就是Pages实体
                    pageView = (PageView) parameterObject;
                } else if (parameterObject instanceof Map)
                {
                    for (Entry entry : (Set<Entry>) ((Map) parameterObject)
                            .entrySet())
                    {
                        if (entry.getValue() instanceof PageView)
                        {
                            pageView = (PageView) entry.getValue();
                            break;
                        }
                    }
                    if (pageView == null)
                    {
                        return ivk.proceed();
                    }
                } else
                {
                    // 参数为某个实体,该实体拥有Pages属性
                    pageView = ReflectUtil.getValueByFieldType(
                            parameterObject, PageView.class);
                    if (pageView == null)
                    {
                        return ivk.proceed();
                    }
                }
//                获取当前要执行的Sql语句,也就是我们直接在Mapper映射语句中写的Sql语句  
                String sql = boundSql.getSql();
                PreparedStatement countStmt = null;
                ResultSet rs = null;
                try
                {

                    // 记录统计
                    Connection connection = (Connection) ivk.getArgs()[0];
                    //执行获取查询总数sql
                    String countSql =getCountSql(sql);
 
                    countStmt = connection.prepareStatement(countSql);
                    ReflectUtil
                            .setValueByFieldName(boundSql, "sql", countSql);

                    DefaultParameterHandler parameterHandler = new DefaultParameterHandler(
                            mappedStatement, parameterObject, boundSql);

                    parameterHandler.setParameters(countStmt);
                    rs = countStmt.executeQuery();

                    int count = 0;

                    if (rs.next())
                    {
                        count = ((Number) rs.getObject(1)).intValue();
                    }
                    pageView.setRowCount(count);
                } finally
                {
                    try
                    {
                        rs.close();
                    } catch (Exception e)
                    {
                    }
                    try
                    {
                        countStmt.close();
                    } catch (Exception e)
                    {
                    }
                }

                String pageSql = generatePagesSql(sql, pageView);
                ReflectUtil.setValueByFieldName(boundSql, "sql", pageSql); // 将分页sql语句反射回BoundSql.
            }
            // }
        }
        return ivk.proceed();
    }

    /**
     * 根据数据库方言,生成特定的分页sql
     * 
     * @param sql
     * @param page
     * @return
     */
    private String generatePagesSql(String sql, PageView page)
    {
        if (page != null && dialectObject != null)
        {
            // pageNow默认是从1,而已数据库是从0开始计算的.所以(page.getPageNow()-1)
            int pageNow = page.getStartPage();
            return dialectObject.getLimitString(sql, (pageNow <= 0 ? 0
                    : pageNow - 1) * page.getPageSize(), page.getPageSize());
        }
        return sql;
    }

    public Object plugin(Object target)
    {
        return Plugin.wrap(target, this);
    }

    public void setProperties(Properties p)
    {
        // 数据库方言
        String dialect = "";
        dialect = p.getProperty("dialect");
        if (dialect=="" || dialect==null)
        {
            try
            {
                throw new PropertyException("dialect property is not found!");
            } catch (PropertyException e)
            {
                e.printStackTrace();
            }
        } else
        {
            try
            {
                dialectObject = (Dialect) Class.forName(dialect)
                        .getDeclaredConstructor().newInstance();
            } catch (Exception e)
            {
                throw new RuntimeException(dialect + ", init fail!\n" + e);
            }
        }

        // 根据id来区分是否需要分页
        pageSqlId = p.getProperty("pageSqlId");
        if (pageSqlId=="" || pageSqlId==null)
        {
            try
            {
                throw new PropertyException("pageSqlId property is not found!");
            } catch (PropertyException e)
            {
                e.printStackTrace();
            }
        }
    }
    
    /** 
     * 根据原Sql语句获取对应的查询总记录数的Sql语句 
     * @param sql 
     * @return 
     */  
    private String getCountSql(String sql) {  
    	
        String countSql = "select count(1) from (" + sql
                + ") tmp_count";
       return countSql;  
    }  
    
  
}

 

package com.feizhou.common.plug_in.page;

import java.util.List;

/**
 * //分页封装函数
 * @param <T>
 */
@SuppressWarnings("rawtypes")
public class PageView {
	private String  order;//desc or asc
	private String sort;//哪个字段进行排序
	/**
	 * 查询的记录
	 */
	private List rows;
	/**
	 * 总页数
	 * 
	 */
	private long pageCount;
	/**
	 * 总记录数
	 */
	private long rowsCount;

	/**
	 * 每页显示几条记录
	 */
	private int pageSize = 10;

	/**
	 *默认 当前页 为第一页
	 */
	private int startPage = 1;


	
 
 
	public PageView() {
	}

  
	/**
	 * 使用构造函数,,强制必需输入
	 * 每页显示数量 和 当前页
	 * @param pageSize  每页显示数量
	 * @param startPage 开始页面
	 */
	public PageView(int pageSize, int startPage){
		this.pageSize = pageSize;
		this.startPage = startPage;
	}
 

	public void setRowCount(long rowCount) {
		this.rowsCount = rowCount;
		setPageCount(this.rowsCount % this.pageSize == 0?
					this.rowsCount/this.pageSize :
					this.rowsCount/this.pageSize+1
		);
	}
	

 
	public void setPageCount(long pageCount) {
		this.pageCount = pageCount;
	}


	public long getPageCount() {
		return pageCount;
	}
	
	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}
	

	public int getStartPage() {
		return startPage;
	}

	public void setStartPage(int startPage) {
		this.startPage = startPage;
	}

	public List getRows() {
		return rows;
	}

	public void setRows(List rows) {
		this.rows = rows;
	}

 

	public long getRowsCount() {
		return rowsCount;
	}

	public void setRowsCount(long rowsCount) {
		this.rowsCount = rowsCount;
	}

	public String getOrder() {
		return order;
	}

	public void setOrder(String order) {
		this.order = order;
	}

	public String getSort() {
		return sort;
	}
	

	public void setSort(String sort) {
		this.sort = sort;
	}

 

}

 

 

package com.feizhou.common.tools.reflect;


import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;




/**
 * 
 * @ClassName ReflectUtil
 * @Description TODO(反射工具)
 * @author feizhou
 * @Date 2018年5月23日 下午3:16:51
 * @version 1.0.0
 */
public class ReflectUtil{
    /**
     * 
     * @Description (获取obj对象fieldName的Field对象)
     * @author feizhou
     * @Date 2018年5月23日下午3:48:14  
     * @version 1.0.0
     * @param obj
     * @param fieldName
     * @return 
     * 如:private java.lang.String com.feizhou.common.tools.reflect.User.name
     */
    public static Field getFieldByFieldName(Object obj, String fieldName)
    {
        if (obj == null || fieldName == null)
        {
            return null;
        }
        //获取当前class文件对象
        Class<?> superClass = obj.getClass();
        //如果当前class文件对象不同于Object,获取父类的class文件
//    	System.out.println("Object.class:  "+Object.class);
//    	Object.class:  class java.lang.Object
        for (; superClass != Object.class; superClass = superClass.getSuperclass())
//        	System.out.println("superClass != Object.class:  "+(superClass != Object.class));
        {
//        	System.out.println("superClass:  "+superClass);
//        superClass:  class com.feizhou.common.tools.reflect.User
            try
            {
            	//获取指定已声明字段的 Field 对象
//            	Field 对象:private java.lang.String com.feizhou.common.tools.reflect.User.name
                return superClass.getDeclaredField(fieldName);
            } catch (Exception e)
            {
            }
        }
        return null;
    }

    /**
     * 
     * @Description (获取obj对象fieldName的属性值)
     * @author feizhou
     * @Date 2018年5月23日下午3:47:43  
     * @version 1.0.0
     * @param obj
     * @param fieldName
     * @return
     */
    public static Object getValueByFieldName(Object obj, String fieldName) {
//    	案例
//    	User user=new User("111","222");
//    	String name = (String) getValueByFieldName(user, "name");
//    	System.out.println("name:"+name);
//    	打印:name:111
        Object value = null;
        try
        {
            Field field = getFieldByFieldName(obj, fieldName);
            if (field != null)
            {	
            	//该field是否可以访问
                if (field.isAccessible())//是
                {
                    value = field.get(obj);
                } else//否
                {//设置可以强制访问,如private 类型的属性
                    field.setAccessible(true);
                    value = field.get(obj);
                    field.setAccessible(false);
                }
            }
        } catch (Exception e)
        {
        }
        return value;
    }

    

    /**
     * 
     * @Description (设置obj对象fieldName的属性值)
     * @author feizhou
     * @Date 2018年5月23日下午3:52:31  
     * @version 1.0.0
     * @param obj
     * @param fieldName
     * @param value
     * @return false:没有这个字段,ture:设置值成功
     */
 	@SuppressWarnings({ "rawtypes", "unchecked" })
    public static boolean setValueByFieldName(Object obj, String fieldName,Object value){
//    	案例
//    	User user=new User();
//	  	setValueByFieldName(user, "name","123");
//	  	System.out.println("打印name:"+user.getName());
//	  	打印name:123
        try
        {
            // java.lang.Class.getDeclaredField()方法用法实例教程 -
            // 方法返回一个Field对象,它反映此Class对象所表示的类或接口的指定已声明字段。
            // 此方法返回这个类中的指定字段的Field对象
            Field field = obj.getClass().getDeclaredField(fieldName);
            /**
             * public void setAccessible(boolean flag) throws
             * SecurityException将此对象的 accessible 标志设置为指示的布尔值。值为 true
             * 则指示反射的对象在使用时应该取消 Java 语言访问检查。值为 false 则指示反射的对象应该实施 Java 语言访问检查。
             * 首先,如果存在安全管理器,则在 ReflectPermission("suppressAccessChecks") 权限下调用
             * checkPermission 方法。 如果 flag 为 true,并且不能更改此对象的可访问性(例如,如果此元素对象是
             * Class 类的 Constructor 对象),则会引发 SecurityException。 如果此对象是
             * java.lang.Class 类的 Constructor 对象,并且 flag 为 true,则会引发
             * SecurityException。 参数: flag - accessible 标志的新值 抛出:
             * SecurityException - 如果请求被拒绝。
             */
            if (field.isAccessible())
            {   
                // 获取此对象的 accessible 标志的值。
                // 将指定对象变量上此 Field 对象表示的字段设置为指定的新值
                field.set(obj, value);
            } else{
            	

//            	value类型与field的类型不匹配,下面的方法将value转换field的类型
         	  
				Class typeClass = field.getType();  
				Constructor con = typeClass.getConstructor(value.getClass());  
        	    Object newInstance = con.newInstance(value);
            	    
                field.setAccessible(true);
                field.set(obj, newInstance);
                field.setAccessible(false);
            }
            return true;
        } catch (Exception e)
        {
        	 
        }
        return false;//没有这个字段
    }
    
    /**
     * 
     * @Description (根据属性名称调用get方法)
     * @author feizhou
     * @Date 2018年5月23日下午3:56:48  
     * @version 1.0.0
     * @param obj
     * @param fieldName
     * @return
     */
    public static String getter(Object obj, String fieldName) {
//    	案例
//    	User user=new User("1111","pass");
//    	System.out.println("打印name:"+getter(user, "name"));
//    	打印name:1111
        String valueString = "";
        try {
        	if (StringUtils.isNotEmpty(fieldName)) {
        		//拼接get方法
        		String getMethod="get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
        		//获取方法
        		Method method = obj.getClass().getMethod(getMethod);
        		Object result = method.invoke(obj);
        		if (result != null) {
        			valueString = result.toString().trim();
        		}
        	}
        } catch (Exception e) {
            e.printStackTrace();
        }
        return valueString;
    }
   
//    public static void main(String[] args) {
//    	User user=new User("1111","pass");
//    	System.out.println("打印name:"+getter(user, "name"));
//    	打印name:1111
//	}
    
//    //内部类
//      class User {
//    	private String name;
//    	private String password;
//
//    	public String getName() {
//    		return name;
//    	}
//    	public void setName(String name) {
//    		this.name = name;
//    	}
//    	public String getPassword() {
//    		return password;
//    	}
//    	public void setPassword(String password) {
//    		this.password = password;
//    	}
//
//    	public User(String name, String password) {
//    		super();
//    		this.name = name;
//    		this.password = password;
//    	}
//    	public User() {
//    		super();
//    	}
//    	}
    
    
    /**
     * 获取obj对象和类文件获取对应类实例
     * @param obj
     * @param fieldName
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <T> T getValueByFieldType(Object obj, Class<T> fieldType)
    {
        Object value = null;
        for (Class<?> superClass = obj.getClass(); superClass != Object.class; superClass = superClass
                .getSuperclass())
        {
            try
            {
                Field[] fields = superClass.getDeclaredFields();
                for (Field f : fields)
                {
                    if (f.getType() == fieldType)
                    {
                        if (f.isAccessible())
                        {
                            value = f.get(obj);
                            break;
                        } else
                        {
                            f.setAccessible(true);
                            value = f.get(obj);
                            f.setAccessible(false);
                            break;
                        }
                    }
                }
                if (value != null)
                {
                    break;
                }
            } catch (Exception e)
            {
            }
        }
        return (T) value;
    }
    /**
     * 
     * @Description (获取接口对象的所有字段和字段对应的值Map(值,字段名))
     * @author feizhou
     * @Date 2018年6月12日上午11:18:19  
     * @version 1.0.0
     * @param obj
     * @return
     */
    public  static Map<String,String>  getAllValueToFileID(Object object){
     
    	Map<String,String> map=new HashMap<String, String>();
            // 拿到该类  
            Class<?> clz = object.getClass();  
            // 获取实体类的所有属性,返回Field数组  
            Field[] fields = clz.getDeclaredFields();  
            Object   val=null;
            try {
				
            for (Field field : fields) {// --for() begin  
            	field.setAccessible(true); // 设置些属性是可以访问的
            	    val = field.get(object);
            	    map.put(String.valueOf(val), field.getName());
                }  
                // 如果还需要其他的类型请自己做扩展  
            } catch (Exception e) {
				// TODO: handle exception
            	e.printStackTrace();
			}

		return map;
    	
    }
    
    /**
     * 
     * @Description (获取接口对象的所有字段和字段对应的值Map(字段名,值))
     * @author feizhou
     * @Date 2018年6月12日上午11:18:19  
     * @version 1.0.0
     * @param obj
     * @return
     */
    public  static Map<String,String>  getAllFileIDToValue(Object object){
     
    	Map<String,String> map=new HashMap<String, String>();
            // 拿到该类  
            Class<?> clz = object.getClass();  
            // 获取实体类的所有属性,返回Field数组  
            Field[] fields = clz.getDeclaredFields();  
            Object   val=null;
            try {
				
            for (Field field : fields) {// --for() begin  
            	field.setAccessible(true); // 设置些属性是可以访问的
            	    val = field.get(object);
            	    map.put(field.getName(), String.valueOf(val));
                }  
                // 如果还需要其他的类型请自己做扩展  
            } catch (Exception e) {
				// TODO: handle exception
            	e.printStackTrace();
			}

		return map;
    	
    }
    
    public  static Field[]  getAllFileID(Object object){
        
    	Map<String,String> map=new HashMap<String, String>();
            // 拿到该类  
            Class<?> clz = object.getClass();  
            // 获取实体类的所有属性,返回Field数组  
            Field[] fields = clz.getDeclaredFields();  

		return fields;
    	
    }
}

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:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.1.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">

   
   
    <bean id="pagePlugin" class="com.feizhou.common.plug_in.page.PagePlugin">
		<property name="properties">
			<props>
			 	<!-- 指定数据库分页方言Dialect -->
				<prop key="dialect">com.feizhou.common.plug_in.page.MySQLDialect</prop>
				<prop key="pageSqlId">.*select.*</prop>
			</props>
		</property>
	</bean>
    
    
    
    
	<!--有接口配置,mybatis sessionFactory配置 -->
	<bean id="SqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
		<!-- 数据源 jdbc.xml的数据源配置 -->
		<property name="dataSource" ref="dataSource" />
		 	<property name="plugins">  
	            <ref bean="pagePlugin"/>  
	        </property>  
		<!-- 模板配置 ,读取的是mybatis接口配置模板,自动扫描mapping.xml文件 -->
		<property name="mapperLocations" value="classpath:com/feizhou/core/dao/*.xml" />
		<!-- 别名,别名包,包下的就不要起别名了,直接扫描包 ,这样bean下就不要起别名了,可以省了一个配置文件,mybaits的配置文件的类名就不要用全路径了 -->
		<property name="typeAliasesPackage" value="com.feizhou.core.bean" />
	</bean>
	
	<!-- mybaits扫包 -->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<!-- basePackage指定要扫描的包,在此包之下的映射器都会被搜索到,可指定多个包,包与包之间用逗号或分号分隔-->  
		<property name="basePackage" value="com.feizhou.core.dao" />
		          
	</bean>
	
 
	  
</beans>

常量配置

package com.feizhou.common.finalConfig.page;



/**
 * 分页常量配置
 *
 */
public interface PageConstans {
	
 
	/**
	 * 起始页参数常量
	 */
	public static final String startPage = "page";
	/**
	 * 每页大小参数常量
	 */
	public static final String pageSize = "rows";
}

请求参数设置

package com.feizhou.common.web.request;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.feizhou.common.finalConfig.page.PageConstans;
import com.feizhou.common.plug_in.page.PageView;
import com.feizhou.common.tools.commonTools.MapUtil;
import com.feizhou.common.tools.commonTools.StringUtil;


public class RequestUtil {
	/**
	 * 
	 * @Description (返回用户的IP地址)
	 * @author feizhou
	 * @Date 2018年5月27日下午3:25:26  
	 * @version 1.0.0
	 * @param request
	 * @return
	 */
	public static String toIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}
	/**
	 * 
	 * @Description (将请求参数转换map(String,Object))
	 * @author feizhou
	 * @Date 2018年5月27日下午3:31:17  
	 * @version 1.0.0
	 * @param request
	 * @return
	 */
	public static Map<String, Object> getUrlParam(HttpServletRequest request) {
		Map<String, Object> map=new HashMap<String, Object>();
		//获取url的参数
		Map<String, String[]> parameterMap = request.getParameterMap();
		//获取keys
		  Set<String> keySet = parameterMap.keySet();
		//遍历keys
		 for ( String  key : keySet) {
			 String[] strings = parameterMap.get(key);
			 if(strings.length>1){
				 map.put(key, strings);
			 }else{
				 map.put(key, strings[0].toString());
			 }
		}
		//data是个json集合
		String data = (String)map.remove("data");
		Map<String, Object> map1 = MapUtil.jsonStrToMap(data);
		if(map1!=null){
			map.putAll(map1);
		}
		
		String pageSize= (String) map.remove(PageConstans.pageSize) ;
		String startPage= (String) map.remove(PageConstans.startPage) ;
		//如果页面传有分页数据
		if(StringUtil.isNotEmpty(pageSize)&&StringUtil.isNotEmpty(startPage)){
			PageView pageView=new PageView();
			pageView.setStartPage(Integer.valueOf(startPage));
			pageView.setPageSize(Integer.valueOf(pageSize));
			map.put("pageView", pageView);
		}
		return map;
	}
	/**
	 * 
	 * @Description (获取当前请求的request)
	 * @author feizhou
	 * @Date 2018年6月4日下午4:27:05  
	 * @version 1.0.0
	 * @return
	 */
	public static  HttpServletRequest getRequest(){
		HttpServletRequest		request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		return request;
	}
	/**
	 * 
	 * @Description (通过参数名获取指定的参数)
	 * @author feizhou
	 * @Date 2018年6月5日上午11:18:12  
	 * @version 1.0.0
	 * @param name
	 * @return
	 */
	public static  Set<Integer> getSetIntByParam(String name){
		HttpServletRequest		request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		
		String names =  request.getParameter(name);
		Set<Integer> namesSet = StringUtil.StringToSetIntByComma(names);
		return namesSet;
	}
	/**
	 * 
	 * @Description (通过参数名获取指定的参数)
	 * @author feizhou
	 * @Date 2018年6月5日上午11:18:12  
	 * @version 1.0.0
	 * @param name
	 * @return
	 */
	public static  Set<String> getSetStrByParam(String name){
		HttpServletRequest		request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
	
		String names =  request.getParameter(name);
		Set<String> namesSet = StringUtil.StringToSetStrByComma(names);
		
		return namesSet;
	}
	/**
	 * 
	 * @Description (通过参数名获取指定的参数)
	 * @author feizhou
	 * @Date 2018年6月5日上午11:18:12  
	 * @version 1.0.0
	 * @param name
	 * @return
	 */
	public static  List<Integer> getListIntByParam(String name){
		HttpServletRequest		request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		String names =  request.getParameter(name);
		List<Integer> namesList = StringUtil.StringToListIntByComma(names);
		
		return namesList;
	}
	/**
	 * 
	 * @Description (通过参数名获取指定的参数)
	 * @author feizhou
	 * @Date 2018年6月5日上午11:18:12  
	 * @version 1.0.0
	 * @param name
	 * @return
	 */
	public static  List<String> getListStrByParam(String name){
		HttpServletRequest		request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		String names =  request.getParameter(name);
		List<String> namesList = StringUtil.StringToListStrByComma(names);
		return namesList;
	}
	}

controller主要代码

@Controller
public class ApplicationController {
	@Autowired
	private ApplicationService applicationService;

	@RequestMapping(value = "/ApplicationController/selectApplications.do")
	public void selectApplications(HttpServletRequest resquest,HttpServletResponse  response) {
 
		// 获取参数
		Map<String, Object> paramMap = RequestUtil.getUrlParam(resquest);
		PageView pageView = (PageView) paramMap.get("pageView");

		if (pageView == null) {
			pageView = new PageView();
		}
		List<Application> list = null;
		String jsonStr = null;
		try {
			list = applicationService.selectList(paramMap);
			pageView.setRows(list);
			jsonStr = ResultBean.createResult_status_success(pageView);
		} catch (Exception e) {
			e.printStackTrace();
			jsonStr = ResultBean.getFailureJsonString();
		}
		ResponseUtils.renderJson(response, jsonStr);
	}

 

posted on 2018-07-18 14:18  2637282556  阅读(203)  评论(0编辑  收藏  举报