unS*_*inn 5 java rest jdbi dropwizard
我想动态过滤JDBI查询.
参数列表通过REST从UI传递,例如
http://localhost/things?foo=bar&baz=taz
http://localhost/things?foo=buz
Run Code Online (Sandbox Code Playgroud)
哪个(笨拙地)构建(Jersey @Context UriInfo :: getQueryParameters - > StringBuilder)是这样的:
WHERE foo=bar AND baz=taz
Run Code Online (Sandbox Code Playgroud)
并传递给JDBI,如下所示:
@UseStringTemplate3StatementLocator
public interface ThingDAO {
@SqlQuery("SELECT * FROM things <where>)
List<Thing> findThingsWhere(@Define("where") String where);
}
Run Code Online (Sandbox Code Playgroud)
据我所知,当前的实现容易受到SQL注入的攻击.我显然可以清理列名而不是值.1
必须有一个更优雅和SQL注入证明的方法来做到这一点.
受让-伯纳德的启发,我想出了这个:
public class WhereClause {
public HashMap<String, String> queryValues; // [<"foo","bar">, <"baz","taz">]
public String preparedString; // "WHERE foo=:foo AND bar=:baz"
}
Run Code Online (Sandbox Code Playgroud)
这是通过自定义 Binder 绑定的BindWhereClause:
@BindingAnnotation(BindWhereClause.WhereClauseBinderFactory.class)
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.PARAMETER})
public @interface BindWhereClause {
class WhereClauseBinderFactory implements BinderFactory {
public Binder build(Annotation annotation) {
return new Binder<BindWhereClause, WhereClause>() {
public void bind(SQLStatement q, BindWhereClause bind, WhereClause clause) {
clause.queryValues
.keySet()
.forEach(s -> q.bind(s, clause.queryValues.get(s)));
}
};
}
}
}
Run Code Online (Sandbox Code Playgroud)
和的组合@Define和@Bind:
@UseStringTemplate3StatementLocator
public interface ThingDAO {
@SqlQuery("SELECT * FROM things <where>")
List<Thing> findThingsWhere(@Define("where") String where,
@BindWhereClause() WhereClause whereClause);
}
Run Code Online (Sandbox Code Playgroud)
这应该是注入证明。(是吗?)
| 归档时间: |
|
| 查看次数: |
3678 次 |
| 最近记录: |