MySQL-代码-orderby排序参数校验-Getter-Setter处理逗号
新建SqlUtil.java
private final static String ORDER_BY_FORMAT = " order by %s ";
private final static String ORDER_BY_EMPTY_BLANK_ONE = " ";
private final static String ORDER_BY_EMPTY_BLANK_TWO = ORDER_BY_EMPTY_BLANK_ONE + ORDER_BY_EMPTY_BLANK_ONE;
private static List<String> ORDER_BY_CHECK = new ArrayList<String>() {
{
add("id");
add("chuangjianshijian");
add("xinwenbiaoti");
add("desc");
add("asc");
}
};
orderBy = checkAndGetOrderBySql(orderBy,"chuangjianshijian desc,id desc");
/**
* order by 入参校验
*
* @param orderBy
* @param defaultOrderBy
* @return
*/
private String checkAndGetOrderBySql(String orderBy, String defaultOrderBy) {
private String checkAndGetOrderBySql(String orderBy, String defaultOrderBy) {
if (StringUtils.isBlank(orderBy)) {
if (StringUtils.isNotBlank(defaultOrderBy)) {
return String.format(ORDER_BY_FORMAT, defaultOrderBy);
}
return Strings.EMPTY;
} else {//创建时间 ,新闻标题 chuangjianshijian desc, xinwenbiaoti desc {2}
while (orderBy.contains(ORDER_BY_EMPTY_BLANK_TWO)) {
orderBy = orderBy.replaceAll(ORDER_BY_EMPTY_BLANK_TWO, ORDER_BY_EMPTY_BLANK_ONE);
}
orderBy = orderBy.toLowerCase().trim();
String[] split = orderBy.replaceAll(ORDER_BY_EMPTY_BLANK_ONE, ",").split(",");
for (String text : split) {
if (StringUtils.isBlank(text)) {
continue;
}
boolean contains = ORDER_BY_CHECK.contains(text);
if (!contains) {
throw new BizzException("该排序参数不被允许:" + text);
}
}
orderBy = String.format(ORDER_BY_FORMAT, orderBy);
}
return orderBy;
}
/**
* 多选情景的字段处理
* 写:前后加上逗号
* @param valueWithoutComma
* @return
*/
public static String handleSetValue(String valueWithoutComma) {
if (StringUtils.isBlank(valueWithoutComma)) {
return valueWithoutComma;
}
if (!valueWithoutComma.startsWith(",")) {
valueWithoutComma = "," + valueWithoutComma;
}
if (!valueWithoutComma.endsWith(",")) {
valueWithoutComma = valueWithoutComma + ",";
}
return valueWithoutComma.replaceAll(",,",",");
}
/**
* 多选情景的字段处理
* 读:把前后的逗号去掉
* @param valueWithComma
* @return
*/
public static String handleGetValue(String valueWithComma) {
if (StringUtils.isBlank(valueWithComma)) {
return valueWithComma;
}
if (valueWithComma.startsWith(",")) {
valueWithComma = valueWithComma.substring(1);
}
if (valueWithComma.endsWith(",")) {
valueWithComma = valueWithComma.substring(0, valueWithComma.length() - 1);
}
return valueWithComma.replaceAll(",,",",");
}
正文到此结束