基于springboot+bootstrap+mysql+redis搭建一套完整的权限架构【四】【编写基础开发工具】

       大家在经过一段时间的开发实际上已经积累的自己的一套的开发框架或者一些自己的jar包,此处所编写的开发工具是基于当前工程的进行扩展的一个开发工具包,仅适合当前框架,若大家需要的话可以自己在当前开发工具包底下进行扩展,有了开发工具包的好处就是我们可以少写很多基础的代码,那么接下来将开始编写我们的开发工具包:

      首先在我们的common包底下先建以下的包结构:

基于springboot+bootstrap+mysql+redis搭建一套完整的权限架构【四】【编写基础开发工具】_第1张图片

在我们创建我们的开发工具包之前我们需要先添加几个配置文件在我们的config->util包底下我们创建一个json包同时增加一个JsonHelper.java文件如下所示:

/*
* 类描述:json工具类
* @auther linzf
* @create 2017/8/23 0023 
*/
public class JsonHelper {

    private static SimpleDateFormat sdf = new SimpleDateFormat(
            "yyyy-MM-dd HH:mm:ss");

    // 将JSON转换成Map,其中valueClz为Map中value的Class,keyArray为Map的key
    public static Map json2Map(Object[] keyArray, String json, Class valueClz) {
        JSONObject jsonObject = JSONObject.fromObject(json);
        Map classMap = new HashMap();
        for (int i = 0; i < keyArray.length; i++) {
            classMap.put(keyArray[i], valueClz);
        }
        return (Map) JSONObject.toBean(jsonObject, Map.class, classMap);
    }

    /***
     * 将对象转换为传入类型的List
     *
     * @param object
     * @param objectClass
     * @return
     */
    public static  Collection toList(Object object, Class objectClass) {
        JSONArray jsonArray = JSONArray.fromObject(object);
        return JSONArray.toCollection(jsonArray, objectClass);
    }

    /**
     * 功能描述:实现将一个object对象转换为json的string字符串
     * @param obj
     * @return
     */
    public static String object2json(Object obj) {
        StringBuilder json = new StringBuilder();
        if (obj == null) {
            json.append("\"\"");
        } else if (obj instanceof String || obj instanceof BigDecimal
                || obj instanceof BigInteger) {
            json.append("\"").append(string2json(obj.toString())).append("\"");
        } else if (obj instanceof Boolean) {
            json.append(Boolean.valueOf(obj.toString()));
        } else if (obj instanceof Integer || obj instanceof Float
                || obj instanceof Short || obj instanceof Double
                || obj instanceof Long || obj instanceof Byte) {
            json.append(obj.toString());
        } else if (obj instanceof Date || obj instanceof java.sql.Date) {
            json.append("\"").append(sdf.format(obj)).append("\"");
        } else if (obj instanceof Object[]) {
            json.append(array2json((Object[]) obj));
        } else if (obj instanceof List) {
            json.append(list2json((List) obj));
        } else if (obj instanceof Map) {
            json.append(map2json((Map) obj));
        } else if (obj instanceof Set) {
            json.append(set2json((Set) obj));
        } else {
            json.append(bean2json(obj));
        }
        return json.toString();
    }

    public static String list2json(List list) {
        StringBuilder json = new StringBuilder();
        json.append("[");
        if (list != null && list.size() > 0) {
            for (Object obj : list) {
                json.append(object2json(obj));
                json.append(",");
            }
            json.setCharAt(json.length() - 1, ']');
        } else {
            json.append("]");
        }
        return json.toString();
    }

    public static String array2json(Object[] array) {
        StringBuilder json = new StringBuilder();
        json.append("[");
        if (array != null && array.length > 0) {
            for (Object obj : array) {
                json.append(object2json(obj));
                json.append(",");
            }
            json.setCharAt(json.length() - 1, ']');
        } else {
            json.append("]");
        }
        return json.toString();
    }

    public static String map2json(Map map) {
        StringBuilder json = new StringBuilder();
        json.append("{");
        if (map != null && map.size() > 0) {
            for (Object key : map.keySet()) {
                json.append(object2json(key));
                json.append(":");
                json.append(object2json(map.get(key)));
                json.append(",");
            }
            json.setCharAt(json.length() - 1, '}');
        } else {
            json.append("}");
        }
        return json.toString();
    }

