I need to log all the request parameters in some situations for debug purposes...
I tried using ToStringBuilder.reflectionToString(request), but it still showed memory addresses
Is there any easy way to log request parameters in plain text so that I could do something
logger.info(ToStringBuilder.reflecti开发者_JAVA百科onToString(request)); ?
I also tried logger.info(ToStringBuilder.reflectionToString(request.getParameterMap());
reflectionToString only uses reflection on the object given, to find the attributes to print. The attributes themselves are output using their toString() methods. Neither the request nor the parameter map have the request parameters you are interested in as direct attributes, so reflectionToString fails for you.
I know of no OOTB way to deeply reflection-print an object, in JDK or commons-lang.
What does the simple call
logger.info(request.getParameterMap());
produce for you?
Ah, I see: The parameter values are String arrays, which only print their hashcode.
You might try a helper function like this (disclaimer: uncompiled and untested)
public static String getParameterToString(ServletRequest request){
StringBuilder sb = new StringBuilder("{");
for (Map.Entry<String, String[]> entry : request.getParameterMap().entrySet()){
sb.append(entry.getKey()).append(":");
sb.append(Arrays.toString(entry.getValue())).append(",");
}
if (sb.length() > 1)
sb.setLength(sb.length() - 1);
return sb.append("}").toString();
}
This function is tested
public static String dumpParams(ServletRequest req) {
StringBuilder sb = new StringBuilder();
Set<Map.Entry<String, String[]>> entries = req.getParameterMap().entrySet();
for (Map.Entry<String, String[]> entry : entries) {
sb.append(entry.getKey())
.append(" = ")
.append(Arrays.toString(entry.getValue()))
.append(", ");
}
if (sb.length() > 2)
sb.setLength(sb.length() - 2); //Removes the last comma
return sb.toString();
}
精彩评论