很多人想要这个东西,都说可以Interceptor来自动trim掉输入,但为什么就没有人整出来呢?
既然没人弄,那我就弄一个呗。不过,其实,这个类基本是从’Apache Struts 2 Web Application Development’中抄来的,我另外做了一点修改。
public class TrimInterceptor extends MethodFilterInterceptor {
private List<String> excluded = new ArrayList<String>();
protected String doIntercept(ActionInvocation invocation) throws Exception {
Map<String, Object> parameters = invocation.getInvocationContext().getParameters();
for (String param : parameters.keySet()) {
if (isIncluded(param)) {
String[] vals = (String[]) parameters.get(param);
boolean allNull = true;
for (int i = 0; i < vals.length; i++) {
vals[i] = StringUtils.trimToNull(vals[i]);
allNull = allNull && (vals[i] == null);
}
if(allNull){
parameters.put(param, null);
}
}
}
return invocation.invoke();
}
private boolean isIncluded(String param) {
for (String exclude : excluded) {
if (param.startsWith(exclude)) {
return false;
}
}
return true;
}
public void setExcludedParams(String excludedParams) {
for (String s : StringUtils.split(excludedParams, ",")) {
excluded.add(s.trim());
}
}
}
//struts.xml
<interceptor class="com.xxx.TrimInterceptor" name="trim"/>
....
<interceptor-ref name="servletConfig"/>
<interceptor-ref name="trim"/>
<interceptor-ref name="params"/>