    public static String set2json(Set set) {
        StringBuilder json = new StringBuilder();
        json.append("[");
        if (set != null && set.size() > 0) {
            for (Object obj : set) {
                json.append(object2json(obj));
                json.append(",");
            }
            json.setCharAt(json.length() - 1, ']');
        } else {
            json.append("]");
        }
        return json.toString();
    }

    public static String string2json(String s) {
        if (s == null)
            return "";
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);
            switch (ch) {
                case '"':
                    sb.append("\\\"");
                    break;
                case '\\':
                    sb.append("\\\\");
                    break;
                case '\b':
                    sb.append("\\b");
                    break;
                case '\f':
                    sb.append("\\f");
                    break;
                case '\n':
                    sb.append("\\n");
                    break;
                case '\r':
                    sb.append("\\r");
                    break;
                case '\t':
                    sb.append("\\t");
                    break;
                case '/':
                    sb.append("\\/");
                    break;
                default:
                    if (ch >= '\u0000' && ch <= '\u001F') {
                        String ss = Integer.toHexString(ch);
                        sb.append("\\u");
                        for (int k = 0; k < 4 - ss.length(); k++) {
                            sb.append('0');
                        }
                        sb.append(ss.toUpperCase());
                    } else {
                        sb.append(ch);
                    }
            }
        }
        return sb.toString();
    }

    public static String bean2json(Object bean) {
        StringBuilder json = new StringBuilder();
        json.append("{");
        PropertyDescriptor[] props = null;
        try {
            props = Introspector.getBeanInfo(bean.getClass(), Object.class)
                    .getPropertyDescriptors();
        } catch (IntrospectionException e) {
        }
        if (props != null) {
            for (int i = 0; i < props.length; i++) {
                try {
                    String name = object2json(props[i].getName());
                    String value = object2json(props[i].getReadMethod().invoke(
                            bean));
                    json.append(name);
                    json.append(":");
                    json.append(value);
                    json.append(",");
                } catch (Throwable e) {
                }
            }
            json.setCharAt(json.length() - 1, '}');
        } else {
            json.append("}");
        }
        return json.toString();
    }


}


接着我们在dao,entity,service包底下分别加入以下的类文件:

/**
 * 分页实体类
 * */
@SuppressWarnings("rawtypes")
public class Page {
	private List rows;
	private long total;
	
	public Page(){}
	
	public Page(List rows, long total) {
		super();
		this.rows = rows;
		this.total = total;
	}
	
	public List getRows() {
		return rows;
	}
	public void setRows(List rows) {
		this.rows = rows;
	}
	public long getTotal() {
		return total;
	}
	public void setTotal(long total) {
		this.total = total;
	}

	@Override
	public String toString() {
		return "Page [rows=" + rows + ", total=" + total + "]";
	}
}

/*
* 类描述:查询基础类
* @auther linzf
* @create 2017/8/11 0011 
*/
public class QueryBase {

    /** 要排序的字段名 */
    protected String sort;
    /** 排序方式: desc \ asc */
    protected String order = "";
    /** 获取一页行数 */
    protected int limit;
    /** 获取的页码 */
    protected int page;
    /** 起始记录 */
    protected int offset;

    public String getSort() {
        return sort;
    }

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

    public String getOrder() {
        return order;
    }

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

    public int getLimit() {
        return limit;
    }

    public void setLimit(int limit) {
        this.limit = limit;
    }

    public int getPage() {
        return page;
    }

    public void setPage(int page) {
        this.page = page;
    }

    public int getOffset() {
        return (this.page-1)*limit;
    }

    public void setOffset(int offset) {
        this.offset = offset;
    }
}

/**
 * Dao通用模版
 * */
public interface GenericDao{
	/**
	 * 根据主键值获取对象
	 * @param entity
	 * */
	public T get(T entity);
	
	/**
	 * 获取全部实体
	 * */
    public List loadAll();

	/**
	 * 查找是否存在
	 * @param queryModel 查询条件
	 * @return int
	 * */
	public int isExist(Q queryModel);

	/** 
	 * 保存
	 * @param entity 保存对象
	 * @return int
	 * @throws Exception
	 * */
	public int save(T entity) throws Exception;

	/** 
	 * 更新 
	 * @param entity 修改对象
	 * @return int
	 * @throws Exception
	 * */
	public int update(T entity) throws Exception;

	/**
	 * 删除 
	 * @param entity 删除对象
	 * @throws Exception
	 * @return int
	 * */
	public int delete(T entity) throws Exception;

