运用类反射机制简化Struts应用程序开发
时间:2011-03-05
1、先定义Action FormBean:
package com.bhsky.webis.system;
import org.apache.struts.action.*;
import javax.servlet.http.*;
public class UsersActionForm extends ActionForm {
private String usr_id;
private String usr_name;
public void setUsr_id(String usr_id) {
this.usr_id = usr_id;
}
public String getUsr_id() {
return usr_id;
}
public String getUsr_memo() {
return usr_memo;
}
public void setUsr_name(String usr_name) {
this.usr_name = usr_name;
}
}
2、编写通用的为ActionFormBean赋值的方法:
//Function: 完成ResultSet对象向ArrayList对象为集合的对象的转化
//Para:sql,指定的查询Sql
//Para:className,Sql相对应得JavaBean/FormBean类的名字
//Return:以类className为一条记录的结果集,
//完成ResultSet对象向ArrayList对象为集合的className对象的转化
public ArrayList Select(String sql,String className){
ArrayList paraList=new ArrayList();
try{
if (conn == null){
Connection();
}
PreparedStatement stmt = conn.prepareStatement(sql);
ResultSet rs = stmt.executeQuery();
String recordValue="";
Object c1=null;
paraList=new ArrayList();
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
while (rs.next()){
c1=Class.forName(className).newInstance();
for (int i=1; i<=columnCount; i++) {
if(rs.getString(rsmd.getColumnName(i))!=null){
recordValue=rs.getString(rsmd.getColumnName(i));
}else{
recordValue="";
}
Method
m=c1.getClass().getMethod(getSetMethodName(rsmd.getColumnName(i)),
new Class[]{recordValue.getClass()});
m.invoke (c1, new Object[]{recordValue});
}
paraList.add(c1);
}
}catch(SQLException ex){
}catch(ClassNotFoundException e){
}catch(NoSuchMethodException e) {
}catch(InvocationTargetException e){
}catch (IllegalAccessException e){
}catch(InstantiationException e){
} finaly{
closeConnection();
return paraList;
}
}
运用类反射机制简化Struts应用程序开发(2)
时间:2011-03-05
3、在JavaBean封装的商业逻辑中调用Select 方法,然后在JSP页面上显示出来:
//Function:取得用户列表
//Para:
//Return:返回用户列表
public ArrayList getUsers(){
ArrayList ret=null;
DatabaseManage db=new DatabaseManage();
String sql=" select usr_id,usr_name "
+" from users " ;
ret=db.Select(sql," com.bhsky. webis.system.UsersActionForm");
return ret;
}
4、在Action的execute方法中调用getUsers()方法:
public ActionForward execute(ActionMapping actionMapping,
ActionForm actionForm, HttpServletRequest request,
HttpServletResponse httpServletResponse)
{
/**@todo: complete the business logic here, this is just a skeleton.*/
UsersActionForm uaf=(UsersActionForm)actionForm;
SystemService ubb=new SystemService
|