1. in project development, if the framework is not used for data binding and encapsulation, a large amount of code similar to the following may be written:
String value = request. getParameter ("v ");
If (null! = Value ){
Obj. setValue (value );
}
Therefore, it is necessary to automatically inject form information to the data model to meet actual needs.
Implementation Code:
Package com. CRF. model;
Import java. lang. reflect. Method;
Import java. lang. reflect. Type;
Import java. text. ParseException;
Import java. text. SimpleDateFormat;
Import java. util. Date;
Import java. util. Iterator;
Import java. util. Map;
Import javax. servlet. http. HttpServletRequest;
Public class BindRequest
{
// Default date format
Private static final String DATE_FORMAT = "yyyy-MM-dd ";
Private SimpleDateFormat format;
Public BindRequest (String f)
{
Format = new SimpleDateFormat (f );
}
Public BindRequest ()
{
This (DATE_FORMAT );
}
@ SuppressWarnings ("unchecked ")
Public T bindFromRquest (Class Clazz, HttpServletRequest request)
Throws Exception
{
Object instance = clazz. newInstance ();
// Obtain all request parameter information
Map Parameters = request. getParameterMap ();
Iterator It = parameters. keySet (). iterator ();
While (it. hasNext ())
{
// Obtain the name in the form parameter
String key = it. next ();
// Obtain the value in the form parameter
String value = request. getParameter (key );
// Obtain the get Method
Method getMethod = clazz. getDeclaredMethod (this. initGetMethod (key ),
Null );
// Obtain the type returned by the Parameter
Class type = getMethod. getReturnType ();
Method method = clazz. getDeclaredMethod (this. initSetMethod (key ),
Type );
If (type = String. class)
{
Method. invoke (instance, value );
} Else if (type = int. class | type = Integer. class)
{
Method. invoke (instance, Integer. parseInt (value ));
} Else if (type = long. class | type = Long. class)
{
Method. invoke (instance, Long. parseLong (value ));
} Else if (type = float. class | type = Float. class)
{
Method. invoke (instance, Float. parseFloat (value ));
} Else if (type = double. class | type = Double. class)
{
Method. invoke (instance, Double. parseDouble (value ));
} Else if (type = Date. class)
{
Method. invoke (instance, format. parse (value ));
}
}
Return (T) instance;
}
Public String initSetMethod (String field)
{
Return "set" + field. substring (0, 1). toUpperCase () + field. substring (1 );
}
Public String initGetMethod (String field)
{
Return "get" + field. substring (0, 1). toUpperCase () + field. substring (1 );
}
}
This class can meet most of the requirements. If the object contains data or set types, you need to modify the part yourself!