	/**
	 * 分页查询
	 * @param queryModel 查询条件
	 *  */
	public List findByPage(Q queryModel);
	
	/**
	 * 统计
	 * @param queryModel 查询条件
	 * @return int
	 * */
	public int count(Q queryModel);

	/**
	 * 查询
	 * @param queryModel 查询条件
	 *  */
	public List query(Q queryModel);
	/**
	 * 根据id数组删除记录
	 * @param ids 数组
	 * @return int
	 * */
	public int deleteByIds(String[] ids) throws Exception;
}

/**
 * 通用Service
 * @author linzf
 * */
public abstract class GenericService {
	protected abstract GenericDao getDao();
	
	/**
	 * 根据主键值获取对象
	 * @param entity
	 * */
	public T get(T entity){
		return getDao().get(entity);
	}

	/**
	 * 获取全部实体
	 * */
    public List loadAll(){
    	return getDao().loadAll();
    }

	/**
	 * 查找是否存在
	 * @param queryModel 查询条件
	 * */
	public boolean isExist(Q queryModel){
		return getDao().isExist(queryModel)>0;
	}

	/** 
	 * 保存
	 * @param entity 保存对象
	 * @return boolean
	 * @throws Exception
	 * */
	public boolean save(T entity) throws Exception{
		return getDao().save(entity)>0;
	}

	/** 
	 * 更新 
	 * @param entity 修改对象
	 * @return boolean
	 * @throws Exception
	 * */
	public boolean update(T entity) throws Exception{
		return getDao().update(entity)>0;
	}

	/**
	 * 删除 
	 * @param entity 删除对象
	 * @return boolean
	 * @throws Exception
	 * */
	public boolean delete(T entity) throws Exception{
		return getDao().delete(entity)>0;
	}

	/**
	 * 分页查询
	 * @param queryModel 查询条件
	 *  */
	public Page findByPage(Q queryModel){
		List list =  getDao().findByPage(queryModel);
		int count = getDao().count(queryModel);
		return new Page(list, count);
	}
	
	/**
	 * 统计
	 * @param queryModel 查询条件
	 * @return int
	 * */
	public int count(Q queryModel){
		return getDao().count(queryModel);
	}

	/**
	 * 查询
	 * @param queryModel 查询条件
	 *  */
	public List query(Q queryModel){
		return getDao().query(queryModel);
	}
	/**
	 * 根据id数组删除记录
	 * @param ids 数组
	 * @return boolean
	 * */
	public boolean deleteByIds(String[] ids) throws Exception{
		return getDao().deleteByIds(ids)>0;
	}

	/**
	 * 功能描述:批量删除数据
	 * @param entityList
	 * @return
	 */
	public boolean removeBath(List entityList) throws Exception{
		for(T t:entityList){
			if(!delete(t)){
				return false;
			}
		}
       return true;
	}
}

public abstract class GenericController {

	// 抽象方法
	protected abstract GenericService getService();

	/**添加页面路径*/
	public final static String ADDPAGE = "/add";
	/**修改页面路径*/
	public final static String UPDATEPAGE = "/update";

	/**
	 * Controller基路径
	 * */
	protected String basePath;

	/**抽象方法,获取页面基路径
	 * @throws Exception */
	protected String getPageBaseRoot() throws Exception{
		if(basePath==null){
			basePath = this.getClass().getName();
			Pattern p=Pattern.compile(".[a-z|A-z]+.controller.[a-z|A-z]+Controller");
			Matcher m=p.matcher(basePath);
			if(m.find()){
				basePath = m.group();
				basePath = basePath.substring(1, basePath.length()-10);
				basePath = basePath.replace(".", "/");
				basePath = basePath.replace("/controller/", "/");
				basePath = basePath.substring(0,basePath.lastIndexOf("/")+1)+ toFirstCharLowerCase(basePath.substring(basePath.lastIndexOf("/")+1));
			}
			else{
				throw new Exception("获取页面基路径失败");
			}
		}
		return basePath;
	}


	/**
	 * 功能描述:直接跳转到更新数据的页面
	 * @param entity
	 * @return
	 */
	@RequestMapping(value = "/updatePage",method = RequestMethod.GET,produces = MediaType.APPLICATION_JSON_VALUE)
	public String updatePage(T entity,Model model) throws Exception{
		entity = getService().get(entity);
		model.addAttribute("entity",entity);
		return getPageBaseRoot()+UPDATEPAGE;
	}

