Code Snippet: Trim all string fields of a bean

You may find it useful where you can’t use Spring MVC’s StringTrimEditor

the trim method

	/**
	 * trim string fields to null. 

	 * Note: only the root string fields are trimmed. string fields of the
	 * bean's composite fields are let alone. 

	 * All reflection related security exceptions are ignored.
	 * 
	 * @param bean
	 */
	public static void trimRootLevelStringFields(Object bean) {
		if (bean == null) {
			return;
		}

		Field[] fields = bean.getClass().getDeclaredFields();
		if (fields == null) {
			return;
		}

		for (Field f : fields) {
			if (f.getType().isPrimitive()) {
				continue;
			}

			if (f.getType().equals(String.class)) {
				try {
					f.setAccessible(true);
					String value = (String) f.get(bean);
					f.set(bean, StringUtils.trimToNull(value));
				} catch (IllegalAccessException e) {
				}

			}
		}
	}


Apply it with all *Manager classes using Spring AOP

@Component
@Aspect
public class ManagerAspect {

	@Before("bean(*Manager)  && execution(public * *(..))")
	public void doAdvice(JoinPoint joinPoint) {	 
		Object[] args = joinPoint.getArgs();
		if (args == null) {
			return;
		}
		for (Object arg : args) {
			if (arg == null) {
				continue;
			}
			// if it is a request object
			if (arg.getClass().getSimpleName().endsWith("Request")) {
				SomeClass.trimRootLevelStringFields(arg);
			}
		}
	}
}

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.