/**
* 根据Request以及Class获取对象
* @throws Exception
* @throws InstantiationException
*/
public static <T extends BaseBean> T createBaseBean(HttpServletRequest request,Class<T> cs) throws Exception{
T t = null;
try
{
t = cs.newInstance();
Method[] methods = cs.getMethods();
JSONObject jsonObject = new JSONObject(getPostParameter(request));
@SuppressWarnings("rawtypes")
Iterator i = jsonObject.keys();
while(i.hasNext()){
String s = (String) i.next();
for(Method method:methods){
if(method.getName().equalsIgnoreCase("set"+s)){
method.invoke(t, jsonObject.getString(s));
}
}
}
}
catch(IOException e)
{
throw new Exception(e.getMessage(),e);
}
catch(Exception e)
{
throw new Exception("Create BaseBean Error",e);
}
return t;
}
/**
* 根据request获取Post参数
* @param request
* @return
* @throws IOException
*/
private static String getPostParameter(HttpServletRequest request) throws IOException{
BufferedInputStream buf = null;
int iContentLen = request.getContentLength();
byte sContent[] = new byte[iContentLen];
String sContent2 = null;
try {
buf = new BufferedInputStream(request.getInputStream());
buf.read(sContent, 0, sContent.length);
sContent2 = new String(sContent,0,iContentLen,"UTF-8");
} catch (IOException e) {
throw new IOException("Parse data error!",e);
} finally
{
try {
buf.close();
} catch (IOException e) {
}
}
return sContent2;
}
* 根据Request以及Class获取对象
* @throws Exception
* @throws InstantiationException
*/
public static <T extends BaseBean> T createBaseBean(HttpServletRequest request,Class<T> cs) throws Exception{
T t = null;
try
{
t = cs.newInstance();
Method[] methods = cs.getMethods();
JSONObject jsonObject = new JSONObject(getPostParameter(request));
@SuppressWarnings("rawtypes")
Iterator i = jsonObject.keys();
while(i.hasNext()){
String s = (String) i.next();
for(Method method:methods){
if(method.getName().equalsIgnoreCase("set"+s)){
method.invoke(t, jsonObject.getString(s));
}
}
}
}
catch(IOException e)
{
throw new Exception(e.getMessage(),e);
}
catch(Exception e)
{
throw new Exception("Create BaseBean Error",e);
}
return t;
}
/**
* 根据request获取Post参数
* @param request
* @return
* @throws IOException
*/
private static String getPostParameter(HttpServletRequest request) throws IOException{
BufferedInputStream buf = null;
int iContentLen = request.getContentLength();
byte sContent[] = new byte[iContentLen];
String sContent2 = null;
try {
buf = new BufferedInputStream(request.getInputStream());
buf.read(sContent, 0, sContent.length);
sContent2 = new String(sContent,0,iContentLen,"UTF-8");
} catch (IOException e) {
throw new IOException("Parse data error!",e);
} finally
{
try {
buf.close();
} catch (IOException e) {
}
}
return sContent2;
}