Note: The required jar package two (indispensable): commons-beanutils-1.8.3.jar; commons-logging-1.1.1.jar
Package CN. test1;
Import java. util. date;
Import java. Text. parseexception;
Import java. Text. simpledateformat;
Import java. util. enumeration;
Import java. util. UUID;
Import javax. servlet. http. httpservletrequest;
Import org. Apache. commons. beanutils. beanutils;
Import org. Apache. commons. beanutils. convertutils;
Import org. Apache. commons. beanutils. converter;
// When the form is submitted, the submitted data is added to the bean through reflection.
Public class webutil {
Public static <t> T request2bean (httpservletrequest request, class <t> beanclass ){
T bean;
Try {
// Create a bean that encapsulates data through reflection
Bean = beanclass. newinstance ();
// Add the data in the request to the bean
Enumeration <string> E = request. getparameternames ();
While (E. hasmoreelements ()){
String value = NULL;
Stringbuffer sb = new stringbuffer ();
// Retrieve the field name in the bean
String name = (string) E. nextelement ();
// If it is a multiple-choice box
If ("enjon". Equals (name )){
String [] STR = request. getparametervalues (name );
For (INT I = 0; I <Str. length; I ++ ){
If (I = (Str. Length)-1 ){
SB. append (STR [I]);
} Else {
SB. append (STR [I] + ",");
}
}
Value = sb. tostring ();
} Else {
// Obtain the value of each field
Value = request. getparameter (name );
}
// Assign the value to each field
Beanutils. setproperty (bean, name, value );
}
Return bean;
} Catch (exception e ){
Throw new runtimeexception (E );
}
}
// Register a date Converter
Public static void copybean (Object SRC, object DEST ){
Convertutils. Register (New converter (){
Public object convert (class type, object Value ){
If (value = NULL ){
Return NULL;
}
String STR = (string) value;
If (Str. Trim (). Equals ("")){
Return NULL;
}
Simpledateformat Sm = new simpledateformat ("yyyy-mm-dd ");
Try {
Return SM. parse (STR );
} Catch (exception e ){
Throw new runtimeexception (E );
}
}
}, Date. Class );
Try {
Beanutils. copyproperties (DEST, Src );
} Catch (exception e ){
Throw new runtimeexception (E );
}
}
// Generate a globally unique ID
Public static string generateid (){
Return UUID. randomuuid (). tostring ();
}
}