以Filter截取请求,填充至bean,并将此bean保存至ThreadLocal,在使用时直接从ThreadLocal中获取。
if(beanMethod != null) {
try {
beanMethod.invoke(beanObject, fieldValue);
} catch (IllegalArgumentException ex) {
request.setAttribute("MainErrMsg", "illegal argument for the method " + sb.toString() + " of " + beanName);
this.filterConfig.getServletContext().getRequestDispatcher("/index.jsp").forward(request, response);
return;
} catch (InvocationTargetException ex) {
request.setAttribute("MainErrMsg", beanName + " invoke target exception ");
this.filterConfig.getServletContext().getRequestDispatcher("/index.jsp").forward(request, response);
return;
} catch (IllegalAccessException ex) {
request.setAttribute("MainErrMsg", beanName + " illegal access to " + sb.toString());
this.filterConfig.getServletContext().getRequestDispatcher("/index.jsp").forward(request, response);
return;
}
}
}
Form2BeanUtil.put(beanObject);
Method getAllErrors = null;
try {
getAllErrors = beanClazz.getDeclaredMethod("getAllErrors");
} catch (SecurityException ex) {
System.err.println("Security exception when call getAllErrors()");
} catch (NoSuchMethodException ex) {
System.err.println("No such method named getAllErrors()");
}
if(getAllErrors != null) {
try {
isValid = ((HashMap)getAllErrors.invoke(beanObject)).isEmpty();
} catch (IllegalArgumentException ex) {
System.err.println("Illegal argument for getAllErrors()");
} catch (IllegalAccessException ex) {
System.err.println("Illegal Access to getAllErrors()");
} catch (InvocationTargetException ex) {
System.err.println("Invocation target exception");
}
}
}
if(beanName == null || isValid) {
chain.doFilter(request, response);
} else {
if(beanObject != null) {
request.setAttribute("formbean", beanObject);
}
this.filterConfig.getServletContext().getRequestDispatcher(getRequestURI(request)).forward(request, response);
}
}
/**
* Destroy method for this filter
*
*/
public void destroy() {
}
public String getRequestURI(ServletRequest request) {
String requestURI = ((HttpServletRequest)request).getRequestURI();
String queryString = ((HttpServletRequest)request).getQueryString();
return requestURI + queryString;
}
/**
* Return a String representation of this object.
*/
public String toString() {
if (filterConfig == null) return ("SimpleFilter()");
StringBuffer sb = new StringBuffer("SimpleFilter(");
sb.append(filterConfig);
sb.append(")");
return (sb.toString());
}
}