	/** 跳转到添加对象页面
	 * @throws Exception */
	@RequestMapping(value="/addPage")
	public String addPage() throws Exception{
		return getPageBaseRoot()+ADDPAGE;
	}

	/**
	 * 功能描述:保存数据字典数据
	 * @param entity
	 * @return
	 */
	@RequestMapping(value = "/save",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	public Map save(T entity) throws Exception{
		boolean success = getService().save(entity);
		Map result = new HashMap();
		if(success==true){
			result.put(SystemStaticConst.RESULT, SystemStaticConst.SUCCESS);
			result.put(SystemStaticConst.MSG,"增加数据成功!");
			result.put("entity",entity);
		}else{
			result.put(SystemStaticConst.RESULT,SystemStaticConst.FAIL);
			result.put(SystemStaticConst.MSG,"增加数据失败!");
		}
		return result;
	}

	/**
	 * 功能描述:更新数据字典数据
	 * @param entity
	 * @return
	 */
	@RequestMapping(value = "/update",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	public Map update(T entity)  throws Exception{
		boolean success  = getService().update(entity);
		Map result = new HashMap();
		if(success==true){
			result.put(SystemStaticConst.RESULT,SystemStaticConst.SUCCESS);
			result.put(SystemStaticConst.MSG,"更新数据成功!");
			result.put("entity",entity);
		}else{
			result.put(SystemStaticConst.RESULT,SystemStaticConst.FAIL);
			result.put(SystemStaticConst.MSG,"更新数据失败!");
		}
		return result;
	}

	/**
	 * 功能描述:实现批量删除数据字典的记录
	 * @param entity
	 * @return
	 */
	@RequestMapping(value = "/remove",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	public Map remove(T entity) throws Exception{
		Map result = new HashMap();
		getService().delete(entity);
		result.put(SystemStaticConst.RESULT,SystemStaticConst.SUCCESS);
		result.put(SystemStaticConst.MSG,"删除数据成功!");
		return result;
	}


	/**
	 * 功能描述:实现批量删除数据字典的记录
	 * @param json
	 * @return
	 */
	@RequestMapping(value = "/removeBath",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	public Map removeBath(String json) throws Exception{
		Map result = new HashMap();
		getService().removeBath((List) JsonHelper.toList(json,(Class ) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]));
		result.put(SystemStaticConst.RESULT,SystemStaticConst.SUCCESS);
		result.put(SystemStaticConst.MSG,"删除数据成功!");
		return result;
	}

	/**
	 * 功能描述:获取数据字典的分页的数据
	 * @param entity
	 * @return
	 */
	@RequestMapping(value = "/list",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	public Map list(Q entity){
		Map result = new HashMap();
		Page page = getService().findByPage(entity);
		result.put("totalCount",page.getTotal());
		result.put("result",page.getRows());
		return result;
	}

	/**
	 * 功能描述:判断当前的字典元素是否已经存在
	 * @param entity
	 * @return
	 */
	@RequestMapping(value = "/isExist",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	public Map isExist(Q entity){
		Map result = new HashMap();
		if(getService().query(entity).size()>0){
			result.put("valid",false);
		}else{
			result.put("valid",true);
		}
		return result;
	}

	/**
	 * 将首字母变小写
	 * @param str
	 * @return
	 */
	private static String toFirstCharLowerCase(String str){
		char[]  columnCharArr = str.toCharArray();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < columnCharArr.length; i++) {
			char cur = columnCharArr[i];
			if(i==0){
				sb.append(Character.toLowerCase(cur));
			}else{
				sb.append(cur);
			}
		}
		return sb.toString();
	}

}

添加好上面的实体以后我们就完成了我们开发基础工具类的基本工作,效果如下所示:

基于springboot+bootstrap+mysql+redis搭建一套完整的权限架构【四】【编写基础开发工具】_第2张图片

接着我们改造我们之前的用户模块的代码,先打开我们的mybatis->mapper底下的mybatis_user.xml我们重新改造该文件结果如下:





	
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
	

	
	
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
			
			
			
		
	

	
	

	
	

	
	
		INSERT INTO user(login,password,user_name,address,job,group_id,birth_date,city,district,province,street_address,state,type,last_login_date)
		VALUES(#{login},#{password},#{userName},#{address},#{job},#{orgGroup.groupId},#{birthDate},#{city},#{district},#{province},#{streetAddress},#{state},#{type},#{lastLoginDate})
	

	
	
		UPDATE user SET user_name=#{userName},address=#{address},job=#{job},group_id=#{orgGroup.groupId},birth_date=#{birthDate},city=#{city},district=#{district},province=#{province},street_address=#{streetAddress}
		WHERE id=#{id}
	

	
	
		DELETE FROM user WHERE id=#{id}
	

	
	

	
	

	
	

	
	

	
	




接着改造我们的java层,首先在我们的sys包的entity底下创建一个QueryUser.java文件如下所示:

/**
 *@author linzf
 **/
public class QueryUser extends QueryBase {
	private String login;
	private String password;
	private String userName;
	private String address;
	private String job;
	private Long groupId;
	private String birthDate;
	private String city;
	private String district;
	private String province;
	private String streetAddress;
	private String state;
	private String type;
	private String lastLoginDate;


	public String getLogin() {
		return login;
	}

	public void setLogin(String login) {
		this.login = login;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public String getJob() {
		return job;
	}

	public void setJob(String job) {
		this.job = job;
	}

	public Long getGroupId() {
		return groupId;
	}

	public void setGroupId(Long groupId) {
		this.groupId = groupId;
	}

	public String getBirthDate() {
		return birthDate;
	}

	public void setBirthDate(String birthDate) {
		this.birthDate = birthDate;
	}

	public String getCity() {
		return city;
	}

	public void setCity(String city) {
		this.city = city;
	}

	public String getDistrict() {
		return district;
	}

	public void setDistrict(String district) {
		this.district = district;
	}

	public String getProvince() {
		return province;
	}

	public void setProvince(String province) {
		this.province = province;
	}

	public String getStreetAddress() {
		return streetAddress;
	}

	public void setStreetAddress(String streetAddress) {
		this.streetAddress = streetAddress;
	}

	public String getState() {
		return state;
	}

	public void setState(String state) {
		this.state = state;
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public String getLastLoginDate() {
		return lastLoginDate;
	}

	public void setLastLoginDate(String lastLoginDate) {
		this.lastLoginDate = lastLoginDate;
	}

}
接着改造我们的UserDao如下所示:

/**
 *@author linzf
 **/
public interface UserDao extends GenericDao {

    /**
     * 功能描述:根据账号来获取用户信息
     * @param login
     * @return
     */
    User findByLogin(String login);

	
}
接着在sys包底下创建一个service包,并创建UserService.java文件如下所示:

/*
* 类描述:
* @auther linzf
* @create 2017/12/8 0008 
*/
@Service("userService")
@Transactional(rollbackFor={IllegalArgumentException.class})
public class UserService extends GenericService {


    @Autowired
    @SuppressWarnings("SpringJavaAutowiringInspection")
    private UserDao userDao;

    @Override
    protected GenericDao getDao() {
        return userDao;
    }
}

接着改造我们的controller层代码如下:

/*
* 类描述:用户维护controller
* @auther linzf
* @create 2017/9/7 0007
*/
@Controller
@RequestMapping("/user")
public class UserController extends GenericController {

    @Inject
    private UserService userService;
    
    @Override
    protected GenericService getService() {
        return userService;
    }
}

配置好以后我们的整个的效果如下:

基于springboot+bootstrap+mysql+redis搭建一套完整的权限架构【四】【编写基础开发工具】_第3张图片

接着我们重新加载我们的代码并把整个项目运行起来,然后去访问我们的swagger2的目录,你会发现我们已经多了很多的功能了,以后我们有了新的模块的时候我们只需要继承我们的类就可以实现快速的开发了,效果如下:

基于springboot+bootstrap+mysql+redis搭建一套完整的权限架构【四】【编写基础开发工具】_第4张图片

        到此处我们完成了我们的基础开发工具的百分30的开发工作了,因为到这里我们还需要自己去编写我们的dao、service、controller以及mybatis配置文件,这个过程完全是一个干苦力的过程,因此在下一章我们将编写一个工具类来帮我们快速生成以上的代码,该项目的GitHub地址:https://github.com/185594-5-27/csdndemo/tree/base-druid-swagger-tool-one。


上一篇文章地址:基于springboot+bootstrap+mysql+redis搭建一套完整的权限架构【三】【整合swagger2和druid】


下一篇文章地址:基于springboot+bootstrap+mysql+redis搭建一套完整的权限架构【五】【编写基础代码快速生成工具】


QQ交流群:578746866


你可能感兴趣的:(java,spring,boot)